Ganteng Doang Upload Shell Gak Bisa


Linux server.jmdstrack.com 3.10.0-1160.119.1.el7.tuxcare.els10.x86_64 #1 SMP Fri Oct 11 21:40:41 UTC 2024 x86_64
/ scripts/

//scripts/updatenow.static

#!/usr/local/cpanel/3rdparty/bin/perl
BEGIN { # Suppress load of all of these at earliest point.
    $INC{'HTTP/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'File/Path/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'cPstrict.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Try/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ExceptionMessage.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Fallback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ExceptionMessage/Raw.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadModule/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ScalarUtil.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/CORE.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Context.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Finally.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LocaleString.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Errno.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Constants/Perl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ChildErrorStringifier.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/AdminBinError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/AbstractClass.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/AttributeNotSet.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/AttributeReadOnly.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/System/RequiredRoleDisabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Caller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Caller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/I18N/LangTags.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/I18N/LangTags/Detect.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locale/Maketext.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Normalize.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/Legacy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/DB/LocaleDisplayPattern/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/DB/CharacterOrientation/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/Compile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locale/Maketext/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Paths.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Time/Local.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Fcntl/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Fcntl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Open.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parser/Vars.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Encoder/Tiny/Rare.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Encoder/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Regex.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Carp.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Set.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TimeHiRes.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFileLock.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FHUtils/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Debug.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Hash.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFile/LockInfoCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFile/LockWatcher.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pack.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Syscall.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Inotify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadModule.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Linux/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/FilesystemNodeName.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Notify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Server/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Logger.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/DB/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Readlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Write.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Write/JSON/Lazy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/JSON/Unicode.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadFile/ReadFast.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Encoder/ASCII.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/UTF8/Strict.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/JSON.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AdminBin/Serializer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AdminBin/Serializer/FailOK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Imports.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SSL/KeyTypeLabel.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SSL/DefaultKey/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpUser/Defaults.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Hash/JSONable.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpUser/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ConfigFiles.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SV.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Struct/Common/Time.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Struct/timespec.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NanoStat.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NanoUtime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HiRes.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Path/Normalize.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/JSON/FailOK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Hash/Stringify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Umask.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadWwwAcctConf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Conf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadCpUserFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/HasCpUserFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NSCD/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Socket/UNIX/Micro.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NSCD/Check.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwCache/Helpers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwCache/Cache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwCache/Find.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwCache/Build.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/User.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Cookies.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeDir/Read.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ArrayFunc/Uniq.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Charmap.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/StringFunc/Case.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Legacy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadCpUserFile/CurrentUser.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/YAML/Syck.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/TouchFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PwUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AccessIds/Normalize.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AccessIds/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AccessIds/ReducedPrivileges.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/DataStore.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/StringFunc/Trim.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeDir/MK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/3rdparty.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/JS/Variations.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Destruct.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Uname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Hostname/Fallback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Hostname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Hostname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpConfGuard/CORE.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpConfGuard.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadCpConf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Display.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/Api1.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/SysPerlBootstrap.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Linux.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rhel.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Almalinux.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rhel6.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rhel7.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rhel8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Almalinux8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Centos.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Centos7.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Cloudlinux.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Cloudlinux6.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Cloudlinux7.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Cloudlinux8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Ubuntu.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Ubuntu20.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rocky.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/Rocky8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS/All.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OS.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Lines.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FHUtils/Autoflush.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeRun/Simple.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeRun/Errors.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Timezones.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/DateTime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Time/ISO.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadUserDomains/Count.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Server/Type.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadUserDomains.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpUser.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/FlushConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpUser/Write.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LinkedNode/Worker/Storage.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFile/Replace.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/CpUserGuard.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Utils/User/Modify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Version/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Version/Full.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Version/Compare.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Version.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Collection.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/CommandAlreadyRunning.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ConnectionFailed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ContextError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/SchemaOutdated.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/DatabaseCreationFailed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/DatabaseMissing.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/Error.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/ServerTime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/TableCorruption.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/TableCreationFailed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/TableInsertionFailed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/UserMissing.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/CpuserNotInMap.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/DatabaseCreationInProgress.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/DatabaseNotFound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Database/UserNotFound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/EntryAlreadyExists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DnsEntryAlreadyExists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainAlreadyExists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainDoesNotExist.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainHasUnknownNameservers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainNameNotAllowed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainNameNotRfcCompliant.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainNotRegistered.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/DomainOwnership.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Email/AccountNotFound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/InvalidParameter.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Empty.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/EntryDoesNotExist.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/FeatureNotEnabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/FeaturesNotEnabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ForbiddenInDemoMode.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/FunctionNotImplemented.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/URI/Password.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Base/HasUrl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/HTTP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/HTTP/Network.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/HTTP/Server.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/InvalidCharacters.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/InvalidParameters.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/InvalidUsername.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ErrnoBase.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IOError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/CloseError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ChdirError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ChownError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ChrootError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryCloseError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryCreateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryDeleteError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryOpenError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryReadError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/DirectoryRewindError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ExecError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FcntlError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileCloseError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileCopyError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileNotFound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileOpenError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ReadError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileReadError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileSeekError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileTruncateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/WriteError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileWriteError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FlockError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ForkError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/LinkError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/RenameError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SelectError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SocketOpenError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SocketWriteError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/StatError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SymlinkCreateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SymlinkReadError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/UnlinkError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Socket/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Socket/Micro.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/SocketConnectError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/ChmodError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/IO/FileCreateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/JSONParseError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/MissingMethod.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/MissingParameter.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/MissingParameters.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ModSecurity/DuplicateQueueItem.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ModuleLoadError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Netlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ProcessFailed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ProcessFailed/Error.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ProcessFailed/Signal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ProcessFailed/Timeout.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Reserved.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ReservedSubdomain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/ResourceLimitReached.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/RootProhibited.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/SMTP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/SMTP/FailedRecipient.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/TempCreateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/TempFileCreateError.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Timeout.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/TooManyBytes.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Unsupported.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/UserNotFound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/AccessDeniedToAccount.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/SystemCall.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/Services/Unknown.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/UserdataLookupFailure.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Exception/UpdateNow.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Locale/Context.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeDir/RM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Sources.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/Settings.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Logger.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Merge.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FHUtils/OS.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FHUtils/Blocking.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IO/Flush.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ReadMultipleFH.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ForkAsync.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeRun/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Rand/Get.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Rand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TempFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/Import.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/Import/Temp.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/YAML.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CachedDataStore.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CachedCommand/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PublicSuffix.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HTTP/Tiny/FastSSLVerify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HTTP/Client/Response.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HTTP/Client.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SecureDownload.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/VendorKeys.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Copy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Math.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parallelizer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Link.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/File/YAML.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/AlwaysInstalled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/AnyAllMatcher.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/StatCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FindBin.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CachedCommand/Valid.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CachedCommand/Save.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeRun/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CachedCommand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/GlobalCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IP/Loopback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MysqlUtils/MyCnf/Basic.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Analytics/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Analytics/Enabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/LoadConfig/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/GreyList/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Hulk.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Chkservd/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Chkservd/Config/Drivers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PHPFPM/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ProcessInfo.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PHPFPM/Controller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/LinkTest.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadModule/Name.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoadModule/Custom.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/List.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Server/Type/Profile/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Server/Type/License.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Httpd/EA4.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/DbUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/Installed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/exists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/exists_nofollow.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/More/Lite.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/Enabled/Spamd.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Dovecot/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/Enabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MariaDB.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MysqlUtils/Versions.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileLookup.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AcctUtils/DomainOwner/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Transaction/File/Read/JSON.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Transaction/File/BaseReader.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Transaction/File/JSONReader.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Read.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/EventImportance/Legacy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/EventImportance.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/Providers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/EmailLocalPart.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/WildcardDomain/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/EmailCpanel.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/IP/v4.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/IP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/Domain/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/Domain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/VirtualUsername.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Time/HTTP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Email/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/Email.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Whostmgr/UI.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Whostmgr/Transfers/State.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/Username/Mode.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/Username/Core.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AcctUtils/Domain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/userdata/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AcctUtils/Account.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AcctUtils/Lookup/Webmail.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AcctUtils/Lookup.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sereal/Decoder.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sereal/Encoder.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/JSON/Sanitize.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/UntrustedException.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ForkSync.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pack/Template.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Id.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AccessIds/SetUids.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Setsid/Fast.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/AccessIds.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Reseller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Features/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Team/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Features/Load.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Features/Cpanel.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/App.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Themes/Get.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/EmailRFC.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ContactInfo/Email.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/FilesystemPath.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MultiUserDirStore.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MultiUserDirStore/TimeIndexedData.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MultiUserDirStore/VirtualUser.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MultiUserDirStore/VirtualUser/TimeIndexedData.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/History.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/Directory.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Fuser.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/IO/Callback/Write.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Destruct/DestroyDetector.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IOCallbackWriteLine/Buffer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IOCallbackWriteLine.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Cmd.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/Dpkg.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/DpkgQuery.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parser/DpkgQuery.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeChdir.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/Pkgr/DEB.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Gpg.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Rpm.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/Pkgr/RPM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/Pkgr.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sync/Digest.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/URL.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/OSSys/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Hardware/Memory/Linux.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Hardware/Memory/Vzzo.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Hardware/Memory.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Cpu.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ConfigFiles/RpmVersions.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ArrayFunc/Shuffle.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Alarm.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SocketIP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/UrlTools.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sync/Common.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/URI/Escape/Fast.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Encoder/URI.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HttpTimer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MirrorSearch.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/VendorKeys/TimestampCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Crypt/GPG/VendorKeys/Verify.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/HttpRequest.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Services/Running.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Chdir.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeRun/Full.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Hooks.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/RPM/Versions/File.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Chattr.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Fcntl/Types.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sync/v2.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Mkdir.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/Apt.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/AptCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/AptGet.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/AptKey.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Debian/AptMark.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parser/Line.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parser/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Parser/Callback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/APT/Preferences.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/APT/Preferences/ExcludePackages.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/EA4/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pkgr/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Slurper.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pkgr/Apt.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/RepoQuery.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pkgr/Yum.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Pkgr.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Output.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Output/Terminal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/UTF8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/StringFunc/Fmt.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Output/Formatted.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Output/Formatted/Plain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Output/Formatted/Terminal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/APT.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Yum.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Repos/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/YUM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Binaries/Dnf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs/DNF.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysPkgs.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/EA4/Install.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sysup.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/StateFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SafeFile/FileLocker.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Task.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Processor.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Serializer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Wait/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Scheduler.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Scheduler/DupeSupport.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/PluginManager.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/TaskQueue/Loader.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Logger/Persistent.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoggerAdapter.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LoggerAdapter/Lazy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ServerTasks.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Proc/Bin.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Proc/Basename.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Info.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Sys/Uptime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SysConf/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PsParser/SysInfo.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PsParser/Fallback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PsParser.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Signal/Numbers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Kill.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Signal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/Base.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IP/NonlocalBind/Cache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Validate/IP/Expand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IP/Expand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Linux/Netlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Linux/NetlinkConstants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Linux/RtNetlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IP/Configured.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/IP/Bound.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NAT/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/NAT.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/DIp/MainIP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/CpanelConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/Constants/MySQL.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/MysqlUtils/Version.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/MySQL.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/RemoteMySQL.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LinkedNode/Privileged/Configuration.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LinkedNode/Index.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/LinkedNode/Index/Read.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Data/Result.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/PromiseUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/WorkerNodes.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Version/Compare/Package.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ConfigFiles/Apache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Config/Httpd/Vendor.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/Always.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker/LTS.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Blocker.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Tiers.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Usage.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Update/Now.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/DB/Territory/en.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/CPAN/Locales/DB/Language/en.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SMTP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/SMTP/Singleton.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Email/Send.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/ServiceAuth.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/Provider.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/iContact/Provider/Email.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/FileUtils/Attr.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/chmod.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/chmod_if_exists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/close.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/fcntl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/link.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/open.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/print.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/read.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/readlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/readlink_if_exists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/rename.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/seek.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/stat.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/sysread.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/sysread_sigguard.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/syswrite.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/syswrite_sigguard.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/truncate.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/CORE/unlink_if_exists.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
    $INC{'Cpanel/Autodie/UpdateNow.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
}

{ # --- BEGIN File::Path::Tiny
package File::Path::Tiny;

use strict;
use warnings;
use Cwd qw(cwd chdir);
use Carp ();

$File::Path::Tiny::VERSION = "1.0";

sub mk {
    my ( $path, $mask ) = @_;
    return 2 if -d $path;
    if ( -e $path ) { $! = 20; return; }
    $mask ||= '0777';    # Perl::Critic == Integer with leading zeros at ...
    $mask = oct($mask) if substr( $mask, 0, 1 ) eq '0';
    require File::Spec;
    my ( $vol, $directories ) = File::Spec->splitpath( $path, 1 );
    my @dirs = File::Spec->splitdir($directories);
    my @list;

    while ( my ($_dir) = shift @dirs ) {
        last if not defined $_dir;
        push @list, $_dir;
        next if ( $_dir eq '' );
        my $progressive = File::Spec->catpath( $vol, File::Spec->catdir(@list), '' );
        if ( !-d $progressive ) {
            mkdir( $progressive, $mask ) or -d $progressive or return;
        }
    }
    return 1 if -d $path;
    return;
}

sub rm {
    my ( $path, $fast ) = @_;
    my ( $orig_dev, $orig_ino ) = ( lstat $path )[ 0, 1 ];
    if ( -e _ && !-d _ ) { $! = 20; return; }
    return 2 if !-d _;

    empty_dir( $path, $fast ) or return;
    _bail_if_changed( $path, $orig_dev, $orig_ino );
    rmdir($path) or !-e $path or return;
    return 1;
}

sub empty_dir {
    my ( $path, $fast ) = @_;
    my ( $orig_dev, $orig_ino ) = ( lstat $path )[ 0, 1 ];
    if ( -e _ && !-d _ ) { $! = 20; return; }

    my ( $starting_point, $starting_dev, $starting_ino );
    if ( !$fast ) {
        $starting_point = cwd();
        ( $starting_dev, $starting_ino ) = ( lstat $starting_point )[ 0, 1 ];
        chdir($path) or Carp::croak("Failed to change directory to “$path”: $!");
        $path = '.';
        _bail_if_changed( $path, $orig_dev, $orig_ino );
    }

    opendir( my $dh, $path ) or return;
    my @contents = grep { $_ ne '.' && $_ ne '..' } readdir($dh);
    closedir $dh;
    _bail_if_changed( $path, $orig_dev, $orig_ino );

    require File::Spec if @contents;
    for my $thing (@contents) {
        my $long = File::Spec->catdir( $path, $thing );
        if ( !-l $long && -d _ ) {
            _bail_if_changed( $path, $orig_dev, $orig_ino );
            rm( $long, $fast ) or !-e $long or return;
        }
        else {
            _bail_if_changed( $path, $orig_dev, $orig_ino );
            unlink $long or !-e $long or return;
        }
    }

    _bail_if_changed( $path, $orig_dev, $orig_ino );

    if ( !$fast ) {
        chdir($starting_point) or Carp::croak("Failed to change directory to “$starting_point”: $!");
        _bail_if_changed( ".", $starting_dev, $starting_ino );
    }

    return 1;
}

sub mk_parent {
    my ( $path, $mode ) = @_;
    $path =~ s{/+$}{};

    require File::Spec;
    my ( $v, $d, $f ) = File::Spec->splitpath( $path, 1 );
    my @p = File::Spec->splitdir($d);

    # pop() is probably cheaper here, benchmark? $d = File::Spec->catdir(@p[0--$#p-1]);
    pop @p;
    $d = File::Spec->catdir(@p);

    my $parent = File::Spec->catpath( $v, $d, $f );
    return mk( $parent, $mode );
}

sub _bail_if_changed {
    my ( $path, $orig_dev, $orig_ino ) = @_;

    my ( $cur_dev, $cur_ino ) = ( lstat $path )[ 0, 1 ];

    if ( !defined $cur_dev || !defined $cur_ino ) {
        $cur_dev ||= "undef(path went away?)";
        $cur_ino ||= "undef(path went away?)";
    }
    else {
        $path = Cwd::abs_path($path);
    }

    if ( $orig_dev ne $cur_dev || $orig_ino ne $cur_ino ) {
        local $Carp::CarpLevel += 1;
        Carp::croak("directory $path changed: expected dev=$orig_dev ino=$orig_ino, actual dev=$cur_dev ino=$cur_ino, aborting");
    }
}

1;

} # --- END File::Path::Tiny


{ # --- BEGIN HTTP::Tiny
# vim: ts=4 sts=4 sw=4 et:
package HTTP::Tiny;
use strict;
use warnings;
# ABSTRACT: A small, simple, correct HTTP/1.1 client

our $VERSION = '0.080';

sub _croak { require Carp; Carp::croak(@_) }

#pod =method new
#pod
#pod     $http = HTTP::Tiny->new( %attributes );
#pod
#pod This constructor returns a new HTTP::Tiny object.  Valid attributes include:
#pod
#pod =for :list
#pod * C<agent> — A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If
#pod   C<agent> — ends in a space character, the default user-agent string is
#pod   appended.
#pod * C<cookie_jar> — An instance of L<HTTP::CookieJar> — or equivalent class
#pod   that supports the C<add> and C<cookie_header> methods
#pod * C<default_headers> — A hashref of default headers to apply to requests
#pod * C<local_address> — The local IP address to bind to
#pod * C<keep_alive> — Whether to reuse the last connection (if for the same
#pod   scheme, host and port) (defaults to 1)
#pod * C<max_redirect> — Maximum number of redirects allowed (defaults to 5)
#pod * C<max_size> — Maximum response size in bytes (only when not using a data
#pod   callback).  If defined, requests with responses larger than this will return
#pod   a 599 status code.
#pod * C<http_proxy> — URL of a proxy server to use for HTTP connections
#pod   (default is C<$ENV{http_proxy}> — if set)
#pod * C<https_proxy> — URL of a proxy server to use for HTTPS connections
#pod   (default is C<$ENV{https_proxy}> — if set)
#pod * C<proxy> — URL of a generic proxy server for both HTTP and HTTPS
#pod   connections (default is C<$ENV{all_proxy}> — if set)
#pod * C<no_proxy> — List of domain suffixes that should not be proxied.  Must
#pod   be a comma-separated string or an array reference. (default is
#pod   C<$ENV{no_proxy}> —)
#pod * C<timeout> — Request timeout in seconds (default is 60) If a socket open,
#pod   read or write takes longer than the timeout, the request response status code
#pod   will be 599.
#pod * C<verify_SSL> — A boolean that indicates whether to validate the SSL
#pod   certificate of an C<https> — connection (default is false)
#pod * C<SSL_options> — A hashref of C<SSL_*> — options to pass through to
#pod   L<IO::Socket::SSL>
#pod
#pod An accessor/mutator method exists for each attribute.
#pod
#pod Passing an explicit C<undef> for C<proxy>, C<http_proxy> or C<https_proxy> will
#pod prevent getting the corresponding proxies from the environment.
#pod
#pod Errors during request execution will result in a pseudo-HTTP status code of 599
#pod and a reason of "Internal Exception". The content field in the response will
#pod contain the text of the error.
#pod
#pod The C<keep_alive> parameter enables a persistent connection, but only to a
#pod single destination scheme, host and port.  If any connection-relevant
#pod attributes are modified via accessor, or if the process ID or thread ID change,
#pod the persistent connection will be dropped.  If you want persistent connections
#pod across multiple destinations, use multiple HTTP::Tiny objects.
#pod
#pod See L</SSL SUPPORT> for more on the C<verify_SSL> and C<SSL_options> attributes.
#pod
#pod =cut

my @attributes;
BEGIN {
    @attributes = qw(
        cookie_jar default_headers http_proxy https_proxy keep_alive
        local_address max_redirect max_size proxy no_proxy
        SSL_options verify_SSL
    );
    my %persist_ok = map {; $_ => 1 } qw(
        cookie_jar default_headers max_redirect max_size
    );
    no strict 'refs';
    no warnings 'uninitialized';
    for my $accessor ( @attributes ) {
        *{$accessor} = sub {
            @_ > 1
                ? do {
                    delete $_[0]->{handle} if !$persist_ok{$accessor} && $_[1] ne $_[0]->{$accessor};
                    $_[0]->{$accessor} = $_[1]
                }
                : $_[0]->{$accessor};
        };
    }
}

sub agent {
    my($self, $agent) = @_;
    if( @_ > 1 ){
        $self->{agent} =
            (defined $agent && $agent =~ / $/) ? $agent . $self->_agent : $agent;
    }
    return $self->{agent};
}

sub timeout {
    my ($self, $timeout) = @_;
    if ( @_ > 1 ) {
        $self->{timeout} = $timeout;
        if ($self->{handle}) {
            $self->{handle}->timeout($timeout);
        }
    }
    return $self->{timeout};
}

sub new {
    my($class, %args) = @_;

    my $self = {
        max_redirect => 5,
        timeout      => defined $args{timeout} ? $args{timeout} : 60,
        keep_alive   => 1,
        verify_SSL   => $args{verify_SSL} || $args{verify_ssl} || 0, # no verification by default
        no_proxy     => $ENV{no_proxy},
    };

    bless $self, $class;

    $class->_validate_cookie_jar( $args{cookie_jar} ) if $args{cookie_jar};

    for my $key ( @attributes ) {
        $self->{$key} = $args{$key} if exists $args{$key}
    }

    $self->agent( exists $args{agent} ? $args{agent} : $class->_agent );

    $self->_set_proxies;

    return $self;
}

sub _set_proxies {
    my ($self) = @_;

    # get proxies from %ENV only if not provided; explicit undef will disable
    # getting proxies from the environment

    # generic proxy
    if (! exists $self->{proxy} ) {
        $self->{proxy} = $ENV{all_proxy} || $ENV{ALL_PROXY};
    }

    if ( defined $self->{proxy} ) {
        $self->_split_proxy( 'generic proxy' => $self->{proxy} ); # validate
    }
    else {
        delete $self->{proxy};
    }

    # http proxy
    if (! exists $self->{http_proxy} ) {
        # under CGI, bypass HTTP_PROXY as request sets it from Proxy header
        local $ENV{HTTP_PROXY} = ($ENV{CGI_HTTP_PROXY} || "") if $ENV{REQUEST_METHOD};
        $self->{http_proxy} = $ENV{http_proxy} || $ENV{HTTP_PROXY} || $self->{proxy};
    }

    if ( defined $self->{http_proxy} ) {
        $self->_split_proxy( http_proxy => $self->{http_proxy} ); # validate
        $self->{_has_proxy}{http} = 1;
    }
    else {
        delete $self->{http_proxy};
    }

    # https proxy
    if (! exists $self->{https_proxy} ) {
        $self->{https_proxy} = $ENV{https_proxy} || $ENV{HTTPS_PROXY} || $self->{proxy};
    }

    if ( $self->{https_proxy} ) {
        $self->_split_proxy( https_proxy => $self->{https_proxy} ); # validate
        $self->{_has_proxy}{https} = 1;
    }
    else {
        delete $self->{https_proxy};
    }

    # Split no_proxy to array reference if not provided as such
    unless ( ref $self->{no_proxy} eq 'ARRAY' ) {
        $self->{no_proxy} =
            (defined $self->{no_proxy}) ? [ split /\s*,\s*/, $self->{no_proxy} ] : [];
    }

    return;
}

#pod =method get|head|put|post|patch|delete
#pod
#pod     $response = $http->get($url);
#pod     $response = $http->get($url, \%options);
#pod     $response = $http->head($url);
#pod
#pod These methods are shorthand for calling C<request()> for the given method.  The
#pod URL must have unsafe characters escaped and international domain names encoded.
#pod See C<request()> for valid options and a description of the response.
#pod
#pod The C<success> field of the response will be true if the status code is 2XX.
#pod
#pod =cut

for my $sub_name ( qw/get head put post patch delete/ ) {
    my $req_method = uc $sub_name;
    no strict 'refs';
    eval <<"HERE"; ## no critic
    sub $sub_name {
        my (\$self, \$url, \$args) = \@_;
        \@_ == 2 || (\@_ == 3 && ref \$args eq 'HASH')
        or _croak(q/Usage: \$http->$sub_name(URL, [HASHREF])/ . "\n");
        return \$self->request('$req_method', \$url, \$args || {});
    }
HERE
}

#pod =method post_form
#pod
#pod     $response = $http->post_form($url, $form_data);
#pod     $response = $http->post_form($url, $form_data, \%options);
#pod
#pod This method executes a C<POST> request and sends the key/value pairs from a
#pod form data hash or array reference to the given URL with a C<content-type> of
#pod C<application/x-www-form-urlencoded>.  If data is provided as an array
#pod reference, the order is preserved; if provided as a hash reference, the terms
#pod are sorted on key and value for consistency.  See documentation for the
#pod C<www_form_urlencode> method for details on the encoding.
#pod
#pod The URL must have unsafe characters escaped and international domain names
#pod encoded.  See C<request()> for valid options and a description of the response.
#pod Any C<content-type> header or content in the options hashref will be ignored.
#pod
#pod The C<success> field of the response will be true if the status code is 2XX.
#pod
#pod =cut

sub post_form {
    my ($self, $url, $data, $args) = @_;
    (@_ == 3 || @_ == 4 && ref $args eq 'HASH')
        or _croak(q/Usage: $http->post_form(URL, DATAREF, [HASHREF])/ . "\n");

    my $headers = {};
    while ( my ($key, $value) = each %{$args->{headers} || {}} ) {
        $headers->{lc $key} = $value;
    }
    delete $args->{headers};

    return $self->request('POST', $url, {
            %$args,
            content => $self->www_form_urlencode($data),
            headers => {
                %$headers,
                'content-type' => 'application/x-www-form-urlencoded'
            },
        }
    );
}

#pod =method mirror
#pod
#pod     $response = $http->mirror($url, $file, \%options)
#pod     if ( $response->{success} ) {
#pod         print "$file is up to date\n";
#pod     }
#pod
#pod Executes a C<GET> request for the URL and saves the response body to the file
#pod name provided.  The URL must have unsafe characters escaped and international
#pod domain names encoded.  If the file already exists, the request will include an
#pod C<If-Modified-Since> header with the modification timestamp of the file.  You
#pod may specify a different C<If-Modified-Since> header yourself in the C<<
#pod $options->{headers} >> hash.
#pod
#pod The C<success> field of the response will be true if the status code is 2XX
#pod or if the status code is 304 (unmodified).
#pod
#pod If the file was modified and the server response includes a properly
#pod formatted C<Last-Modified> header, the file modification time will
#pod be updated accordingly.
#pod
#pod =cut

sub mirror {
    my ($self, $url, $file, $args) = @_;
    @_ == 3 || (@_ == 4 && ref $args eq 'HASH')
      or _croak(q/Usage: $http->mirror(URL, FILE, [HASHREF])/ . "\n");

    if ( exists $args->{headers} ) {
        my $headers = {};
        while ( my ($key, $value) = each %{$args->{headers} || {}} ) {
            $headers->{lc $key} = $value;
        }
        $args->{headers} = $headers;
    }

    if ( -e $file and my $mtime = (stat($file))[9] ) {
        $args->{headers}{'if-modified-since'} ||= $self->_http_date($mtime);
    }
    my $tempfile = $file . int(rand(2**31));

    require Fcntl;
    sysopen my $fh, $tempfile, Fcntl::O_CREAT()|Fcntl::O_EXCL()|Fcntl::O_WRONLY()
       or _croak(qq/Error: Could not create temporary file $tempfile for downloading: $!\n/);
    binmode $fh;
    $args->{data_callback} = sub { print {$fh} $_[0] };
    my $response = $self->request('GET', $url, $args);
    close $fh
        or _croak(qq/Error: Caught error closing temporary file $tempfile: $!\n/);

    if ( $response->{success} ) {
        rename $tempfile, $file
            or _croak(qq/Error replacing $file with $tempfile: $!\n/);
        my $lm = $response->{headers}{'last-modified'};
        if ( $lm and my $mtime = $self->_parse_http_date($lm) ) {
            utime $mtime, $mtime, $file;
        }
    }
    $response->{success} ||= $response->{status} eq '304';
    unlink $tempfile;
    return $response;
}

#pod =method request
#pod
#pod     $response = $http->request($method, $url);
#pod     $response = $http->request($method, $url, \%options);
#pod
#pod Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST',
#pod 'PUT', etc.) on the given URL.  The URL must have unsafe characters escaped and
#pod international domain names encoded.
#pod
#pod B<NOTE>: Method names are B<case-sensitive> per the HTTP/1.1 specification.
#pod Don't use C<get> when you really want C<GET>.  See L<LIMITATIONS> for
#pod how this applies to redirection.
#pod
#pod If the URL includes a "user:password" stanza, they will be used for Basic-style
#pod authorization headers.  (Authorization headers will not be included in a
#pod redirected request.) For example:
#pod
#pod     $http->request('GET', 'http://Aladdin:open sesame@example.com/');
#pod
#pod If the "user:password" stanza contains reserved characters, they must
#pod be percent-escaped:
#pod
#pod     $http->request('GET', 'http://john%40example.com:password@example.com/');
#pod
#pod A hashref of options may be appended to modify the request.
#pod
#pod Valid options are:
#pod
#pod =for :list
#pod * C<headers> —
#pod     A hashref containing headers to include with the request.  If the value for
#pod     a header is an array reference, the header will be output multiple times with
#pod     each value in the array.  These headers over-write any default headers.
#pod * C<content> —
#pod     A scalar to include as the body of the request OR a code reference
#pod     that will be called iteratively to produce the body of the request
#pod * C<trailer_callback> —
#pod     A code reference that will be called if it exists to provide a hashref
#pod     of trailing headers (only used with chunked transfer-encoding)
#pod * C<data_callback> —
#pod     A code reference that will be called for each chunks of the response
#pod     body received.
#pod * C<peer> —
#pod     Override host resolution and force all connections to go only to a
#pod     specific peer address, regardless of the URL of the request.  This will
#pod     include any redirections!  This options should be used with extreme
#pod     caution (e.g. debugging or very special circumstances). It can be given as
#pod     either a scalar or a code reference that will receive the hostname and
#pod     whose response will be taken as the address.
#pod
#pod The C<Host> header is generated from the URL in accordance with RFC 2616.  It
#pod is a fatal error to specify C<Host> in the C<headers> option.  Other headers
#pod may be ignored or overwritten if necessary for transport compliance.
#pod
#pod If the C<content> option is a code reference, it will be called iteratively
#pod to provide the content body of the request.  It should return the empty
#pod string or undef when the iterator is exhausted.
#pod
#pod If the C<content> option is the empty string, no C<content-type> or
#pod C<content-length> headers will be generated.
#pod
#pod If the C<data_callback> option is provided, it will be called iteratively until
#pod the entire response body is received.  The first argument will be a string
#pod containing a chunk of the response body, the second argument will be the
#pod in-progress response hash reference, as described below.  (This allows
#pod customizing the action of the callback based on the C<status> or C<headers>
#pod received prior to the content body.)
#pod
#pod The C<request> method returns a hashref containing the response.  The hashref
#pod will have the following keys:
#pod
#pod =for :list
#pod * C<success> —
#pod     Boolean indicating whether the operation returned a 2XX status code
#pod * C<url> —
#pod     URL that provided the response. This is the URL of the request unless
#pod     there were redirections, in which case it is the last URL queried
#pod     in a redirection chain
#pod * C<status> —
#pod     The HTTP status code of the response
#pod * C<reason> —
#pod     The response phrase returned by the server
#pod * C<content> —
#pod     The body of the response.  If the response does not have any content
#pod     or if a data callback is provided to consume the response body,
#pod     this will be the empty string
#pod * C<headers> —
#pod     A hashref of header fields.  All header field names will be normalized
#pod     to be lower case. If a header is repeated, the value will be an arrayref;
#pod     it will otherwise be a scalar string containing the value
#pod * C<protocol> -
#pod     If this field exists, it is the protocol of the response
#pod     such as HTTP/1.0 or HTTP/1.1
#pod * C<redirects>
#pod     If this field exists, it is an arrayref of response hash references from
#pod     redirects in the same order that redirections occurred.  If it does
#pod     not exist, then no redirections occurred.
#pod
#pod On an error during the execution of the request, the C<status> field will
#pod contain 599, and the C<content> field will contain the text of the error.
#pod
#pod =cut

my %idempotent = map { $_ => 1 } qw/GET HEAD PUT DELETE OPTIONS TRACE/;

sub request {
    my ($self, $method, $url, $args) = @_;
    @_ == 3 || (@_ == 4 && ref $args eq 'HASH')
      or _croak(q/Usage: $http->request(METHOD, URL, [HASHREF])/ . "\n");
    $args ||= {}; # we keep some state in this during _request

    # RFC 2616 Section 8.1.4 mandates a single retry on broken socket
    my $response;
    for ( 0 .. 1 ) {
        $response = eval { $self->_request($method, $url, $args) };
        last unless $@ && $idempotent{$method}
            && $@ =~ m{^(?:Socket closed|Unexpected end|SSL read error)};
    }

    if (my $e = $@) {
        # maybe we got a response hash thrown from somewhere deep
        if ( ref $e eq 'HASH' && exists $e->{status} ) {
            $e->{redirects} = delete $args->{_redirects} if @{ $args->{_redirects} || []};
            return $e;
        }

        # otherwise, stringify it
        $e = "$e";
        $response = {
            url     => $url,
            success => q{},
            status  => 599,
            reason  => 'Internal Exception',
            content => $e,
            headers => {
                'content-type'   => 'text/plain',
                'content-length' => length $e,
            },
            ( @{$args->{_redirects} || []} ? (redirects => delete $args->{_redirects}) : () ),
        };
    }
    return $response;
}

#pod =method www_form_urlencode
#pod
#pod     $params = $http->www_form_urlencode( $data );
#pod     $response = $http->get("http://example.com/query?$params");
#pod
#pod This method converts the key/value pairs from a data hash or array reference
#pod into a C<x-www-form-urlencoded> string.  The keys and values from the data
#pod reference will be UTF-8 encoded and escaped per RFC 3986.  If a value is an
#pod array reference, the key will be repeated with each of the values of the array
#pod reference.  If data is provided as a hash reference, the key/value pairs in the
#pod resulting string will be sorted by key and value for consistent ordering.
#pod
#pod =cut

sub www_form_urlencode {
    my ($self, $data) = @_;
    (@_ == 2 && ref $data)
        or _croak(q/Usage: $http->www_form_urlencode(DATAREF)/ . "\n");
    (ref $data eq 'HASH' || ref $data eq 'ARRAY')
        or _croak("form data must be a hash or array reference\n");

    my @params = ref $data eq 'HASH' ? %$data : @$data;
    @params % 2 == 0
        or _croak("form data reference must have an even number of terms\n");

    my @terms;
    while( @params ) {
        my ($key, $value) = splice(@params, 0, 2);
        _croak("form data keys must not be undef")
            if !defined($key);
        if ( ref $value eq 'ARRAY' ) {
            unshift @params, map { $key => $_ } @$value;
        }
        else {
            push @terms, join("=", map { $self->_uri_escape($_) } $key, $value);
        }
    }

    return join("&", (ref $data eq 'ARRAY') ? (@terms) : (sort @terms) );
}

#pod =method can_ssl
#pod
#pod     $ok         = HTTP::Tiny->can_ssl;
#pod     ($ok, $why) = HTTP::Tiny->can_ssl;
#pod     ($ok, $why) = $http->can_ssl;
#pod
#pod Indicates if SSL support is available.  When called as a class object, it
#pod checks for the correct version of L<Net::SSLeay> and L<IO::Socket::SSL>.
#pod When called as an object methods, if C<SSL_verify> is true or if C<SSL_verify_mode>
#pod is set in C<SSL_options>, it checks that a CA file is available.
#pod
#pod In scalar context, returns a boolean indicating if SSL is available.
#pod In list context, returns the boolean and a (possibly multi-line) string of
#pod errors indicating why SSL isn't available.
#pod
#pod =cut

sub can_ssl {
    my ($self) = @_;

    my($ok, $reason) = (1, '');

    # Need IO::Socket::SSL 1.42 for SSL_create_ctx_callback
    local @INC = @INC;
    pop @INC if $INC[-1] eq '.';
    unless (eval {require IO::Socket::SSL; IO::Socket::SSL->VERSION(1.42)}) {
        $ok = 0;
        $reason .= qq/IO::Socket::SSL 1.42 must be installed for https support\n/;
    }

    # Need Net::SSLeay 1.49 for MODE_AUTO_RETRY
    unless (eval {require Net::SSLeay; Net::SSLeay->VERSION(1.49)}) {
        $ok = 0;
        $reason .= qq/Net::SSLeay 1.49 must be installed for https support\n/;
    }

    # If an object, check that SSL config lets us get a CA if necessary
    if ( ref($self) && ( $self->{verify_SSL} || $self->{SSL_options}{SSL_verify_mode} ) ) {
        my $handle = HTTP::Tiny::Handle->new(
            SSL_options => $self->{SSL_options},
            verify_SSL  => $self->{verify_SSL},
        );
        unless ( eval { $handle->_find_CA_file; 1 } ) {
            $ok = 0;
            $reason .= "$@";
        }
    }

    wantarray ? ($ok, $reason) : $ok;
}

#pod =method connected
#pod
#pod     $host = $http->connected;
#pod     ($host, $port) = $http->connected;
#pod
#pod Indicates if a connection to a peer is being kept alive, per the C<keep_alive>
#pod option.
#pod
#pod In scalar context, returns the peer host and port, joined with a colon, or
#pod C<undef> (if no peer is connected).
#pod In list context, returns the peer host and port or an empty list (if no peer
#pod is connected).
#pod
#pod B<Note>: This method cannot reliably be used to discover whether the remote
#pod host has closed its end of the socket.
#pod
#pod =cut

sub connected {
    my ($self) = @_;

    if ( $self->{handle} ) {
        return $self->{handle}->connected;
    }
    return;
}

#--------------------------------------------------------------------------#
# private methods
#--------------------------------------------------------------------------#

my %DefaultPort = (
    http => 80,
    https => 443,
);

sub _agent {
    my $class = ref($_[0]) || $_[0];
    (my $default_agent = $class) =~ s{::}{-}g;
    my $version = $class->VERSION;
    $default_agent .= "/$version" if defined $version;
    return $default_agent;
}

sub _request {
    my ($self, $method, $url, $args) = @_;

    my ($scheme, $host, $port, $path_query, $auth) = $self->_split_url($url);

    if ($scheme ne 'http' && $scheme ne 'https') {
      die(qq/Unsupported URL scheme '$scheme'\n/);
    }

    my $request = {
        method    => $method,
        scheme    => $scheme,
        host      => $host,
        port      => $port,
        host_port => ($port == $DefaultPort{$scheme} ? $host : "$host:$port"),
        uri       => $path_query,
        headers   => {},
    };

    my $peer = $args->{peer} || $host;

    # Allow 'peer' to be a coderef.
    if ('CODE' eq ref $peer) {
        $peer = $peer->($host);
    }

    # We remove the cached handle so it is not reused in the case of redirect.
    # If all is well, it will be recached at the end of _request.  We only
    # reuse for the same scheme, host and port
    my $handle = delete $self->{handle};
    if ( $handle ) {
        unless ( $handle->can_reuse( $scheme, $host, $port, $peer ) ) {
            $handle->close;
            undef $handle;
        }
    }
    $handle ||= $self->_open_handle( $request, $scheme, $host, $port, $peer );

    $self->_prepare_headers_and_cb($request, $args, $url, $auth);
    $handle->write_request($request);

    my $response;
    do { $response = $handle->read_response_header }
        until (substr($response->{status},0,1) ne '1');

    $self->_update_cookie_jar( $url, $response ) if $self->{cookie_jar};
    my @redir_args = $self->_maybe_redirect($request, $response, $args);

    my $known_message_length;
    if ($method eq 'HEAD' || $response->{status} =~ /^[23]04/) {
        # response has no message body
        $known_message_length = 1;
    }
    else {
        # Ignore any data callbacks during redirection.
        my $cb_args = @redir_args ? +{} : $args;
        my $data_cb = $self->_prepare_data_cb($response, $cb_args);
        $known_message_length = $handle->read_body($data_cb, $response);
    }

    if ( $self->{keep_alive}
        && $handle->connected
        && $known_message_length
        && $response->{protocol} eq 'HTTP/1.1'
        && ($response->{headers}{connection} || '') ne 'close'
    ) {
        $self->{handle} = $handle;
    }
    else {
        $handle->close;
    }

    $response->{success} = substr( $response->{status}, 0, 1 ) eq '2';
    $response->{url} = $url;

    # Push the current response onto the stack of redirects if redirecting.
    if (@redir_args) {
        push @{$args->{_redirects}}, $response;
        return $self->_request(@redir_args, $args);
    }

    # Copy the stack of redirects into the response before returning.
    $response->{redirects} = delete $args->{_redirects}
      if @{$args->{_redirects}};
    return $response;
}

sub _open_handle {
    my ($self, $request, $scheme, $host, $port, $peer) = @_;

    my $handle  = HTTP::Tiny::Handle->new(
        timeout         => $self->{timeout},
        SSL_options     => $self->{SSL_options},
        verify_SSL      => $self->{verify_SSL},
        local_address   => $self->{local_address},
        keep_alive      => $self->{keep_alive}
    );

    if ($self->{_has_proxy}{$scheme} && ! grep { $host =~ /\Q$_\E$/ } @{$self->{no_proxy}}) {
        return $self->_proxy_connect( $request, $handle );
    }
    else {
        return $handle->connect($scheme, $host, $port, $peer);
    }
}

sub _proxy_connect {
    my ($self, $request, $handle) = @_;

    my @proxy_vars;
    if ( $request->{scheme} eq 'https' ) {
        _croak(qq{No https_proxy defined}) unless $self->{https_proxy};
        @proxy_vars = $self->_split_proxy( https_proxy => $self->{https_proxy} );
        if ( $proxy_vars[0] eq 'https' ) {
            _croak(qq{Can't proxy https over https: $request->{uri} via $self->{https_proxy}});
        }
    }
    else {
        _croak(qq{No http_proxy defined}) unless $self->{http_proxy};
        @proxy_vars = $self->_split_proxy( http_proxy => $self->{http_proxy} );
    }

    my ($p_scheme, $p_host, $p_port, $p_auth) = @proxy_vars;

    if ( length $p_auth && ! defined $request->{headers}{'proxy-authorization'} ) {
        $self->_add_basic_auth_header( $request, 'proxy-authorization' => $p_auth );
    }

    $handle->connect($p_scheme, $p_host, $p_port, $p_host);

    if ($request->{scheme} eq 'https') {
        $self->_create_proxy_tunnel( $request, $handle );
    }
    else {
        # non-tunneled proxy requires absolute URI
        $request->{uri} = "$request->{scheme}://$request->{host_port}$request->{uri}";
    }

    return $handle;
}

sub _split_proxy {
    my ($self, $type, $proxy) = @_;

    my ($scheme, $host, $port, $path_query, $auth) = eval { $self->_split_url($proxy) };

    unless(
        defined($scheme) && length($scheme) && length($host) && length($port)
        && $path_query eq '/'
    ) {
        _croak(qq{$type URL must be in format http[s]://[auth@]<host>:<port>/\n});
    }

    return ($scheme, $host, $port, $auth);
}

sub _create_proxy_tunnel {
    my ($self, $request, $handle) = @_;

    $handle->_assert_ssl;

    my $agent = exists($request->{headers}{'user-agent'})
        ? $request->{headers}{'user-agent'} : $self->{agent};

    my $connect_request = {
        method    => 'CONNECT',
        uri       => "$request->{host}:$request->{port}",
        headers   => {
            host => "$request->{host}:$request->{port}",
            'user-agent' => $agent,
        }
    };

    if ( $request->{headers}{'proxy-authorization'} ) {
        $connect_request->{headers}{'proxy-authorization'} =
            delete $request->{headers}{'proxy-authorization'};
    }

    $handle->write_request($connect_request);
    my $response;
    do { $response = $handle->read_response_header }
        until (substr($response->{status},0,1) ne '1');

    # if CONNECT failed, throw the response so it will be
    # returned from the original request() method;
    unless (substr($response->{status},0,1) eq '2') {
        die $response;
    }

    # tunnel established, so start SSL handshake
    $handle->start_ssl( $request->{host} );

    return;
}

sub _prepare_headers_and_cb {
    my ($self, $request, $args, $url, $auth) = @_;

    for ($self->{default_headers}, $args->{headers}) {
        next unless defined;
        while (my ($k, $v) = each %$_) {
            $request->{headers}{lc $k} = $v;
            $request->{header_case}{lc $k} = $k;
        }
    }

    if (exists $request->{headers}{'host'}) {
        die(qq/The 'Host' header must not be provided as header option\n/);
    }

    $request->{headers}{'host'}         = $request->{host_port};
    $request->{headers}{'user-agent'} ||= $self->{agent};
    $request->{headers}{'connection'}   = "close"
        unless $self->{keep_alive};

    # Some servers error on an empty-body PUT/POST without a content-length
    if ( $request->{method} eq 'PUT' || $request->{method} eq 'POST' ) {
        if (!defined($args->{content}) || !length($args->{content}) ) {
            $request->{headers}{'content-length'} = 0;
        }
    }

    if ( defined $args->{content} ) {
        if ( ref $args->{content} eq 'CODE' ) {
            if ( exists $request->{'content-length'} && $request->{'content-length'} == 0 ) {
                $request->{cb} = sub { "" };
            }
            else {
                $request->{headers}{'content-type'} ||= "application/octet-stream";
                $request->{headers}{'transfer-encoding'} = 'chunked'
                  unless exists $request->{headers}{'content-length'}
                  || $request->{headers}{'transfer-encoding'};
                $request->{cb} = $args->{content};
            }
        }
        elsif ( length $args->{content} ) {
            my $content = $args->{content};
            if ( $] ge '5.008' ) {
                utf8::downgrade($content, 1)
                    or die(qq/Wide character in request message body\n/);
            }
            $request->{headers}{'content-type'} ||= "application/octet-stream";
            $request->{headers}{'content-length'} = length $content
              unless $request->{headers}{'content-length'}
                  || $request->{headers}{'transfer-encoding'};
            $request->{cb} = sub { substr $content, 0, length $content, '' };
        }
        $request->{trailer_cb} = $args->{trailer_callback}
            if ref $args->{trailer_callback} eq 'CODE';
    }

    ### If we have a cookie jar, then maybe add relevant cookies
    if ( $self->{cookie_jar} ) {
        my $cookies = $self->cookie_jar->cookie_header( $url );
        $request->{headers}{cookie} = $cookies if length $cookies;
    }

    # if we have Basic auth parameters, add them
    if ( length $auth && ! defined $request->{headers}{authorization} ) {
        $self->_add_basic_auth_header( $request, 'authorization' => $auth );
    }

    return;
}

sub _add_basic_auth_header {
    my ($self, $request, $header, $auth) = @_;
    require MIME::Base64;
    $request->{headers}{$header} =
        "Basic " . MIME::Base64::encode_base64($auth, "");
    return;
}

sub _prepare_data_cb {
    my ($self, $response, $args) = @_;
    my $data_cb = $args->{data_callback};
    $response->{content} = '';

    if (!$data_cb || $response->{status} !~ /^2/) {
        if (defined $self->{max_size}) {
            $data_cb = sub {
                $_[1]->{content} .= $_[0];
                die(qq/Size of response body exceeds the maximum allowed of $self->{max_size}\n/)
                  if length $_[1]->{content} > $self->{max_size};
            };
        }
        else {
            $data_cb = sub { $_[1]->{content} .= $_[0] };
        }
    }
    return $data_cb;
}

sub _update_cookie_jar {
    my ($self, $url, $response) = @_;

    my $cookies = $response->{headers}->{'set-cookie'};
    return unless defined $cookies;

    my @cookies = ref $cookies ? @$cookies : $cookies;

    $self->cookie_jar->add( $url, $_ ) for @cookies;

    return;
}

sub _validate_cookie_jar {
    my ($class, $jar) = @_;

    # duck typing
    for my $method ( qw/add cookie_header/ ) {
        _croak(qq/Cookie jar must provide the '$method' method\n/)
            unless ref($jar) && ref($jar)->can($method);
    }

    return;
}

sub _maybe_redirect {
    my ($self, $request, $response, $args) = @_;
    my $headers = $response->{headers};
    my ($status, $method) = ($response->{status}, $request->{method});
    $args->{_redirects} ||= [];

    if (($status eq '303' or ($status =~ /^30[1278]/ && $method =~ /^GET|HEAD$/))
        and $headers->{location}
        and @{$args->{_redirects}} < $self->{max_redirect}
    ) {
        my $location = ($headers->{location} =~ /^\//)
            ? "$request->{scheme}://$request->{host_port}$headers->{location}"
            : $headers->{location} ;
        return (($status eq '303' ? 'GET' : $method), $location);
    }
    return;
}

sub _split_url {
    my $url = pop;

    # URI regex adapted from the URI module
    my ($scheme, $host, $path_query) = $url =~ m<\A([^:/?#]+)://([^/?#]*)([^#]*)>
      or die(qq/Cannot parse URL: '$url'\n/);

    $scheme     = lc $scheme;
    $path_query = "/$path_query" unless $path_query =~ m<\A/>;

    my $auth = '';
    if ( (my $i = index $host, '@') != -1 ) {
        # user:pass@host
        $auth = substr $host, 0, $i, ''; # take up to the @ for auth
        substr $host, 0, 1, '';          # knock the @ off the host

        # userinfo might be percent escaped, so recover real auth info
        $auth =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
    }
    my $port = $host =~ s/:(\d*)\z// && length $1 ? $1
             : $scheme eq 'http'                  ? 80
             : $scheme eq 'https'                 ? 443
             : undef;

    return ($scheme, (length $host ? lc $host : "localhost") , $port, $path_query, $auth);
}

# Date conversions adapted from HTTP::Date
my $DoW = "Sun|Mon|Tue|Wed|Thu|Fri|Sat";
my $MoY = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
sub _http_date {
    my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($_[1]);
    return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
        substr($DoW,$wday*4,3),
        $mday, substr($MoY,$mon*4,3), $year+1900,
        $hour, $min, $sec
    );
}

sub _parse_http_date {
    my ($self, $str) = @_;
    require Time::Local;
    my @tl_parts;
    if ($str =~ /^[SMTWF][a-z]+, +(\d{1,2}) ($MoY) +(\d\d\d\d) +(\d\d):(\d\d):(\d\d) +GMT$/) {
        @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3);
    }
    elsif ($str =~ /^[SMTWF][a-z]+, +(\d\d)-($MoY)-(\d{2,4}) +(\d\d):(\d\d):(\d\d) +GMT$/ ) {
        @tl_parts = ($6, $5, $4, $1, (index($MoY,$2)/4), $3);
    }
    elsif ($str =~ /^[SMTWF][a-z]+ +($MoY) +(\d{1,2}) +(\d\d):(\d\d):(\d\d) +(?:[^0-9]+ +)?(\d\d\d\d)$/ ) {
        @tl_parts = ($5, $4, $3, $2, (index($MoY,$1)/4), $6);
    }
    return eval {
        my $t = @tl_parts ? Time::Local::timegm(@tl_parts) : -1;
        $t < 0 ? undef : $t;
    };
}

# URI escaping adapted from URI::Escape
# c.f. http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
# perl 5.6 ready UTF-8 encoding adapted from JSON::PP
my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255;
$escapes{' '}="+";
my $unsafe_char = qr/[^A-Za-z0-9\-\._~]/;

sub _uri_escape {
    my ($self, $str) = @_;
    return "" if !defined $str;
    if ( $] ge '5.008' ) {
        utf8::encode($str);
    }
    else {
        $str = pack("U*", unpack("C*", $str)) # UTF-8 encode a byte string
            if ( length $str == do { use bytes; length $str } );
        $str = pack("C*", unpack("C*", $str)); # clear UTF-8 flag
    }
    $str =~ s/($unsafe_char)/$escapes{$1}/g;
    return $str;
}

package
    HTTP::Tiny::Handle; # hide from PAUSE/indexers
use strict;
use warnings;

use Errno      qw[EINTR EPIPE];
use IO::Socket qw[SOCK_STREAM];
use Socket     qw[SOL_SOCKET SO_KEEPALIVE];

# PERL_HTTP_TINY_IPV4_ONLY is a private environment variable to force old
# behavior if someone is unable to boostrap CPAN from a new perl install; it is
# not intended for general, per-client use and may be removed in the future
my $SOCKET_CLASS =
    $ENV{PERL_HTTP_TINY_IPV4_ONLY} ? 'IO::Socket::INET' :
    eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.32) } ? 'IO::Socket::IP' :
    'IO::Socket::INET';

sub BUFSIZE () { 32768 } ## no critic

my $Printable = sub {
    local $_ = shift;
    s/\r/\\r/g;
    s/\n/\\n/g;
    s/\t/\\t/g;
    s/([^\x20-\x7E])/sprintf('\\x%.2X', ord($1))/ge;
    $_;
};

my $Token = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/;
my $Field_Content = qr/[[:print:]]+ (?: [\x20\x09]+ [[:print:]]+ )*/x;

sub new {
    my ($class, %args) = @_;
    return bless {
        rbuf             => '',
        timeout          => 60,
        max_line_size    => 16384,
        max_header_lines => 64,
        verify_SSL       => 0,
        SSL_options      => {},
        %args
    }, $class;
}

sub timeout {
    my ($self, $timeout) = @_;
    if ( @_ > 1 ) {
        $self->{timeout} = $timeout;
        if ( $self->{fh} && $self->{fh}->can('timeout') ) {
            $self->{fh}->timeout($timeout);
        }
    }
    return $self->{timeout};
}

sub connect {
    @_ == 5 || die(q/Usage: $handle->connect(scheme, host, port, peer)/ . "\n");
    my ($self, $scheme, $host, $port, $peer) = @_;

    if ( $scheme eq 'https' ) {
        $self->_assert_ssl;
    }

    $self->{fh} = $SOCKET_CLASS->new(
        PeerHost  => $peer,
        PeerPort  => $port,
        $self->{local_address} ?
            ( LocalAddr => $self->{local_address} ) : (),
        Proto     => 'tcp',
        Type      => SOCK_STREAM,
        Timeout   => $self->{timeout},
    ) or die(qq/Could not connect to '$host:$port': $@\n/);

    binmode($self->{fh})
      or die(qq/Could not binmode() socket: '$!'\n/);

    if ( $self->{keep_alive} ) {
        unless ( defined( $self->{fh}->setsockopt( SOL_SOCKET, SO_KEEPALIVE, 1 ) ) ) {
            CORE::close($self->{fh});
            die(qq/Could not set SO_KEEPALIVE on socket: '$!'\n/);
        }
    }

    $self->start_ssl($host) if $scheme eq 'https';

    $self->{scheme} = $scheme;
    $self->{host} = $host;
    $self->{peer} = $peer;
    $self->{port} = $port;
    $self->{pid} = $$;
    $self->{tid} = _get_tid();

    return $self;
}

sub connected {
    my ($self) = @_;
    if ( $self->{fh} && $self->{fh}->connected ) {
        return wantarray
          ? ( $self->{fh}->peerhost, $self->{fh}->peerport )
          : join( ':', $self->{fh}->peerhost, $self->{fh}->peerport );
    }
    return;
}

sub start_ssl {
    my ($self, $host) = @_;

    # As this might be used via CONNECT after an SSL session
    # to a proxy, we shut down any existing SSL before attempting
    # the handshake
    if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
        unless ( $self->{fh}->stop_SSL ) {
            my $ssl_err = IO::Socket::SSL->errstr;
            die(qq/Error halting prior SSL connection: $ssl_err/);
        }
    }

    my $ssl_args = $self->_ssl_args($host);
    IO::Socket::SSL->start_SSL(
        $self->{fh},
        %$ssl_args,
        SSL_create_ctx_callback => sub {
            my $ctx = shift;
            Net::SSLeay::CTX_set_mode($ctx, Net::SSLeay::MODE_AUTO_RETRY());
        },
    );

    unless ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
        my $ssl_err = IO::Socket::SSL->errstr;
        die(qq/SSL connection failed for $host: $ssl_err\n/);
    }
}

sub close {
    @_ == 1 || die(q/Usage: $handle->close()/ . "\n");
    my ($self) = @_;
    CORE::close($self->{fh})
      or die(qq/Could not close socket: '$!'\n/);
}

sub write {
    @_ == 2 || die(q/Usage: $handle->write(buf)/ . "\n");
    my ($self, $buf) = @_;

    if ( $] ge '5.008' ) {
        utf8::downgrade($buf, 1)
            or die(qq/Wide character in write()\n/);
    }

    my $len = length $buf;
    my $off = 0;

    local $SIG{PIPE} = 'IGNORE';

    while () {
        $self->can_write
          or die(qq/Timed out while waiting for socket to become ready for writing\n/);
        my $r = syswrite($self->{fh}, $buf, $len, $off);
        if (defined $r) {
            $len -= $r;
            $off += $r;
            last unless $len > 0;
        }
        elsif ($! == EPIPE) {
            die(qq/Socket closed by remote server: $!\n/);
        }
        elsif ($! != EINTR) {
            if ($self->{fh}->can('errstr')){
                my $err = $self->{fh}->errstr();
                die (qq/Could not write to SSL socket: '$err'\n /);
            }
            else {
                die(qq/Could not write to socket: '$!'\n/);
            }

        }
    }
    return $off;
}

sub read {
    @_ == 2 || @_ == 3 || die(q/Usage: $handle->read(len [, allow_partial])/ . "\n");
    my ($self, $len, $allow_partial) = @_;

    my $buf  = '';
    my $got = length $self->{rbuf};

    if ($got) {
        my $take = ($got < $len) ? $got : $len;
        $buf  = substr($self->{rbuf}, 0, $take, '');
        $len -= $take;
    }

    # Ignore SIGPIPE because SSL reads can result in writes that might error.
    # See "Expecting exactly the same behavior as plain sockets" in
    # https://metacpan.org/dist/IO-Socket-SSL/view/lib/IO/Socket/SSL.pod#Common-Usage-Errors
    local $SIG{PIPE} = 'IGNORE';

    while ($len > 0) {
        $self->can_read
          or die(q/Timed out while waiting for socket to become ready for reading/ . "\n");
        my $r = sysread($self->{fh}, $buf, $len, length $buf);
        if (defined $r) {
            last unless $r;
            $len -= $r;
        }
        elsif ($! != EINTR) {
            if ($self->{fh}->can('errstr')){
                my $err = $self->{fh}->errstr();
                die (qq/Could not read from SSL socket: '$err'\n /);
            }
            else {
                die(qq/Could not read from socket: '$!'\n/);
            }
        }
    }
    if ($len && !$allow_partial) {
        die(qq/Unexpected end of stream\n/);
    }
    return $buf;
}

sub readline {
    @_ == 1 || die(q/Usage: $handle->readline()/ . "\n");
    my ($self) = @_;

    while () {
        if ($self->{rbuf} =~ s/\A ([^\x0D\x0A]* \x0D?\x0A)//x) {
            return $1;
        }
        if (length $self->{rbuf} >= $self->{max_line_size}) {
            die(qq/Line size exceeds the maximum allowed size of $self->{max_line_size}\n/);
        }
        $self->can_read
          or die(qq/Timed out while waiting for socket to become ready for reading\n/);
        my $r = sysread($self->{fh}, $self->{rbuf}, BUFSIZE, length $self->{rbuf});
        if (defined $r) {
            last unless $r;
        }
        elsif ($! != EINTR) {
            if ($self->{fh}->can('errstr')){
                my $err = $self->{fh}->errstr();
                die (qq/Could not read from SSL socket: '$err'\n /);
            }
            else {
                die(qq/Could not read from socket: '$!'\n/);
            }
        }
    }
    die(qq/Unexpected end of stream while looking for line\n/);
}

sub read_header_lines {
    @_ == 1 || @_ == 2 || die(q/Usage: $handle->read_header_lines([headers])/ . "\n");
    my ($self, $headers) = @_;
    $headers ||= {};
    my $lines   = 0;
    my $val;

    while () {
         my $line = $self->readline;

         if (++$lines >= $self->{max_header_lines}) {
             die(qq/Header lines exceeds maximum number allowed of $self->{max_header_lines}\n/);
         }
         elsif ($line =~ /\A ([^\x00-\x1F\x7F:]+) : [\x09\x20]* ([^\x0D\x0A]*)/x) {
             my ($field_name) = lc $1;
             if (exists $headers->{$field_name}) {
                 for ($headers->{$field_name}) {
                     $_ = [$_] unless ref $_ eq "ARRAY";
                     push @$_, $2;
                     $val = \$_->[-1];
                 }
             }
             else {
                 $val = \($headers->{$field_name} = $2);
             }
         }
         elsif ($line =~ /\A [\x09\x20]+ ([^\x0D\x0A]*)/x) {
             $val
               or die(qq/Unexpected header continuation line\n/);
             next unless length $1;
             $$val .= ' ' if length $$val;
             $$val .= $1;
         }
         elsif ($line =~ /\A \x0D?\x0A \z/x) {
            last;
         }
         else {
            die(q/Malformed header line: / . $Printable->($line) . "\n");
         }
    }
    return $headers;
}

sub write_request {
    @_ == 2 || die(q/Usage: $handle->write_request(request)/ . "\n");
    my($self, $request) = @_;
    $self->write_request_header(@{$request}{qw/method uri headers header_case/});
    $self->write_body($request) if $request->{cb};
    return;
}

# Standard request header names/case from HTTP/1.1 RFCs
my @rfc_request_headers = qw(
  Accept Accept-Charset Accept-Encoding Accept-Language Authorization
  Cache-Control Connection Content-Length Expect From Host
  If-Match If-Modified-Since If-None-Match If-Range If-Unmodified-Since
  Max-Forwards Pragma Proxy-Authorization Range Referer TE Trailer
  Transfer-Encoding Upgrade User-Agent Via
);

my @other_request_headers = qw(
  Content-Encoding Content-MD5 Content-Type Cookie DNT Date Origin
  X-XSS-Protection
);

my %HeaderCase = map { lc($_) => $_ } @rfc_request_headers, @other_request_headers;

# to avoid multiple small writes and hence nagle, you can pass the method line or anything else to
# combine writes.
sub write_header_lines {
    (@_ >= 2 && @_ <= 4 && ref $_[1] eq 'HASH') || die(q/Usage: $handle->write_header_lines(headers, [header_case, prefix])/ . "\n");
    my($self, $headers, $header_case, $prefix_data) = @_;
    $header_case ||= {};

    my $buf = (defined $prefix_data ? $prefix_data : '');

    # Per RFC, control fields should be listed first
    my %seen;
    for my $k ( qw/host cache-control expect max-forwards pragma range te/ ) {
        next unless exists $headers->{$k};
        $seen{$k}++;
        my $field_name = $HeaderCase{$k};
        my $v = $headers->{$k};
        for (ref $v eq 'ARRAY' ? @$v : $v) {
            $_ = '' unless defined $_;
            $buf .= "$field_name: $_\x0D\x0A";
        }
    }

    # Other headers sent in arbitrary order
    while (my ($k, $v) = each %$headers) {
        my $field_name = lc $k;
        next if $seen{$field_name};
        if (exists $HeaderCase{$field_name}) {
            $field_name = $HeaderCase{$field_name};
        }
        else {
            if (exists $header_case->{$field_name}) {
                $field_name = $header_case->{$field_name};
            }
            else {
                $field_name =~ s/\b(\w)/\u$1/g;
            }
            $field_name =~ /\A $Token+ \z/xo
              or die(q/Invalid HTTP header field name: / . $Printable->($field_name) . "\n");
            $HeaderCase{lc $field_name} = $field_name;
        }
        for (ref $v eq 'ARRAY' ? @$v : $v) {
            # unwrap a field value if pre-wrapped by user
            s/\x0D?\x0A\s+/ /g;
            die(qq/Invalid HTTP header field value ($field_name): / . $Printable->($_). "\n")
              unless $_ eq '' || /\A $Field_Content \z/xo;
            $_ = '' unless defined $_;
            $buf .= "$field_name: $_\x0D\x0A";
        }
    }
    $buf .= "\x0D\x0A";
    return $self->write($buf);
}

# return value indicates whether message length was defined; this is generally
# true unless there was no content-length header and we just read until EOF.
# Other message length errors are thrown as exceptions
sub read_body {
    @_ == 3 || die(q/Usage: $handle->read_body(callback, response)/ . "\n");
    my ($self, $cb, $response) = @_;
    my $te = $response->{headers}{'transfer-encoding'} || '';
    my $chunked = grep { /chunked/i } ( ref $te eq 'ARRAY' ? @$te : $te ) ;
    return $chunked
        ? $self->read_chunked_body($cb, $response)
        : $self->read_content_body($cb, $response);
}

sub write_body {
    @_ == 2 || die(q/Usage: $handle->write_body(request)/ . "\n");
    my ($self, $request) = @_;
    if (exists $request->{headers}{'content-length'}) {
        return unless $request->{headers}{'content-length'};
        return $self->write_content_body($request);
    }
    else {
        return $self->write_chunked_body($request);
    }
}

sub read_content_body {
    @_ == 3 || @_ == 4 || die(q/Usage: $handle->read_content_body(callback, response, [read_length])/ . "\n");
    my ($self, $cb, $response, $content_length) = @_;
    $content_length ||= $response->{headers}{'content-length'};

    if ( defined $content_length ) {
        my $len = $content_length;
        while ($len > 0) {
            my $read = ($len > BUFSIZE) ? BUFSIZE : $len;
            $cb->($self->read($read, 0), $response);
            $len -= $read;
        }
        return length($self->{rbuf}) == 0;
    }

    my $chunk;
    $cb->($chunk, $response) while length( $chunk = $self->read(BUFSIZE, 1) );

    return;
}

sub write_content_body {
    @_ == 2 || die(q/Usage: $handle->write_content_body(request)/ . "\n");
    my ($self, $request) = @_;

    my ($len, $content_length) = (0, $request->{headers}{'content-length'});
    while () {
        my $data = $request->{cb}->();

        defined $data && length $data
          or last;

        if ( $] ge '5.008' ) {
            utf8::downgrade($data, 1)
                or die(qq/Wide character in write_content()\n/);
        }

        $len += $self->write($data);
    }

    $len == $content_length
      or die(qq/Content-Length mismatch (got: $len expected: $content_length)\n/);

    return $len;
}

sub read_chunked_body {
    @_ == 3 || die(q/Usage: $handle->read_chunked_body(callback, $response)/ . "\n");
    my ($self, $cb, $response) = @_;

    while () {
        my $head = $self->readline;

        $head =~ /\A ([A-Fa-f0-9]+)/x
          or die(q/Malformed chunk head: / . $Printable->($head) . "\n");

        my $len = hex($1)
          or last;

        $self->read_content_body($cb, $response, $len);

        $self->read(2) eq "\x0D\x0A"
          or die(qq/Malformed chunk: missing CRLF after chunk data\n/);
    }
    $self->read_header_lines($response->{headers});
    return 1;
}

sub write_chunked_body {
    @_ == 2 || die(q/Usage: $handle->write_chunked_body(request)/ . "\n");
    my ($self, $request) = @_;

    my $len = 0;
    while () {
        my $data = $request->{cb}->();

        defined $data && length $data
          or last;

        if ( $] ge '5.008' ) {
            utf8::downgrade($data, 1)
                or die(qq/Wide character in write_chunked_body()\n/);
        }

        $len += length $data;

        my $chunk  = sprintf '%X', length $data;
           $chunk .= "\x0D\x0A";
           $chunk .= $data;
           $chunk .= "\x0D\x0A";

        $self->write($chunk);
    }
    $self->write("0\x0D\x0A");
    if ( ref $request->{trailer_cb} eq 'CODE' ) {
        $self->write_header_lines($request->{trailer_cb}->())
    }
    else {
        $self->write("\x0D\x0A");
    }
    return $len;
}

sub read_response_header {
    @_ == 1 || die(q/Usage: $handle->read_response_header()/ . "\n");
    my ($self) = @_;

    my $line = $self->readline;

    $line =~ /\A (HTTP\/(0*\d+\.0*\d+)) [\x09\x20]+ ([0-9]{3}) (?: [\x09\x20]+ ([^\x0D\x0A]*) )? \x0D?\x0A/x
      or die(q/Malformed Status-Line: / . $Printable->($line). "\n");

    my ($protocol, $version, $status, $reason) = ($1, $2, $3, $4);
    $reason = "" unless defined $reason;

    die (qq/Unsupported HTTP protocol: $protocol\n/)
        unless $version =~ /0*1\.0*[01]/;

    return {
        status       => $status,
        reason       => $reason,
        headers      => $self->read_header_lines,
        protocol     => $protocol,
    };
}

sub write_request_header {
    @_ == 5 || die(q/Usage: $handle->write_request_header(method, request_uri, headers, header_case)/ . "\n");
    my ($self, $method, $request_uri, $headers, $header_case) = @_;

    return $self->write_header_lines($headers, $header_case, "$method $request_uri HTTP/1.1\x0D\x0A");
}

sub _do_timeout {
    my ($self, $type, $timeout) = @_;
    $timeout = $self->{timeout}
        unless defined $timeout && $timeout >= 0;

    my $fd = fileno $self->{fh};
    defined $fd && $fd >= 0
      or die(qq/select(2): 'Bad file descriptor'\n/);

    my $initial = time;
    my $pending = $timeout;
    my $nfound;

    vec(my $fdset = '', $fd, 1) = 1;

    while () {
        $nfound = ($type eq 'read')
            ? select($fdset, undef, undef, $pending)
            : select(undef, $fdset, undef, $pending) ;
        if ($nfound == -1) {
            $! == EINTR
              or die(qq/select(2): '$!'\n/);
            redo if !$timeout || ($pending = $timeout - (time - $initial)) > 0;
            $nfound = 0;
        }
        last;
    }
    $! = 0;
    return $nfound;
}

sub can_read {
    @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_read([timeout])/ . "\n");
    my $self = shift;
    if ( ref($self->{fh}) eq 'IO::Socket::SSL' ) {
        return 1 if $self->{fh}->pending;
    }
    return $self->_do_timeout('read', @_)
}

sub can_write {
    @_ == 1 || @_ == 2 || die(q/Usage: $handle->can_write([timeout])/ . "\n");
    my $self = shift;
    return $self->_do_timeout('write', @_)
}

sub _assert_ssl {
    my($ok, $reason) = HTTP::Tiny->can_ssl();
    die $reason unless $ok;
}

sub can_reuse {
    my ($self,$scheme,$host,$port,$peer) = @_;
    return 0 if
        $self->{pid} != $$
        || $self->{tid} != _get_tid()
        || length($self->{rbuf})
        || $scheme ne $self->{scheme}
        || $host ne $self->{host}
        || $port ne $self->{port}
        || $peer ne $self->{peer}
        || eval { $self->can_read(0) }
        || $@ ;
        return 1;
}

# Try to find a CA bundle to validate the SSL cert,
# prefer Mozilla::CA or fallback to a system file
sub _find_CA_file {
    my $self = shift();

    my $ca_file =
      defined( $self->{SSL_options}->{SSL_ca_file} )
      ? $self->{SSL_options}->{SSL_ca_file}
      : $ENV{SSL_CERT_FILE};

    if ( defined $ca_file ) {
        unless ( -r $ca_file ) {
            die qq/SSL_ca_file '$ca_file' not found or not readable\n/;
        }
        return $ca_file;
    }

    local @INC = @INC;
    pop @INC if $INC[-1] eq '.';
    return Mozilla::CA::SSL_ca_file()
        if eval { require Mozilla::CA; 1 };

    # cert list copied from golang src/crypto/x509/root_unix.go
    foreach my $ca_bundle (
        "/etc/ssl/certs/ca-certificates.crt",     # Debian/Ubuntu/Gentoo etc.
        "/etc/pki/tls/certs/ca-bundle.crt",       # Fedora/RHEL
        "/etc/ssl/ca-bundle.pem",                 # OpenSUSE
        "/etc/openssl/certs/ca-certificates.crt", # NetBSD
        "/etc/ssl/cert.pem",                      # OpenBSD
        "/usr/local/share/certs/ca-root-nss.crt", # FreeBSD/DragonFly
        "/etc/pki/tls/cacert.pem",                # OpenELEC
        "/etc/certs/ca-certificates.crt",         # Solaris 11.2+
    ) {
        return $ca_bundle if -e $ca_bundle;
    }

    die qq/Couldn't find a CA bundle with which to verify the SSL certificate.\n/
      . qq/Try installing Mozilla::CA from CPAN\n/;
}

# for thread safety, we need to know thread id if threads are loaded
sub _get_tid {
    no warnings 'reserved'; # for 'threads'
    return threads->can("tid") ? threads->tid : 0;
}

sub _ssl_args {
    my ($self, $host) = @_;

    my %ssl_args;

    # This test reimplements IO::Socket::SSL::can_client_sni(), which wasn't
    # added until IO::Socket::SSL 1.84
    if ( Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x01000000 ) {
        $ssl_args{SSL_hostname} = $host,          # Sane SNI support
    }

    if ($self->{verify_SSL}) {
        $ssl_args{SSL_verifycn_scheme}  = 'http'; # enable CN validation
        $ssl_args{SSL_verifycn_name}    = $host;  # set validation hostname
        $ssl_args{SSL_verify_mode}      = 0x01;   # enable cert validation
        $ssl_args{SSL_ca_file}          = $self->_find_CA_file;
    }
    else {
        $ssl_args{SSL_verifycn_scheme}  = 'none'; # disable CN validation
        $ssl_args{SSL_verify_mode}      = 0x00;   # disable cert validation
    }

    # user options override settings from verify_SSL
    for my $k ( keys %{$self->{SSL_options}} ) {
        $ssl_args{$k} = $self->{SSL_options}{$k} if $k =~ m/^SSL_/;
    }

    return \%ssl_args;
}

1;


} # --- END HTTP::Tiny


{ # --- BEGIN Try::Tiny
package Try::Tiny; # git description: v0.30-11-g1b81d0a
use 5.006;
# ABSTRACT: Minimal try/catch with proper preservation of $@

our $VERSION = '0.31';

use strict;
use warnings;

BEGIN   {
use Exporter 5.57 'import';
our @EXPORT = our @EXPORT_OK = qw(try catch finally);

use Carp;
$Carp::Internal{+__PACKAGE__}++;

  if ($INC{'Sub/Util.pm'} && defined &Sub::Util::set_subname ) {
      *_subname = \&Sub::Util::set_subname;
      *_HAS_SUBNAME = sub {1};
  }
  elsif( $INC{'Sub/Name.pm'} && eval { Sub::Name->VERSION(0.08) } ){
      *_subname = \&Sub::Name::subname;
      *_HAS_SUBNAME = sub {1};
  }
  else {
      *_HAS_SUBNAME = sub {0};
  }
}

my %_finally_guards;

# Need to prototype as @ not $$ because of the way Perl evaluates the prototype.
# Keeping it at $$ means you only ever get 1 sub because we need to eval in a list
# context & not a scalar one

sub try (&;@) {
  my ( $try, @code_refs ) = @_;

  # we need to save this here, the eval block will be in scalar context due
  # to $failed
  my $wantarray = wantarray;

  # work around perl bug by explicitly initializing these, due to the likelyhood
  # this will be used in global destruction (perl rt#119311)
  my ( $catch, @finally ) = ();

  # find labeled blocks in the argument list.
  # catch and finally tag the blocks by blessing a scalar reference to them.
  foreach my $code_ref (@code_refs) {

    if ( ref($code_ref) eq 'Try::Tiny::Catch' ) {
      croak 'A try() may not be followed by multiple catch() blocks'
        if $catch;
      $catch = ${$code_ref};
    } elsif ( ref($code_ref) eq 'Try::Tiny::Finally' ) {
      push @finally, ${$code_ref};
    } else {
      croak(
        'try() encountered an unexpected argument ('
      . ( defined $code_ref ? $code_ref : 'undef' )
      . ') - perhaps a missing semi-colon before or'
      );
    }
  }

  # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's
  # not perfect, but we could provide a list of additional errors for
  # $catch->();

  # name the blocks if we have Sub::Name installed
  _subname(caller().'::try {...} ' => $try)
    if _HAS_SUBNAME;

  # set up scope guards to invoke the finally blocks at the end.
  # this should really be a function scope lexical variable instead of
  # file scope + local but that causes issues with perls < 5.20 due to
  # perl rt#119311
  local $_finally_guards{guards} = [
    map Try::Tiny::ScopeGuard->_new($_),
    @finally
  ];

  # save the value of $@ so we can set $@ back to it in the beginning of the eval
  # and restore $@ after the eval finishes
  my $prev_error = $@;

  my ( @ret, $error );

  # failed will be true if the eval dies, because 1 will not be returned
  # from the eval body
  my $failed = not eval {
    $@ = $prev_error;

    # evaluate the try block in the correct context
    if ( $wantarray ) {
      @ret = $try->();
    } elsif ( defined $wantarray ) {
      $ret[0] = $try->();
    } else {
      $try->();
    };

    return 1; # properly set $failed to false
  };

  # preserve the current error and reset the original value of $@
  $error = $@;
  $@ = $prev_error;

  # at this point $failed contains a true value if the eval died, even if some
  # destructor overwrote $@ as the eval was unwinding.
  if ( $failed ) {
    # pass $error to the finally blocks
    push @$_, $error for @{$_finally_guards{guards}};

    # if we got an error, invoke the catch block.
    if ( $catch ) {
      # This works like given($error), but is backwards compatible and
      # sets $_ in the dynamic scope for the body of C<$catch>
      for ($error) {
        return $catch->($error);
      }

      # in case when() was used without an explicit return, the C<for>
      # loop will be aborted and there's no useful return value
    }

    return;
  } else {
    # no failure, $@ is back to what it was, everything is fine
    return $wantarray ? @ret : $ret[0];
  }
}

sub catch (&;@) {
  my ( $block, @rest ) = @_;

  croak 'Useless bare catch()' unless wantarray;

  _subname(caller().'::catch {...} ' => $block)
    if _HAS_SUBNAME;
  return (
    bless(\$block, 'Try::Tiny::Catch'),
    @rest,
  );
}

sub finally (&;@) {
  my ( $block, @rest ) = @_;

  croak 'Useless bare finally()' unless wantarray;

  _subname(caller().'::finally {...} ' => $block)
    if _HAS_SUBNAME;
  return (
    bless(\$block, 'Try::Tiny::Finally'),
    @rest,
  );
}

{
  package # hide from PAUSE
    Try::Tiny::ScopeGuard;

  use constant UNSTABLE_DOLLARAT => ("$]" < '5.013002') ? 1 : 0;

  sub _new {
    shift;
    bless [ @_ ];
  }

  sub DESTROY {
    my ($code, @args) = @{ $_[0] };

    local $@ if UNSTABLE_DOLLARAT;
    eval {
      $code->(@args);
      1;
    } or do {
      warn
        "Execution of finally() block $code resulted in an exception, which "
      . '*CAN NOT BE PROPAGATED* due to fundamental limitations of Perl. '
      . 'Your program will continue as if this event never took place. '
      . "Original exception text follows:\n\n"
      . (defined $@ ? $@ : '$@ left undefined...')
      . "\n"
      ;
    }
  }
}

1;

} # --- END Try::Tiny


{ # --- BEGIN cPstrict
package cPstrict;

# cpanel - cPstrict.pm                             Copyright 2022 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

use strict;
use warnings;

=pod

This is importing the following to your namespace

    use strict;
    use warnings;
    use v5.30;

    use feature 'signatures';
    no warnings 'experimental::signatures';

=cut

sub import {

    # auto import strict and warnings to our caller

    warnings->import();
    strict->import();

    require feature;
    feature->import( ':5.30', 'signatures' );
    warnings->unimport('experimental::signatures');

    return;
}

1;

} # --- END cPstrict


{ # --- BEGIN Cpanel/ExceptionMessage.pm
package Cpanel::ExceptionMessage;


use strict;
# use Cpanel::Exception ();

*load_perl_module = \&Cpanel::Exception::load_perl_module;

1;

} # --- END Cpanel/ExceptionMessage.pm


{ # --- BEGIN Cpanel/Locale/Utils/Fallback.pm
package Cpanel::Locale::Utils::Fallback;


use strict;
use warnings;




sub interpolate_variables {
    my ( $str, @maketext_opts ) = @_;

    my $c = 1;
    my %h = map { $c++, $_ } @maketext_opts;
    $str =~ s{(\[(?:[^_]+,)?_([0-9])+\])}{$h{$2}}g;
    return $str;
}

1;

} # --- END Cpanel/Locale/Utils/Fallback.pm


{ # --- BEGIN Cpanel/ExceptionMessage/Raw.pm
package Cpanel::ExceptionMessage::Raw;



use strict;
use warnings;

# use Cpanel::ExceptionMessage();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::ExceptionMessage); }

# use Cpanel::Locale::Utils::Fallback ();

sub new {
    my ( $class, $str ) = @_;

    my $str_copy = $str;

    return bless( \$str_copy, $class );
}

sub to_string {
    my ($self) = @_;

    return $$self;
}

sub get_language_tag {
    return 'en';
}

BEGIN {
    *Cpanel::ExceptionMessage::Raw::convert_localized_to_raw = *Cpanel::Locale::Utils::Fallback::interpolate_variables;
    *Cpanel::ExceptionMessage::Raw::to_locale_string         = *Cpanel::ExceptionMessage::Raw::to_string;
    *Cpanel::ExceptionMessage::Raw::to_en_string             = *Cpanel::ExceptionMessage::Raw::to_string;
}
1;

} # --- END Cpanel/ExceptionMessage/Raw.pm


{ # --- BEGIN Cpanel/LoadModule/Utils.pm
package Cpanel::LoadModule::Utils;


use strict;
use warnings;



sub module_is_loaded {
    my $p = module_path( $_[0] );
    return 0 unless defined $p;

    return defined $INC{$p} ? 1 : 0;
}

sub module_path {
    my ($module_name) = @_;

    if ( defined $module_name && length($module_name) ) {
        substr( $module_name, index( $module_name, '::' ), 2, '/' ) while index( $module_name, '::' ) > -1;
        $module_name .= '.pm' unless substr( $module_name, -3 ) eq '.pm';
    }

    return $module_name;
}

sub is_valid_module_name {
    return $_[0] =~ m/\A[A-Za-z_]\w*(?:(?:'|::)\w+)*\z/ ? 1 : 0;
}

1;

} # --- END Cpanel/LoadModule/Utils.pm


{ # --- BEGIN Cpanel/ScalarUtil.pm
package Cpanel::ScalarUtil;


use strict;
use warnings;




sub blessed {
    return ref( $_[0] ) && UNIVERSAL::isa( $_[0], 'UNIVERSAL' ) || undef;
}

1;

} # --- END Cpanel/ScalarUtil.pm


{ # --- BEGIN Cpanel/Exception/CORE.pm
package Cpanel::Exception::CORE;


1;

package Cpanel::Exception;

use strict;


BEGIN {
    $INC{'Cpanel/Exception.pm'} = '__BYPASSED__';
}

our $_SUPPRESS_STACK_TRACES = 0;

our $_EXCEPTION_MODULE_PREFIX = 'Cpanel::Exception';
our $IN_EXCEPTION_CREATION    = 0;

our $_suppressed_msg = '__STACK_TRACE_SUPPRESSED__YOU_SHOULD_NEVER_SEE_THIS_MESSAGE__';

my $PACKAGE = 'Cpanel::Exception';
my $locale;

my @ID_CHARS = qw( a b c d e f g h j k m n p q r s t u v w x y z 2 3 4 5 6 7 8 9 );

my $ID_LENGTH = 6;


# use Cpanel::ExceptionMessage::Raw ();
# use Cpanel::LoadModule::Utils     ();

use constant _TRUE => 1;

use overload (
    '""'     => \&__spew,
    bool     => \&_TRUE,
    fallback => 1,
);

BEGIN {
    die "Cannot compile Cpanel::Exception::CORE" if $INC{'B/C.pm'} && $0 !~ m{cpkeyclt|cpsrvd\.so|t/large};
}

sub _init { return 1 }    # legacy


sub create {
    my ( $exception_type, @args ) = @_;

    _init();

    if ($IN_EXCEPTION_CREATION) {
        _load_cpanel_carp();
        die 'Cpanel::Carp'->can('safe_longmess')->("Attempted to create a “$exception_type” exception with arguments “@args” while creating exception “$IN_EXCEPTION_CREATION->[0]” with arguments “@{$IN_EXCEPTION_CREATION->[1]}”.");
    }
    local $IN_EXCEPTION_CREATION = [ $exception_type, \@args ];

    if ( $exception_type !~ m/\A[A-Za-z0-9_]+(?:\:\:[A-Za-z0-9_]+)*\z/ ) {
        die "Invalid exception type: $exception_type";
    }

    my $perl_class;
    if ( $exception_type eq __PACKAGE__ ) {
        $perl_class = $exception_type;
    }
    else {
        $perl_class = "${_EXCEPTION_MODULE_PREFIX}::$exception_type";
    }

    _load_perl_module($perl_class) unless $perl_class->can('new');

    if ( $args[0] && ref $args[0] eq 'ARRAY' && scalar @{ $args[0] } > 1 ) {
        $args[0] = { @{ $args[0] } };
    }

    return $perl_class->new(@args);
}


sub create_raw {
    my ( $class, $msg, @extra_args ) = @_;

    _init();

    my $msg_obj = 'Cpanel::ExceptionMessage::Raw'->new($msg);

    if ( $class =~ m<\A(?:\Q${_EXCEPTION_MODULE_PREFIX}::\E)?Collection\z> ) {
        die "Use create('Collection', ..) to create a Cpanel::Exception::Collection object.";
    }

    return create( $class, $msg_obj, @extra_args );
}

sub _load_perl_module {
    my ($module) = @_;

    local ( $!, $@ );

    if ( !defined $module ) {
        die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("load_perl_module requires a module name.") );
    }

    return 1 if Cpanel::LoadModule::Utils::module_is_loaded($module);

    my $module_name = $module;
    $module_name =~ s{\.pm$}{};

    if ( !Cpanel::LoadModule::Utils::is_valid_module_name($module_name) ) {
        die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("load_perl_module requires a valid module name: '$module_name'.") );
    }

    {
        eval qq{use $module (); 1 }
          or die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("load_perl_module cannot load '$module_name': $@") )
    }

    return 1;
}

sub new {
    my ( $class, @args ) = @_;

    @args = grep { defined } @args;

    my $self = {};

    bless $self, $class;

    if ( ref $args[-1] eq 'HASH' ) {
        $self->{'_metadata'} = pop @args;
    }

    if ( defined $self->{'_metadata'}->{'longmess'} ) {
        $self->{'_longmess'} = &{ $self->{'_metadata'}->{'longmess'} }($self)
          if $self->{'_metadata'}->{'longmess'};
    }
    elsif ($_SUPPRESS_STACK_TRACES) {
        $self->{'_longmess'} = $_suppressed_msg;
    }
    else {
        if ( !$INC{'Carp.pm'} ) { _load_carp(); }
        $self->{'_longmess'} = scalar do {

            local $Carp::CarpInternal{'Cpanel::Exception'} = 1;
            local $Carp::CarpInternal{$class} = 1;

            'Carp'->can('longmess')->();
        };
    }

    _init();

    $self->{'_auxiliaries'} = [];

    if ( UNIVERSAL::isa( $args[0], 'Cpanel::ExceptionMessage' ) ) {
        $self->{'_message'} = shift @args;
    }
    else {
        my @mt_args;

        if ( @args && !ref $args[0] ) {
            @mt_args = ( shift @args );

            if ( ref $args[0] eq 'ARRAY' ) {
                push @mt_args, @{ $args[0] };
            }
        }
        else {

            $self->{'_orig_mt_args'} = $args[0];

            my $phrase = $self->_default_phrase( $args[0] );

            if ($phrase) {

                if ( ref $phrase ) {
                    @mt_args = $phrase->to_list();
                }

                else {
                    $self->{'_message'} = Cpanel::ExceptionMessage::Raw->new($phrase);
                    return $self;
                }
            }
        }

        if ( my @extras = grep { !ref } @args ) {
            die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("Extra scalar(s) passed to $PACKAGE! (@extras)") );
        }

        if ( !length $mt_args[0] ) {
            die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("No args passed to $PACKAGE constructor!") );
        }

        $self->{'_mt_args'} = \@mt_args;
    }

    return $self;
}



sub get_string {
    my ( $exc, $no_id_yn ) = @_;

    return get_string_no_id($exc) if $no_id_yn;

    return _get_string( $exc, 'to_string' );
}


sub get_string_no_id {
    my ($exc) = @_;

    return _get_string( $exc, 'to_string_no_id' );
}

sub _get_string {
    my ( $exc, $cp_exc_stringifier_name ) = @_;

    return $exc if !ref $exc;

    {
        local $@;
        my $ret = eval { $exc->$cp_exc_stringifier_name() };
        return $ret if defined $ret && !$@ && !ref $ret;
    }

    if ( ref $exc eq 'HASH' && $exc->{'message'} ) {
        return $exc->{'message'};
    }

    if ( $INC{'Cpanel/YAML.pm'} ) {
        local $@;
        my $ret = eval { 'Cpanel::YAML'->can('Dump')->($exc); };
        return $ret if defined $ret && !$@;
    }

    if ( $INC{'Cpanel/JSON.pm'} ) {
        local $@;
        my $ret = eval { 'Cpanel::JSON'->can('Dump')->($exc); };
        return $ret if defined $ret && !$@;
    }

    return $exc;
}


sub _create_id {

    srand();

    return join(
        q<>,
        map { $ID_CHARS[ int rand( 0 + @ID_CHARS ) ]; } ( 1 .. $ID_LENGTH ),
    );
}

sub get_stack_trace_suppressor {
    return Cpanel::Exception::_StackTraceSuppression->new();
}



sub set_id {
    my ( $self, $new_id ) = @_;
    $self->{'_id'} = $new_id;
    return $self;
}


sub id {
    my ($self) = @_;

    return $self->{'_id'} ||= _create_id();
}


sub set {
    my ( $self, $key ) = @_;

    $self->{'_metadata'}{$key} = $_[2];

    if ( exists $self->{'_orig_mt_args'} ) {
        my $phrase = $self->_default_phrase( $self->{'_orig_mt_args'} );

        if ($phrase) {
            if ( ref $phrase ) {
                $self->{'_mt_args'} = [ $phrase->to_list() ];
                undef $self->{'_message'};
            }
            else {
                $self->{'_message'} = Cpanel::ExceptionMessage::Raw->new($phrase);
            }
        }
    }

    return $self;
}


sub get {
    my ( $self, $key ) = @_;

    my $v = $self->{'_metadata'}{$key};

    if ( my $reftype = ref $v ) {
        local $@;
        if ( $reftype eq 'HASH' ) {
            $v = { %{$v} };    # shallow copy
        }
        elsif ( $reftype eq 'ARRAY' ) {
            $v = [ @{$v} ];    # shallow copy
        }
        elsif ( $reftype eq 'SCALAR' ) {
            $v = \${$v};       # shallow copy
        }
        else {
            local ( $@, $! );
            require Cpanel::ScalarUtil;

            if ( $reftype ne 'GLOB' && !Cpanel::ScalarUtil::blessed($v) ) {

                warn if !eval {
                    _load_perl_module('Clone') if !$INC{'Clone.pm'};
                    $v = 'Clone'->can('clone')->($v);
                };
            }
        }
    }

    return $v;
}


sub get_all_metadata {
    my $self = shift;
    my %metadata_copy;
    for my $key ( keys %{ $self->{'_metadata'} } ) {
        $metadata_copy{$key} = $self->get($key);
    }
    return \%metadata_copy;
}

my $loaded_LocaleString;

sub _require_LocaleString {
    return $loaded_LocaleString ||= do {
        local $@;
        eval 'require Cpanel::LocaleString; 1;' or die $@;    ## no critic qw(BuiltinFunctions::ProhibitStringyEval) -  # PPI NO PARSE - load on demand
        1;
    };
}

my $loaded_ExceptionMessage_Locale;

sub _require_ExceptionMessage_Locale {
    return $loaded_ExceptionMessage_Locale ||= do {
        local $@;
        eval 'require Cpanel::ExceptionMessage::Locale; 1;' or die $@;    ## no critic qw(BuiltinFunctions::ProhibitStringyEval) - # PPI NO PARSE - load on demand
        1;
    };
}

sub _default_phrase {
    _require_LocaleString();
    return 'Cpanel::LocaleString'->new( 'An unknown error in the “[_1]” package has occurred.', scalar ref $_[0] );    # PPI NO PARSE - loaded above
}


sub longmess {
    my ($self) = @_;

    return ''           if $self->{'_longmess'} eq $_suppressed_msg;
    _load_cpanel_carp() if !$INC{'Cpanel/Carp.pm'};
    return Cpanel::Carp::sanitize_longmess( $self->{'_longmess'} );
}


sub to_string {
    my ($self) = @_;

    return _apply_id_prefix( $self->id(), $self->to_string_no_id() );
}

sub to_string_no_id {
    my ($self) = @_;

    my $string = $self->to_locale_string_no_id();

    if ( $self->_message()->get_language_tag() ne 'en' ) {
        my $en_string = $self->to_en_string_no_id();
        $string .= "\n$en_string" if ( $en_string ne $string );
    }

    return $string;
}

sub _apply_id_prefix {
    my ( $id, $msg ) = @_;

    return sprintf "(XID %s) %s", $id, $msg;
}


sub to_en_string {
    my ($self) = @_;

    return _apply_id_prefix( $self->id(), $self->to_en_string_no_id() );
}

sub to_en_string_no_id {
    my ($self) = @_;

    return $self->_message()->to_en_string() . $self->_stringify_auxiliaries('to_en_string');
}


sub to_locale_string {
    my ($self) = @_;

    return _apply_id_prefix( $self->id(), $self->to_locale_string_no_id() );
}

sub to_locale_string_no_id {
    my ($self) = @_;

    return $self->_message()->to_locale_string() . $self->_stringify_auxiliaries('to_locale_string');
}


sub add_auxiliary_exception {
    my ( $self, $aux ) = @_;

    return push @{ $self->{'_auxiliaries'} }, $aux;
}


sub get_auxiliary_exceptions {
    my ($self) = @_;

    die 'List context only!' if !wantarray;    #Can’t use Cpanel::Context

    return @{ $self->{'_auxiliaries'} };
}

sub __spew {
    my ($self) = @_;

    return $self->_spew();
}

sub _spew {
    my ($self) = @_;

    return ref($self) . '/' . join "\n", $self->to_string() || '<no message>', $self->longmess() || ();
}

sub _stringify_auxiliaries {
    my ( $self, $method ) = @_;

    my @lines;

    if ( @{ $self->{'_auxiliaries'} } ) {

        local $@;

        _require_LocaleString();

        my $intro = 'Cpanel::LocaleString'->new( 'The following additional [numerate,_1,error,errors] occurred:', 0 + @{ $self->{'_auxiliaries'} } );    # PPI NO PARSE - required above

        if ( $method eq 'to_locale_string' ) {
            push @lines, _locale()->makevar( $intro->to_list() );
        }
        elsif ( $method eq 'to_en_string' ) {
            push @lines, _locale()->makethis_base( $intro->to_list() );
        }
        else {
            die "Invalid method: $method";
        }

        push @lines, map { UNIVERSAL::isa( $_, __PACKAGE__ ) ? $_->$method() : $_ } @{ $self->{'_auxiliaries'} };
    }

    return join q<>, map { "\n$_" } @lines;
}

*TO_JSON = \&to_string;

sub _locale {
    return $locale ||= do {

        local $@;

        eval 'require Cpanel::Locale; 1;' or die $@;

        'Cpanel::Locale'->get_handle();    # hide from perlcc
    };
}

sub _reset_locale {
    return undef $locale;
}

sub _load_carp {
    if ( !$INC{'Carp.pm'} ) {

        local $@;
        eval 'require Carp; 1;' or die $@;    ## no critic qw(BuiltinFunctions::ProhibitStringyEval) -- hide from perlcc
    }

    return;
}

sub _load_cpanel_carp {
    if ( !$INC{'Cpanel/Carp.pm'} ) {

        local $@;
        eval 'require Cpanel::Carp; 1;' or die $@;    ## no critic qw(BuiltinFunctions::ProhibitStringyEval) -- hide from perlcc
    }

    return;
}

sub _message {
    my ($self) = @_;

    return $self->{'_message'} if $self->{'_message'};

    local $!;
    if ($Cpanel::Exception::LOCALIZE_STRINGS) {    # the default
        _require_ExceptionMessage_Locale();
        return ( $self->{'_message'} ||= 'Cpanel::ExceptionMessage::Locale'->new( @{ $self->{'_mt_args'} } ) );    # PPI NO PARSE - required above
    }

    return ( $self->{'_message'} ||= Cpanel::ExceptionMessage::Raw->new( Cpanel::ExceptionMessage::Raw::convert_localized_to_raw( @{ $self->{'_mt_args'} } ) ) );
}


package Cpanel::Exception::_StackTraceSuppression;

sub new {
    my ($class) = @_;

    $Cpanel::Exception::_SUPPRESS_STACK_TRACES++;

    return bless [], $class;
}

sub DESTROY {
    $Cpanel::Exception::_SUPPRESS_STACK_TRACES--;
    return;
}

1;

} # --- END Cpanel/Exception/CORE.pm


{ # --- BEGIN Cpanel/Context.pm
package Cpanel::Context;


use strict;
use warnings;

# use Cpanel::Exception ();

sub must_be_list {
    return 1 if ( caller(1) )[5];    # 5 = wantarray
    my $msg = ( caller(1) )[3];      # 3 = subroutine
    $msg .= $_[0] if defined $_[0];
    return _die_context( 'list', $msg );
}

sub must_not_be_scalar {
    my ($message) = @_;

    my $wa = ( caller(1) )[5];       # 5 = wantarray

    if ( !$wa && defined $wa ) {
        _die_context( 'list or void', $message );
    }

    return 1;
}

sub must_not_be_void {
    return if defined( ( caller 1 )[5] );

    return _die_context('scalar or list');
}

sub _die_context {
    my ( $context, $message ) = @_;

    local $Carp::CarpInternal{__PACKAGE__} if $INC{'Carp.pm'};

    my $to_throw = length $message ? "Must be $context context ($message)!" : "Must be $context context!";

    die Cpanel::Exception::create_raw( 'ContextError', $to_throw );
}

1;

} # --- END Cpanel/Context.pm


{ # --- BEGIN Cpanel/Finally.pm
package Cpanel::Finally;



use strict;

sub new {
    my ( $class, @todo_crs ) = @_;

    return bless { 'pid' => $$, 'todo' => \@todo_crs }, $class;
}

sub add {
    my ( $self, @new_crs ) = @_;

    push @{ $self->{'todo'} }, @new_crs;

    return;
}

sub skip {
    my ($self) = @_;
    return delete $self->{'todo'};
}

sub DESTROY {
    my ($self) = @_;

    return if $$ != $self->{'pid'} || !$self->{'todo'};

    local $@;    #prevent insidious clobber of error messages

    while ( @{ $self->{'todo'} } ) {
        my $ok = eval {
            while ( my $item = shift @{ $self->{'todo'} } ) {
                $item->();
            }

            1;
        };

        warn $@ if !$ok;
    }

    return;
}

1;

} # --- END Cpanel/Finally.pm


{ # --- BEGIN Cpanel/LocaleString.pm
package Cpanel::LocaleString;



use strict;
use warnings;

sub DESTROY { }


sub new {

    if ( !length $_[1] ) {
        die 'Must include at least a string!';
    }

    return bless \@_, shift;
}


sub set_json_to_freeze {
    no warnings 'redefine';
    *TO_JSON = \&_to_list_ref;
    return ( __PACKAGE__ . '::_JSON_MODE' )->new();
}


sub thaw {

    if ( ref( $_[1] ) ne 'ARRAY' ) {
        die "Call thaw() on an ARRAY reference, not “$_[1]”!";
    }

    return $_[0]->new( @{ $_[1] }[ 1 .. $#{ $_[1] } ] );
}


sub is_frozen {
    {
        last if ref( $_[1] ) ne 'ARRAY';
        last if !$_[1][0]->isa( $_[0] );
        last if @{ $_[1] } < 2;

        return 1;
    }

    return 0;
}



sub to_string {
    return _locale()->makevar( @{ $_[0] } );
}


sub to_en_string {
    return _locale()->makethis_base( @{ $_[0] } );
}


sub clone_with_args {
    return ( ref $_[0] )->new(
        $_[0][0],          #the phrase, currently stored in the object
        @_[ 1 .. $#_ ],    #the new args, supplied by the caller
    );
}


sub to_list {

    if ( !wantarray ) {
        require Cpanel::Context;
        Cpanel::Context::must_be_list();
    }

    return @{ $_[0] };
}

*TO_JSON = \&to_string;


my $_locale;

sub _locale {
    return $_locale if $_locale;
    local $@;

    eval 'require Cpanel::Locale;' or do {    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        warn "Failed to load Cpanel::Locale; falling back to substitute. Error was: $@";
    };

    eval { $_locale = Cpanel::Locale->get_handle() };
    return $_locale || bless {}, 'Cpanel::LocaleString::_Cpanel_Locale_unavailable';
}

sub _put_back {
    no warnings 'redefine';
    *TO_JSON = \&to_string;

    return;
}

sub _to_list_ref {
    return [ ref( $_[0] ), @{ $_[0] } ];
}


package Cpanel::LocaleString::_JSON_MODE;


sub new {
    require Cpanel::Finally;    # PPI USE OK - loaded only when needed
    return $_[0]->SUPER::new( \&Cpanel::LocaleString::_put_back );
}

package Cpanel::LocaleString::_Cpanel_Locale_unavailable;

BEGIN {
    *Cpanel::LocaleString::_Cpanel_Locale_unavailable::makethis_base = *Cpanel::LocaleString::_Cpanel_Locale_unavailable::makevar;
}

sub makevar {
    my ( $self, $str, @maketext_opts ) = @_;

    local ( $@, $! );
    require Cpanel::Locale::Utils::Fallback;

    return Cpanel::Locale::Utils::Fallback::interpolate_variables( $str, @maketext_opts );
}

1;

} # --- END Cpanel/LocaleString.pm


{ # --- BEGIN Cpanel/Errno.pm
package Cpanel::Errno;


use strict;

my %_err_name_cache;

sub get_name_for_errno_number {
    my ($number) = @_;

    if ( !$INC{'Errno.pm'} ) {
        local ( $@, $! );
        require Errno;
    }

    die 'need number!' if !length $number;

    if ( !%_err_name_cache ) {

        my $s = scalar keys %Errno::;    # init iterator
        foreach my $k ( sort keys %Errno:: ) {
            if ( Errno->EXISTS($k) ) {
                my $v = 'Errno'->can($k)->();
                $_err_name_cache{$v} = $k;
            }
        }
    }

    return $_err_name_cache{$number};
}

1;

} # --- END Cpanel/Errno.pm


{ # --- BEGIN Cpanel/Config/Constants/Perl.pm
package Cpanel::Config::Constants::Perl;


use strict;

our $ABRT   = 6;
our $ALRM   = 14;
our $BUS    = 7;
our $CHLD   = 17;
our $CLD    = 17;
our $CONT   = 18;
our $FPE    = 8;
our $HUP    = 1;
our $ILL    = 4;
our $INT    = 2;
our $IO     = 29;
our $IOT    = 6;
our $KILL   = 9;
our $NUM32  = 32;
our $NUM33  = 33;
our $NUM35  = 35;
our $NUM36  = 36;
our $NUM37  = 37;
our $NUM38  = 38;
our $NUM39  = 39;
our $NUM40  = 40;
our $NUM41  = 41;
our $NUM42  = 42;
our $NUM43  = 43;
our $NUM44  = 44;
our $NUM45  = 45;
our $NUM46  = 46;
our $NUM47  = 47;
our $NUM48  = 48;
our $NUM49  = 49;
our $NUM50  = 50;
our $NUM51  = 51;
our $NUM52  = 52;
our $NUM53  = 53;
our $NUM54  = 54;
our $NUM55  = 55;
our $NUM56  = 56;
our $NUM57  = 57;
our $NUM58  = 58;
our $NUM59  = 59;
our $NUM60  = 60;
our $NUM61  = 61;
our $NUM62  = 62;
our $NUM63  = 63;
our $PIPE   = 13;
our $POLL   = 29;
our $PROF   = 27;
our $PWR    = 30;
our $QUIT   = 3;
our $RTMAX  = 64;
our $RTMIN  = 34;
our $SEGV   = 11;
our $STKFLT = 16;
our $STOP   = 19;
our $SYS    = 31;
our $TERM   = 15;
our $TRAP   = 5;
our $TSTP   = 20;
our $TTIN   = 21;
our $TTOU   = 22;
our $UNUSED = 31;
our $URG    = 23;
our $USR1   = 10;
our $USR2   = 12;
our $VTALRM = 26;
our $WINCH  = 28;
our $XCPU   = 24;
our $XFSZ   = 25;
our $ZERO   = 0;

our %SIGNAL_NAME = qw(
  0    ZERO
  1    HUP
  10    USR1
  11    SEGV
  12    USR2
  13    PIPE
  14    ALRM
  15    TERM
  16    STKFLT
  17    CHLD
  18    CONT
  19    STOP
  2    INT
  20    TSTP
  21    TTIN
  22    TTOU
  23    URG
  24    XCPU
  25    XFSZ
  26    VTALRM
  27    PROF
  28    WINCH
  29    IO
  3    QUIT
  30    PWR
  31    SYS
  32    NUM32
  33    NUM33
  34    RTMIN
  35    NUM35
  36    NUM36
  37    NUM37
  38    NUM38
  39    NUM39
  4    ILL
  40    NUM40
  41    NUM41
  42    NUM42
  43    NUM43
  44    NUM44
  45    NUM45
  46    NUM46
  47    NUM47
  48    NUM48
  49    NUM49
  5    TRAP
  50    NUM50
  51    NUM51
  52    NUM52
  53    NUM53
  54    NUM54
  55    NUM55
  56    NUM56
  57    NUM57
  58    NUM58
  59    NUM59
  6    ABRT
  60    NUM60
  61    NUM61
  62    NUM62
  63    NUM63
  64    RTMAX
  7    BUS
  8    FPE
  9    KILL
);

1;

} # --- END Cpanel/Config/Constants/Perl.pm


{ # --- BEGIN Cpanel/ChildErrorStringifier.pm
package Cpanel::ChildErrorStringifier;


use strict;

# use Cpanel::LocaleString ();
# use Cpanel::Exception    ();


sub new {
    my ( $class, $CHILD_ERROR, $PROGRAM_NAME ) = @_;

    return bless { _CHILD_ERROR => $CHILD_ERROR, _PROGRAM_NAME => $PROGRAM_NAME }, $class;
}

sub CHILD_ERROR {
    my ($self) = @_;

    return $self->{'_CHILD_ERROR'};
}

sub error_code {
    my ($self) = @_;

    return undef if !$self->CHILD_ERROR();

    return $self->CHILD_ERROR() >> 8;
}


sub error_name {
    my ($self) = @_;

    my $error_number = $self->error_code();

    return '' if ( !defined $error_number );    # Can't index a hash with undef

    require Cpanel::Errno;
    return Cpanel::Errno::get_name_for_errno_number($error_number) || q<>;
}

sub dumped_core {
    my ($self) = @_;

    return $self->CHILD_ERROR() && ( $self->CHILD_ERROR() & 128 ) ? 1 : 0;
}

sub signal_code {
    my ($self) = @_;

    return if !$self->CHILD_ERROR();

    return $self->CHILD_ERROR() & 127;
}

sub signal_name {
    my ($self) = @_;
    require Cpanel::Config::Constants::Perl;
    return $Cpanel::Config::Constants::Perl::SIGNAL_NAME{ $self->signal_code() };
}

sub exec_failed {
    return $_[0]->{'_exec_failed'} ? 1 : 0;
}

sub program {
    my ($self) = @_;

    return $self->{'_PROGRAM_NAME'} || undef;
}

sub set_program {
    my ( $self, $program ) = @_;

    return ( $self->{'_PROGRAM_NAME'} = $program );
}

sub autopsy {
    my ($self) = @_;

    return undef if !$self->CHILD_ERROR();

    my @localized_strings = (
        $self->error_code() ? $self->_ERROR_PHRASE() : $self->_SIGNAL_PHRASE(),
        $self->_core_dump_for_phrase_if_needed(),
        $self->_additional_phrases_for_autopsy(),
    );

    return join ' ', map { $_->to_string() } @localized_strings;
}

sub terse_autopsy {
    my ($self) = @_;

    my $str;

    if ( $self->signal_code() ) {
        $str .= 'SIG' . $self->signal_name() . " (#" . $self->signal_code() . ")";
    }
    elsif ( my $code = $self->error_code() ) {
        $str .= "exit $code";
    }
    else {
        $str = 'OK';
    }

    if ( $self->dumped_core() ) {
        $str .= ' (+core)';
    }

    return $str;
}

sub die_if_error {
    my ($self) = @_;

    my $err = $self->to_exception();
    die $err if $err;

    return $self;
}

sub to_exception {
    my ($self) = @_;

    if ( $self->signal_code() ) {
        return Cpanel::Exception::create(
            'ProcessFailed::Signal',
            [
                process_name => $self->program(),
                signal_code  => $self->signal_code(),
                $self->_extra_error_args_for_die_if_error(),
            ],
        );
    }

    if ( $self->error_code() ) {
        return Cpanel::Exception::create(
            'ProcessFailed::Error',
            [
                process_name => $self->program(),
                error_code   => $self->error_code(),
                $self->_extra_error_args_for_die_if_error(),
            ],
        );
    }

    return undef;
}

sub _extra_error_args_for_die_if_error { }

sub _additional_phrases_for_autopsy { }

sub _core_dump_for_phrase_if_needed {
    my ($self) = @_;

    if ( $self->dumped_core() ) {
        return Cpanel::LocaleString->new('The process dumped a core file.');
    }

    return;
}


sub _ERROR_PHRASE {
    my ($self) = @_;

    if ( $self->program() ) {
        return Cpanel::LocaleString->new( 'The subprocess “[_1]” reported error number [numf,_2] when it ended.', $self->program(), $self->error_code() );
    }

    return Cpanel::LocaleString->new( 'The subprocess reported error number [numf,_1] when it ended.', $self->error_code() );
}

sub _SIGNAL_PHRASE {
    my ($self) = @_;

    if ( $self->program() ) {
        return Cpanel::LocaleString->new( 'The subprocess “[_1]” ended prematurely because it received the “[_2]” ([_3]) signal.', $self->program(), $self->signal_name(), $self->signal_code() );
    }

    return Cpanel::LocaleString->new( 'The subprocess ended prematurely because it received the “[_1]” ([_2]) signal.', $self->signal_name(), $self->signal_code() );
}


1;

} # --- END Cpanel/ChildErrorStringifier.pm


{ # --- BEGIN Cpanel/Exception/AdminBinError.pm
package Cpanel::Exception::AdminBinError;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }
# use Cpanel::ChildErrorStringifier();
BEGIN { push @ISA, qw(Cpanel::ChildErrorStringifier); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->signal_code() ) {
        if ( length $self->{'_metadata'}{'message_from_subprocess'} ) {
            return Cpanel::LocaleString->new(
                'The administrative request ended prematurely because it received the “[_1]” ([_2]) signal. It gave the following output: [_3]',
                $self->signal_name(),
                $self->signal_code(),
                $self->{'_metadata'}{'message_from_subprocess'},
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The administrative request ended prematurely because it received the “[_1]” ([_2]) signal.',
                $self->signal_name(),
                $self->signal_code(),
            );
        }
    }

    if ( $self->error_code() ) {
        my $err_display = ( $self->error_name() ? $self->error_name() . '/' : q<> ) . $self->error_code();

        if ( length $self->{'_metadata'}{'message_from_subprocess'} ) {
            return Cpanel::LocaleString->new(
                'The administrative request failed because of an error ([_1]) with output: [_2]',
                $err_display,
                $self->{'_metadata'}{'message_from_subprocess'},
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The administrative request failed because of an error ([_1]).',
                $err_display,
            );
        }
    }
}

sub CHILD_ERROR {
    my ($self) = @_;

    return $self->{'_metadata'}{'CHILD_ERROR'};
}

1;

} # --- END Cpanel/Exception/AdminBinError.pm


{ # --- BEGIN Cpanel/Exception/AbstractClass.pm
package Cpanel::Exception::AbstractClass;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ( $class, $mt_args_ar ) = @_;

    return Cpanel::LocaleString->new(
        '“[_1]” is an abstract base class. Please use an implementation!',
        $mt_args_ar->[0],
    );
}

1;

} # --- END Cpanel/Exception/AbstractClass.pm


{ # --- BEGIN Cpanel/Exception/AttributeNotSet.pm
package Cpanel::Exception::AttributeNotSet;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/AttributeNotSet.pm


{ # --- BEGIN Cpanel/Exception/AttributeReadOnly.pm
package Cpanel::Exception::AttributeReadOnly;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'You cannot set the attribute “[_1]” because it is read-only.',
        $self->get('name'),
    );
}

1;

} # --- END Cpanel/Exception/AttributeReadOnly.pm


{ # --- BEGIN Cpanel/Exception/System/RequiredRoleDisabled.pm
package Cpanel::Exception::System::RequiredRoleDisabled;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }


sub _default_phrase {
    my ($self) = @_;

    require Cpanel::LocaleString;
    if ($>) {
        return Cpanel::LocaleString->new('This server does not support this functionality.');
    }

    my $role = $self->get('role');

    my @roles = ( ref $role ) ? @$role : $role;

    return Cpanel::LocaleString->new( 'This functionality is not available because the [list_and_quoted,_1] [numerate,_2,role is,roles are] disabled on this server.', \@roles, 0 + @roles );
}

1;

} # --- END Cpanel/Exception/System/RequiredRoleDisabled.pm


{ # --- BEGIN Cpanel/Caller.pm
package Cpanel::Caller;



use strict;

my %PROPERTY_INDEX;

sub _get {
    my ( $property, $frames_back_count ) = @_;

    if ( !%PROPERTY_INDEX ) {
        my @PROPERTIES_ORDER = qw(
          package
          filename
          line
          subroutine
          hasargs
          wantarray
          evaltext
          is_require

          hints__NOT_USED__
          bitmask__NOT_USED__

          hinthash
        );

        %PROPERTY_INDEX = map { $PROPERTIES_ORDER[$_] => $_ } ( 0 .. $#PROPERTIES_ORDER );
    }

    $frames_back_count ||= 0;
    $frames_back_count += 2;

    return scalar( ( caller $frames_back_count )[ $PROPERTY_INDEX{$property} ] );
}


sub evaltext   { return _get( 'evaltext',   @_ ) }
sub filename   { return _get( 'filename',   @_ ) }
sub hasargs    { return _get( 'hasargs',    @_ ) }
sub hinthash   { return _get( 'hinthash',   @_ ) }
sub is_require { return _get( 'is_require', @_ ) }
sub line       { return _get( 'line',       @_ ) }
sub package    { return _get( 'package',    @_ ) }
sub subroutine { return _get( 'subroutine', @_ ) }
sub wantarray  { return _get( 'wantarray',  @_ ) }


1;

} # --- END Cpanel/Caller.pm


{ # --- BEGIN Cpanel/Exception/Caller.pm
package Cpanel::Exception::Caller;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::Caller ();

my @CALLERS_TO_EXCLUDE_FROM_MESSAGE = (
    q<Whostmgr::API::1::Utils::get[a-z_]+argument>,
    q<Cpanel::JSON::>
);

sub _get_caller_name {
    my $i = 0;
    my $caller_name;
    while ( my $sub = Cpanel::Caller::subroutine( $i++ ) ) {
        last if ( $sub =~ m{::BEGIN$} );
        next if $sub eq 'Cpanel::Exception::__ANON__';    # do not advertise anonymous sub from Cpanel::Exception
        $caller_name = $sub;
        next if index( $caller_name, '::_' ) > -1 || grep { $caller_name =~ m<$_> } @CALLERS_TO_EXCLUDE_FROM_MESSAGE;
        last if ( $caller_name !~ m{^Cpanel::Exception} );
    }
    return $caller_name;
}

1;

} # --- END Cpanel/Exception/Caller.pm


{ # --- BEGIN Cpanel/CPAN/I18N/LangTags.pm


package Cpanel::CPAN::I18N::LangTags;
use strict;

require Exporter;
our @ISA       = qw(Exporter);
our @EXPORT    = qw();
our @EXPORT_OK = qw(is_language_tag same_language_tag
  extract_language_tags super_languages
  similarity_language_tag is_dialect_of
  locale2language_tag alternate_language_tags
  encode_language_tag panic_languages
  implicate_supers
  implicate_supers_strictly
);
our %EXPORT_TAGS = ( 'ALL' => \@EXPORT_OK );
our %Panic;
our $VERSION = "0.35";

sub uniq { my %seen; return grep( !( $seen{$_}++ ), @_ ); }    # a util function




sub is_language_tag {


    my ($tag) = lc( $_[0] );

    return 0 if $tag eq "i" or $tag eq "x";


    return $tag =~ /^(?:  # First subtag
         [xi] | [a-z]{2,3}
      )
      (?:  # Subtags thereafter
         -           # separator
         [a-z0-9]{1,8}  # subtag
      )*
    $/xs ? 1 : 0;
}



sub extract_language_tags {


    my ($text) = $_[0] =~ m/(.+)/    # to make for an untainted result
      ? $1
      : '';

    return grep( !m/^[ixIX]$/s,      # 'i' and 'x' aren't good tags
        $text =~ m/
      \b
      (?:  # First subtag
         [iIxX] | [a-zA-Z]{2,3}
      )
      (?:  # Subtags thereafter
         -           # separator
         [a-zA-Z0-9]{1,8}  # subtag
      )*
      \b
    /xsg
    );
}



sub same_language_tag {
    my $el1 = &encode_language_tag( $_[0] );
    return 0 unless defined $el1;


    return $el1 eq &encode_language_tag( $_[1] ) ? 1 : 0;
}



sub similarity_language_tag {
    my $lang1 = &encode_language_tag( $_[0] );
    my $lang2 = &encode_language_tag( $_[1] );



    return undef if !defined($lang1) and !defined($lang2);
    return 0 if !defined($lang1) or !defined($lang2);

    my @l1_subtags = split( '-', $lang1 );
    my @l2_subtags = split( '-', $lang2 );
    my $similarity = 0;

    while ( @l1_subtags and @l2_subtags ) {
        if ( shift(@l1_subtags) eq shift(@l2_subtags) ) {
            ++$similarity;
        }
        else {
            last;
        }
    }
    return $similarity;
}



sub is_dialect_of {

    my $lang1 = &encode_language_tag( $_[0] );
    my $lang2 = &encode_language_tag( $_[1] );

    return undef if !defined($lang1) and !defined($lang2);
    return 0 if !defined($lang1) or !defined($lang2);

    return 1 if $lang1 eq $lang2;
    return 0 if length($lang1) < length($lang2);

    $lang1 .= '-';
    $lang2 .= '-';
    return ( substr( $lang1, 0, length($lang2) ) eq $lang2 ) ? 1 : 0;
}



sub super_languages {
    my $lang1 = $_[0];
    return () unless defined($lang1) && &is_language_tag($lang1);

    $lang1 =~ s/^nb\b/no-bok/i;            # yes, backwards
    $lang1 =~ s/^nn\b/no-nyn/i;            # yes, backwards
    $lang1 =~ s/^[ix](-hakka\b)/zh$1/i;    # goes the right way

    my @l1_subtags = split( '-', $lang1 );



    my @supers = ();
    foreach my $bit (@l1_subtags) {
        push @supers, scalar(@supers) ? ( $supers[-1] . '-' . $bit ) : $bit;
    }
    pop @supers if @supers;
    shift @supers if @supers && $supers[0] =~ m<^[iIxX]$>s;
    return reverse @supers;
}



sub locale2language_tag {
    my $lang = $_[0] =~ m/(.+)/    # to make for an untainted result
      ? $1
      : '';

    return $lang if &is_language_tag($lang);    # like "en"

    $lang =~ tr<_><->;                          # "en_US" -> en-US
    $lang =~ s<(?:[\.\@][-_a-zA-Z0-9]+)+$><>s;  # "en_US.ISO8859-1" -> en-US

    return $lang if &is_language_tag($lang);

    return;
}



sub encode_language_tag {



    my ($tag) = $_[0] || return undef;
    return undef unless &is_language_tag($tag);

    $tag =~ s/^iw\b/he/i;                  # Hebrew
    $tag =~ s/^in\b/id/i;                  # Indonesian
    $tag =~ s/^cre\b/cr/i;                 # Cree
    $tag =~ s/^jw\b/jv/i;                  # Javanese
    $tag =~ s/^[ix]-lux\b/lb/i;            # Luxemburger
    $tag =~ s/^[ix]-navajo\b/nv/i;         # Navajo
    $tag =~ s/^ji\b/yi/i;                  # Yiddish
    $tag =~ s/^[ix]-hakka\b/zh-hakka/i;    # Hakka
    $tag =~ s/^nb\b/no-bok/i;              # BACKWARDS for Bokmal
    $tag =~ s/^nn\b/no-nyn/i;              # BACKWARDS for Nynorsk

    $tag =~ s/^[xiXI]-//s;


    return "~" . uc($tag);
}



my %alt = qw( i x   x i   I X   X I );

sub alternate_language_tags {
    my $tag = $_[0];
    return () unless &is_language_tag($tag);

    my @em;    # push 'em real goood!


    if ( $tag =~ m/^[ix]-hakka\b(.*)/i ) {
        push @em, "zh-hakka$1";
    }
    elsif ( $tag =~ m/^zh-hakka\b(.*)/i ) {
        push @em, "x-hakka$1", "i-hakka$1";

    }
    elsif ( $tag =~ m/^he\b(.*)/i ) {
        push @em, "iw$1";
    }
    elsif ( $tag =~ m/^iw\b(.*)/i ) {
        push @em, "he$1";

    }
    elsif ( $tag =~ m/^in\b(.*)/i ) {
        push @em, "id$1";
    }
    elsif ( $tag =~ m/^id\b(.*)/i ) {
        push @em, "in$1";

    }
    elsif ( $tag =~ m/^[ix]-lux\b(.*)/i ) {
        push @em, "lb$1";
    }
    elsif ( $tag =~ m/^lb\b(.*)/i ) {
        push @em, "i-lux$1", "x-lux$1";

    }
    elsif ( $tag =~ m/^[ix]-navajo\b(.*)/i ) {
        push @em, "nv$1";
    }
    elsif ( $tag =~ m/^nv\b(.*)/i ) {
        push @em, "i-navajo$1", "x-navajo$1";

    }
    elsif ( $tag =~ m/^yi\b(.*)/i ) {
        push @em, "ji$1";
    }
    elsif ( $tag =~ m/^ji\b(.*)/i ) {
        push @em, "yi$1";

    }
    elsif ( $tag =~ m/^nb\b(.*)/i ) {
        push @em, "no-bok$1";
    }
    elsif ( $tag =~ m/^no-bok\b(.*)/i ) {
        push @em, "nb$1";

    }
    elsif ( $tag =~ m/^nn\b(.*)/i ) {
        push @em, "no-nyn$1";
    }
    elsif ( $tag =~ m/^no-nyn\b(.*)/i ) {
        push @em, "nn$1";
    }

    push @em, $alt{$1} . $2 if $tag =~ /^([XIxi])(-.+)/;
    return @em;
}


{


    my @panic = (    # MUST all be lowercase!

        'sv' => [qw(nb no da nn)],
        'da' => [qw(nb no sv nn)],    # I guess
        [qw(no nn nb)], [qw(no nn nb sv da)],
        'is' => [qw(da sv no nb nn)],
        'fo' => [qw(da is no nb nn sv)],    # I guess

        'pt' => [qw(es ca it fr)],    # Portuguese, Spanish, Catalan, Italian, French
        'ca' => [qw(es pt it fr)],
        'es' => [qw(ca it fr pt)],
        'it' => [qw(es fr ca pt)],
        'fr' => [qw(es it ca pt)],

        [
            qw(
              as bn gu kn ks kok ml mni mr ne or pa sa sd te ta ur
              )
        ] => 'hi',

        'hi' => [qw(bn pa as or)],



        ( [qw(ru be uk)] ) x 2,    # Russian, Belarusian, Ukranian
        'sr' => 'hr', 'hr' => 'sr',    # Serb + Croat
        'cs' => 'sk', 'sk' => 'cs',    # Czech + Slovak

        'ms' => 'id', 'id' => 'ms',    # Malay + Indonesian

        'et' => 'fi', 'fi' => 'et',    # Estonian + Finnish


    );
    my ( $k, $v );
    while (@panic) {
        ( $k, $v ) = splice( @panic, 0, 2 );
        foreach my $k ( ref($k) ? @$k : $k ) {
            foreach my $v ( ref($v) ? @$v : $v ) {
                push @{ $Panic{$k} ||= [] }, $v unless $k eq $v;
            }
        }
    }
}


sub panic_languages {

    my ( @out, %seen );
    foreach my $t (@_) {
        next unless $t;
        next if $seen{$t}++;    # so we don't return it or hit it again
        push @out, @{ $Panic{ lc $t } || next };
    }
    return grep !$seen{$_}++, @out, 'en';
}



sub implicate_supers {
    my @languages = grep is_language_tag($_), @_;
    my %seen_encoded;
    foreach my $lang (@languages) {
        $seen_encoded{ Cpanel::CPAN::I18N::LangTags::encode_language_tag($lang) } = 1;
    }

    my (@output_languages);
    foreach my $lang (@languages) {
        push @output_languages, $lang;
        foreach my $s ( Cpanel::CPAN::I18N::LangTags::super_languages($lang) ) {

            last if $seen_encoded{ Cpanel::CPAN::I18N::LangTags::encode_language_tag($s) };
            push @output_languages, $s;
        }
    }
    return uniq(@output_languages);

}

sub implicate_supers_strictly {
    my @tags = grep is_language_tag($_), @_;
    return uniq( @_, map super_languages($_), @_ );
}

1;

} # --- END Cpanel/CPAN/I18N/LangTags.pm


{ # --- BEGIN Cpanel/CPAN/I18N/LangTags/Detect.pm


package Cpanel::CPAN::I18N::LangTags::Detect;
use strict;

use vars qw( @ISA $VERSION $MATCH_SUPERS $USING_LANGUAGE_TAGS
  $USE_LITERALS $MATCH_SUPERS_TIGHTLY);

BEGIN {
    unless ( defined &DEBUG ) {
        *DEBUG = sub () { 0 }
    }
}


$VERSION = "1.04";
@ISA     = ();
# use Cpanel::CPAN::I18N::LangTags ();

sub _uniq { my %seen; return grep( !( $seen{$_}++ ), @_ ); }

sub _normalize {
    my (@languages) =
      map lc($_),
      grep $_,
      map { ; $_, Cpanel::CPAN::I18N::LangTags::alternate_language_tags($_) } @_;
    return _uniq(@languages) if wantarray;
    return $languages[0];
}


sub detect () { return __PACKAGE__->ambient_langprefs; }


sub ambient_langprefs {    # always returns things untainted
    my $base_class = $_[0];

    return $base_class->http_accept_langs
      if length( $ENV{'REQUEST_METHOD'} || '' );    # I'm a CGI

    my @languages;

    foreach my $envname (qw( LANGUAGE LC_ALL LC_MESSAGES LANG )) {
        next unless $ENV{$envname};
        DEBUG and print "Noting \$$envname: $ENV{$envname}\n";
        push @languages, map Cpanel::CPAN::I18N::LangTags::locale2language_tag($_),


          split m/[,:]/, $ENV{$envname};
        last;    # first one wins
    }

    if ( $ENV{'IGNORE_WIN32_LOCALE'} ) {

    }
    elsif ( &_try_use('Win32::Locale') ) {

        push @languages, Win32::Locale::get_language() || ''
          if defined &Win32::Locale::get_language;
    }
    return _normalize @languages;
}


sub http_accept_langs {

    no integer;

    my $in = ( @_ > 1 ) ? $_[1] : $ENV{'HTTP_ACCEPT_LANGUAGE'};


    return () unless defined $in and length $in;

    $in =~ s/\([^\)]*\)//g;    # nix just about any comment

    if ( $in =~ m/^\s*([a-zA-Z][-a-zA-Z]+)\s*$/s ) {

        return _normalize $1;
    }
    elsif ( $in =~ m/^\s*[a-zA-Z][-a-zA-Z]+(?:\s*,\s*[a-zA-Z][-a-zA-Z]+)*\s*$/s ) {

        return _normalize( $in =~ m/([a-zA-Z][-a-zA-Z]+)/g );
    }


    $in =~ s/\s+//g;    # Yes, we can just do without the WS!
    my @in = $in =~ m/([^,]+)/g;
    my %pref;

    my $q;
    foreach my $tag (@in) {
        next unless $tag =~ m/^([a-zA-Z][-a-zA-Z]+)
        (?:
         ;q=
         (
          \d*   # a bit too broad of a RE, but so what.
          (?:
            \.\d+
          )?
         )
        )?
       $
      /sx
          ;
        $q = ( defined $2 and length $2 ) ? $2 : 1;

        push @{ $pref{$q} }, lc $1;
    }

    return _normalize(

        map @{ $pref{$_} },
        sort { $b <=> $a }
          keys %pref
    );
}


my %tried = ();


sub _try_use {    # Basically a wrapper around "require Modulename"
    return $tried{ $_[0] } if exists $tried{ $_[0] };    # memoization

    my $module = $_[0];                                  # ASSUME sane module name!
    {
        no strict 'refs';
        return ( $tried{$module} = 1 )
          if %{ $module . "::Lexicon" }
          or @{ $module . "::ISA" };

    }

    print " About to use $module ...\n" if DEBUG;
    {
        local $SIG{'__DIE__'};
        eval "require $module";    # used to be "use $module", but no point in that.
    }
    if ($@) {
        print "Error using $module \: $@\n" if DEBUG > 1;
        return $tried{$module} = 0;
    }
    else {
        print " OK, $module is used\n" if DEBUG;
        return $tried{$module} = 1;
    }
}

1;

} # --- END Cpanel/CPAN/I18N/LangTags/Detect.pm


{ # --- BEGIN Cpanel/CPAN/Locale/Maketext.pm
package Cpanel::CPAN::Locale::Maketext;


use strict;
our @ISA;
our $VERSION;
our $MATCH_SUPERS;
our $USING_LANGUAGE_TAGS;
our $USE_LITERALS;
our $MATCH_SUPERS_TIGHTLY;

use constant IS_ASCII => ord('A') == 65;

BEGIN {
    unless ( defined &DEBUG ) {
        *DEBUG = sub () { 0 }
    }
}


$VERSION = '1.13_89';
$VERSION = eval $VERSION;
@ISA     = ();

$MATCH_SUPERS         = 1;
$MATCH_SUPERS_TIGHTLY = 1;
$USING_LANGUAGE_TAGS  = 1;
my $FORCE_REGEX_LAZY = '';


$USE_LITERALS = 1 unless defined $USE_LITERALS;


my %isa_scan = ();
my %isa_ones = ();


sub quant {
    my ( $handle, $num, @forms ) = @_;

    return $num if @forms == 0;    # what should this mean?
    return $forms[2] if @forms > 2 and $num == 0;    # special zeroth case

    return ( $handle->numf($num) . ' ' . $handle->numerate( $num, @forms ) );

}

sub numerate {

    my ( $handle, $num, @forms ) = @_;
    my $s = ( $num == 1 );

    return '' unless @forms;
    if ( @forms == 1 ) {    # only the headword form specified
        return $s ? $forms[0] : ( $forms[0] . 's' );    # very cheap hack.
    }
    else {                                              # sing and plural were specified
        return $s ? $forms[0] : $forms[1];
    }
}


sub numf {
    my ( $handle, $num ) = @_[ 0, 1 ];
    if ( $num < 10_000_000_000 and $num > -10_000_000_000 and $num == int($num) ) {
        $num += 0;                                      # Just use normal integer stringification.
    }
    else {
        $num = CORE::sprintf( '%G', $num );

    }
    while ( $num =~ s/$FORCE_REGEX_LAZY^([-+]?\d+)(\d{3})/$1,$2/os ) { 1 }    # right from perlfaq5

    $num =~ tr<.,><,.> if ref($handle) and $handle->{'numf_comma'};

    return $num;
}

sub sprintf {
    no integer;
    my ( $handle, $format, @params ) = @_;
    return CORE::sprintf( $format, @params );

}


use integer;    # vroom vroom... applies to the whole rest of the module

sub language_tag {
    my $it = ref( $_[0] ) || $_[0];
    return undef unless $it =~ m/$FORCE_REGEX_LAZY([^':]+)(?:::)?$/os;
    $it = lc($1);
    $it =~ tr<_><->;
    return $it;
}

sub encoding {
    my $it = $_[0];
    return (
        ( ref($it) && $it->{'encoding'} )
          || 'iso-8859-1'    # Latin-1
    );
}


sub fallback_languages { return ( 'i-default', 'en', 'en-US' ) }

sub fallback_language_classes { return () }


sub fail_with {              # an actual attribute method!
    my ( $handle, @params ) = @_;
    return unless ref($handle);
    $handle->{'fail'} = $params[0] if @params;
    return $handle->{'fail'};
}


sub blacklist {
    my ( $handle, @methods ) = @_;

    unless ( defined $handle->{'blacklist'} ) {
        no strict 'refs';

        $handle->{'blacklist'} = {
            map { $_ => 1 } (
                qw/
                  blacklist
                  encoding
                  fail_with
                  failure_handler_auto
                  fallback_language_classes
                  fallback_languages
                  get_handle
                  init
                  language_tag
                  maketext
                  new
                  whitelist
                  /, grep { substr( $_, 0, 1 ) eq '_' } keys %{ __PACKAGE__ . "::" }
            ),
        };
    }

    if ( scalar @methods ) {
        $handle->{'blacklist'} = { %{ $handle->{'blacklist'} }, map { $_ => 1 } @methods };
    }

    delete $handle->{'_external_lex_cache'};
    return;
}

sub whitelist {
    my ( $handle, @methods ) = @_;
    if ( scalar @methods ) {
        if ( defined $handle->{'whitelist'} ) {
            $handle->{'whitelist'} = { %{ $handle->{'whitelist'} }, map { $_ => 1 } @methods };
        }
        else {
            $handle->{'whitelist'} = { map { $_ => 1 } @methods };
        }
    }

    delete $handle->{'_external_lex_cache'};
    return;
}


sub failure_handler_auto {


    my $handle = shift;
    my $phrase = shift;

    $handle->{'failure_lex'} ||= {};
    my $lex = $handle->{'failure_lex'};

    my $value = $lex->{$phrase} ||= ( $phrase !~ tr/[// ? \"$phrase" : $handle->_compile($phrase) );

    return ${$value} if ref($value) eq 'SCALAR';
    return $value if ref($value) ne 'CODE';
    {
        local $SIG{'__DIE__'};
        eval { $value = &$value( $handle, @_ ) };
    }

    if ($@) {
        my $err = $@;

        $err =~ s{\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?}
                 {\n in bracket code [compiled line $1],}s;

        require Carp;
        Carp::croak("Error in maketexting \"$phrase\":\n$err as used");

    }
    else {
        return $value;
    }
}


sub new {

    my $class = ref( $_[0] ) || $_[0];
    my $handle = bless {}, $class;
    $handle->blacklist;
    $handle->init;
    return $handle;
}

sub init { return }    # no-op


sub maketext {

    unless ( @_ > 1 ) {
        require Carp;
        Carp::croak('maketext requires at least one parameter');
    }

    my ( $handle, $phrase ) = splice( @_, 0, 2 );
    unless ( defined($handle) && defined($phrase) ) {
        require Carp;
        Carp::confess('No handle/phrase');
    }

    my $value;
    if ( exists $handle->{'_external_lex_cache'}{$phrase} ) {
        DEBUG and warn "* Using external lex cache version of \"$phrase\"\n";
        $value = $handle->{'_external_lex_cache'}{$phrase};
    }
    else {
        my $ns = ref($handle) || $handle;
        foreach my $h_r ( @{ $isa_scan{$ns} || $handle->_lex_refs } ) {
            DEBUG and warn "* Looking up \"$phrase\" in $h_r\n";
            if ( defined( $value = $h_r->{$phrase} ) ) {    # Minimize looking at $h_r as much as possible as an expensive tied hash to CDB_File
                DEBUG and warn "  Found \"$phrase\" in $h_r\n";
                unless ( ref $value ) {

                    if ( !length $value ) {
                        DEBUG and warn " value is undef or ''";
                        if ( $isa_ones{"$h_r"} ) {
                            DEBUG and warn " $ns ($h_r) is Onesided and \"$phrase\" entry is undef or ''\n";
                            $value = $phrase;
                        }
                    }


                    if ( $handle->{'use_external_lex_cache'} ) {

                        $handle->{'_external_lex_cache'}{$phrase} = $value = ( $value !~ tr/[// ? \"$value" : $handle->_compile($value) );
                    }
                    else {

                        $h_r->{$phrase} = $value = ( $value !~ tr/[// ? \"$value" : $handle->_compile($value) );
                    }
                }
                last;
            }

            elsif ( substr( $phrase, 0, 1 ) ne '_' and ( $handle->{'use_external_lex_cache'} ? ( exists $handle->{'_external_lex_cache'}{'_AUTO'} ? $handle->{'_external_lex_cache'}{'_AUTO'} : $h_r->{'_AUTO'} ) : $h_r->{'_AUTO'} ) ) {

                DEBUG and warn "  Automaking \"$phrase\" into $h_r\n";
                if ( $handle->{'use_external_lex_cache'} ) {

                    $handle->{'_external_lex_cache'}{$phrase} = $value = ( $phrase !~ tr/[// ? \"$phrase" : $handle->_compile($phrase) );
                }
                else {

                    $h_r->{$phrase} = $value = ( $phrase !~ tr/[// ? \"$phrase" : $handle->_compile($phrase) );
                }
                last;
            }
            DEBUG > 1 and print "  Not found in $h_r, nor automakable\n";

        }

        if ( !defined($value) ) {
            delete $handle->{'_external_lex_cache'}{$phrase};

            DEBUG and warn "! Lookup of \"$phrase\" in/under ", ref($handle) || $handle, " fails.\n";
            if ( ref($handle) and $handle->{'fail'} ) {
                DEBUG and warn "WARNING0: maketext fails looking for <$phrase>\n";
                my $fail;
                if ( ref( $fail = $handle->{'fail'} ) eq 'CODE' ) {    # it's a sub reference
                    return &{$fail}( $handle, $phrase, @_ );

                }
                else {                                                 # It's a method name
                    return $handle->$fail( $phrase, @_ );

                }
            }
            else {
                require Carp;

                Carp::croak("maketext doesn't know how to say:\n$phrase\nas needed");
            }
        }

    }

    if ( ref($value) eq 'SCALAR' ) {
        return $$value;
    }
    elsif ( ref($value) ne 'CODE' ) {
        return $value;
    }

    local $@;
    {
        local $SIG{'__DIE__'};
        return eval { &$value( $handle, @_ ) } unless $@;
    }

    my $err = $@;

    $err =~ s{\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?}
    {\n in bracket code [compiled line $1],}s;

    require Carp;

    Carp::croak("Error in maketexting \"$phrase\":\n$err as used");

}


sub get_handle {    # This is a constructor and, yes, it CAN FAIL.

    my ( $base_class, @languages ) = @_;
    $base_class = ref($base_class) || $base_class;

    my $load_alternate_language_tags = 0;


    if (@languages) {
        DEBUG and warn 'Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
        $load_alternate_language_tags = 1 if $USING_LANGUAGE_TAGS;    # An explicit language-list was given!
    }
    else {
        @languages = $base_class->_ambient_langprefs;
    }

    my %seen;
    foreach my $module_name ( map { $base_class . '::' . $_ } @languages ) {
        next
          if !length $module_name                                     # sanity
          || $seen{$module_name}++                                    # Already been here, and it was no-go
          || $module_name =~ tr{/-}{}
          || !&_try_use($module_name);                                # Try to use() it, but can't it.
        return ( $module_name->new );                                 # Make it!
    }

    if ($load_alternate_language_tags) {
        require Cpanel::CPAN::I18N::LangTags;
        @languages =
          map { ; $_, Cpanel::CPAN::I18N::LangTags::alternate_language_tags($_) }

          map Cpanel::CPAN::I18N::LangTags::locale2language_tag($_),

          @languages;
        DEBUG and warn 'Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
    }
    @languages = $base_class->_langtag_munging(@languages);

    foreach my $module_name ( map { $base_class . '::' . $_ } @languages ) {
        next
          if !length $module_name     # sanity
          || $seen{$module_name}++    # Already been here, and it was no-go
          || $module_name =~ tr{/-}{}
          || !&_try_use($module_name);    # Try to use() it, but can't it.
        return ( $module_name->new );     # Make it!
    }

    return undef;                         # Fail!
}


sub _langtag_munging {
    my ( $base_class, @languages ) = @_;


    DEBUG and warn 'Lgs1: ', map( "<$_>", @languages ), "\n";

    if ($USING_LANGUAGE_TAGS) {
        require Cpanel::CPAN::I18N::LangTags;

        DEBUG and warn 'Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
        @languages = $base_class->_add_supers(@languages);

        push @languages, Cpanel::CPAN::I18N::LangTags::panic_languages(@languages);
        DEBUG and warn "After adding panic languages:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

        push @languages, $base_class->fallback_languages;

        DEBUG and warn 'Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

        @languages =    # final bit of processing to turn them into classname things
          map {
            my $it = $_;               # copy
            $it =~ tr<-A-Z><_a-z>;     # lc, and turn - to _
            $it =~ tr<_a-z0-9><>cd;    # remove all but a-z0-9_
            $it;
          } @languages;
        DEBUG and warn "Nearing end of munging:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
    }
    else {
        DEBUG and warn "Bypassing language-tags.\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
    }

    DEBUG and warn "Before adding fallback classes:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

    push @languages, $base_class->fallback_language_classes;


    DEBUG and warn "Finally:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

    return @languages;
}


sub _ambient_langprefs {
    require Cpanel::CPAN::I18N::LangTags::Detect;
    return Cpanel::CPAN::I18N::LangTags::Detect::detect();
}


sub _add_supers {
    my ( $base_class, @languages ) = @_;

    if ( !$MATCH_SUPERS ) {

        DEBUG and warn "Bypassing any super-matching.\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

    }
    elsif ($MATCH_SUPERS_TIGHTLY) {
        require Cpanel::CPAN::I18N::LangTags;
        DEBUG and warn "Before adding new supers tightly:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
        @languages = Cpanel::CPAN::I18N::LangTags::implicate_supers(@languages);
        DEBUG and warn "After adding new supers tightly:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";

    }
    else {
        require Cpanel::CPAN::I18N::LangTags;
        DEBUG and warn "Before adding supers to end:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
        @languages = Cpanel::CPAN::I18N::LangTags::implicate_supers_strictly(@languages);
        DEBUG and warn "After adding supers to end:\n", ' Lgs@', __LINE__, ': ', map( "<$_>", @languages ), "\n";
    }

    return @languages;
}


my %tried = ();


sub _try_use {    # Basically a wrapper around "require Modulename"
    return $tried{ $_[0] } if exists $tried{ $_[0] };    # memoization

    my $module = $_[0];                                  # ASSUME sane module name!
    {
        no strict 'refs';
        return ( $tried{$module} = 1 )
          if ( %{ $module . '::Lexicon' } or @{ $module . '::ISA' } );

    }

    DEBUG and warn " About to use $module ...\n";
    {
        local $SIG{'__DIE__'};
        eval "require $module";                          # used to be "use $module", but no point in that.
    }
    if ($@) {
        DEBUG and warn "Error using $module \: $@\n";
        return $tried{$module} = 0;
    }
    else {
        DEBUG and warn " OK, $module is used\n";
        return $tried{$module} = 1;
    }
}


sub _lex_refs {    # report the lexicon references for this handle's class
    no strict 'refs';
    no warnings 'once';
    my $class = ref( $_[0] ) || $_[0];
    DEBUG and warn "Lex refs lookup on $class\n";
    return $isa_scan{$class} if exists $isa_scan{$class};    # memoization!

    my @lex_refs;
    my $seen_r = ref( $_[1] ) ? $_[1] : {};

    if ( defined( *{ $class . '::Lexicon' }{'HASH'} ) ) {
        push @lex_refs, *{ $class . '::Lexicon' }{'HASH'};
        $isa_ones{"$lex_refs[-1]"} = defined ${ $class . '::Onesided' } && ${ $class . '::Onesided' } ? 1 : 0;
        DEBUG and warn '%' . $class . '::Lexicon contains ', scalar( keys %{ $class . '::Lexicon' } ), " entries\n";
    }

    foreach my $superclass ( @{ $class . '::ISA' } ) {
        DEBUG and warn " Super-class search into $superclass\n";
        next if $seen_r->{$superclass}++;
        push @lex_refs, @{ &_lex_refs( $superclass, $seen_r ) };    # call myself
    }

    $isa_scan{$class} = \@lex_refs;                                 # save for next time
    return \@lex_refs;
}

sub clear_isa_scan { %isa_scan = (); return; }                      # end on a note of simplicity!


BEGIN {
}


sub _compile {


    return \"$_[1]" if $_[1] !~ tr/[//;

    my ( $handle, $call_count, $big_pile, @c, @code ) = ( $_[0], 0, '', '' );
    {

        my ( $in_group, $m, @params ) = (0);    # scratch

        my $under_one = $_[1];                  # There are taint issues using regex on $_ - perlbug 60378,27344
        while (
            $under_one =~                       # Iterate over chunks.
            m/\G(
                [^\~\[\]]+  # non-~[] stuff
                |
                ~.       # ~[, ~], ~~, ~other
                |
                \[          # [ presumably opening a group
                |
                \]          # ] presumably closing a group
                |
                ~           # terminal ~ ?
                |
                $
            )/xgs
        ) {
            DEBUG > 2 and warn qq{  "$1"\n};

            if ( $1 eq '[' or $1 eq '' ) {    # "[" or end
                if ($in_group) {
                    if ( $1 eq '' ) {
                        $handle->_die_pointing( $under_one, 'Unterminated bracket group' );
                    }
                    else {
                        $handle->_die_pointing( $under_one, 'You can\'t nest bracket groups' );
                    }
                }
                else {
                    if ( $1 eq '' ) {
                        DEBUG > 2 and warn "   [end-string]\n";
                    }
                    else {
                        $in_group = 1;
                    }
                    die "How come \@c is empty?? in <$under_one>" unless @c;    # sanity
                    if ( length $c[-1] ) {

                        $big_pile .= $c[-1];
                        if (
                            $USE_LITERALS and (
                                IS_ASCII
                                ? $c[-1] !~ tr/\x20-\x7E//c

                                : $c[-1] !~ m/$FORCE_REGEX_LAZY[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/os

                            )
                        ) {

                            $c[-1] =~ s/'/\\'/g if $c[-1] =~ tr{'}{};
                            push @code, q{ '} . $c[-1] . "',\n";
                            $c[-1] = '';    # reuse this slot
                        }
                        else {
                            $c[-1] =~ s/\\\\/\\/g if $c[-1] =~ tr{\\}{};
                            push @code, ' $c[' . $#c . "],\n";
                            push @c,    '';                      # new chunk
                        }
                    }

                }

            }
            elsif ( $1 eq ']' ) {                                # "]"
                if ($in_group) {
                    $in_group = 0;

                    DEBUG > 2 and warn "   --Closing group [$c[-1]]\n";


                    if ( !length( $c[-1] ) or $c[-1] !~ tr/ \t\r\n\f//c ) {
                        DEBUG > 2 and warn "   -- (Ignoring)\n";
                        $c[-1] = '';                             # reset out chink
                        next;
                    }

                    ( $m, @params ) = split( /,/, $c[-1], -1 );    # was /\s*,\s*/

                    if (IS_ASCII) {    # ASCII, etc
                        foreach ( $m, @params ) { tr/\x7F/,/ }
                    }
                    else {             # EBCDIC (1047, 0037, POSIX-BC)
                        foreach ( $m, @params ) { tr/\x07/,/ }
                    }

                    if ( $m eq '_1' or $m eq '_2' or $m eq '_3' or $m eq '_*' or ( substr( $m, 0, 1 ) eq '_' && $m =~ m/^_(-?\d+)$/s ) ) {

                        unshift @params, $m;
                        $m = '';
                    }
                    elsif ( $m eq '*' ) {
                        $m = 'quant';    # "*" for "times": "4 cars" is 4 times "cars"
                    }
                    elsif ( $m eq '#' ) {
                        $m = 'numf';     # "#" for "number": [#,_1] for "the number _1"
                    }

                    if ( $m eq '' ) {

                        push @code, ' (';
                    }
                    elsif (
                        $m !~ tr{a-zA-Z0-9_}{}c    # does not contain non-word characters
                        && !$handle->{'blacklist'}{$m}
                        && ( !defined $handle->{'whitelist'} || $handle->{'whitelist'}{$m} )

                    ) {
                        push @code, ' $_[0]->' . $m . '(';
                    }
                    else {

                        $handle->_die_pointing(
                            $under_one,
                            "Can't use \"$m\" as a method name in bracket group",
                            2 + length( $c[-1] )
                        );
                    }

                    pop @c;    # we don't need that chunk anymore
                    ++$call_count;

                    foreach my $p (@params) {
                        if ( $p eq '_*' ) {

                            $code[-1] .= ' @_[1 .. $#_], ';

                        }
                        elsif ( substr( $p, 0, 1 ) eq '_' && ( $p eq '_1' || $p eq '_2' || $p eq '_3' || $p =~ m/^_-?\d+$/s ) ) {

                            $code[-1] .= '$_[' . ( 0 + substr( $p, 1 ) ) . '], ';
                        }
                        elsif (
                            $USE_LITERALS and (
                                IS_ASCII
                                ? $p !~ tr/\x20-\x7E//c

                                : $p !~ m/$FORCE_REGEX_LAZY[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/os

                            )
                        ) {

                            $p =~ s/'/\\'/g if $p =~ tr{'}{};
                            $code[-1] .= q{'} . $p . q{', };
                        }
                        else {

                            push @c,    $p;
                            push @code, ' $c[' . $#c . '], ';
                        }
                    }
                    $code[-1] .= "),\n";

                    push @c, '';
                }
                else {
                    $handle->_die_pointing( $under_one, q{Unbalanced ']'} );
                }

            }
            elsif ( substr( $1, 0, 1 ) ne '~' ) {

                if ( $1 =~ tr{\\}{} ) {
                    my $text = $1;
                    $text =~ s/\\/\\\\/g;
                    $c[-1] .= $text;
                }
                else {
                    $c[-1] .= $1;
                }

            }
            elsif ( $1 eq '~~' ) {    # "~~"
                $c[-1] .= '~';

            }
            elsif ( $1 eq '~[' ) {    # "~["
                $c[-1] .= '[';

            }
            elsif ( $1 eq '~]' ) {    # "~]"
                $c[-1] .= ']';

            }
            elsif ( $1 eq '~,' ) {    # "~,"
                if ($in_group) {

                    if (IS_ASCII) {    # ASCII etc
                        $c[-1] .= "\x7F";
                    }
                    else {             # EBCDIC (cp 1047, 0037, POSIX-BC)
                        $c[-1] .= "\x07";
                    }
                }
                else {
                    $c[-1] .= '~,';
                }

            }
            elsif ( $1 eq '~' ) {      # possible only at string-end, it seems.
                $c[-1] .= '~';

            }
            else {

                my $text = $1;
                $text =~ s/\\/\\\\/g if $text =~ tr{\\}{};
                $c[-1] .= $text;
            }
        }
    }

    if ($call_count) {
        undef $big_pile;    # Well, nevermind that.
    }
    else {

        return \$big_pile;
    }

    die q{Last chunk isn't null??} if @c and length $c[-1];    # sanity
    DEBUG and warn scalar(@c), " chunks under closure\n";
    my $sub;
    if ( @code == 0 ) {                                        # not possible?
        DEBUG and warn "Empty code\n";
        return \'';
    }
    elsif ( scalar @code > 1 ) {                               # most cases, presumably!
        $sub = "sub { join '', map { defined \$_ ? \$_ : '' } @code }";
    }
    else {
        $sub = "sub { $code[0] }";
    }
    DEBUG and warn $sub;
    my $code;
    {
       use strict;
       $code = eval $sub;
       die "$@ while evalling" . $sub if $@;                      # Should be impossible.
    }
    return $code;
}


sub _die_pointing {

    my $target = shift;
    $target = ref($target) || $target;                         # class name

    my $i = index( $_[0], "\n" );

    my $pointy;
    my $pos = pos( $_[0] ) - ( defined( $_[2] ) ? $_[2] : 0 ) - 1;
    if ( $pos < 1 ) {
        $pointy = "^=== near there\n";
    }
    else {                                                     # we need to space over
        my $first_tab = index( $_[0], "\t" );
        if ( $pos > 2 and ( -1 == $first_tab or $first_tab > pos( $_[0] ) ) ) {

            $pointy = ( '=' x $pos ) . "^ near there\n";
        }
        else {

            $pointy = substr( $_[0], 0, $pos );
            $pointy =~ tr/\t //cd;

            $pointy .= "^=== near there\n";
        }
    }

    my $errmsg = "$_[1], in\:\n$_[0]";

    if ( $i == -1 ) {

        $errmsg .= "\n" . $pointy;
    }
    elsif ( $i == ( length( $_[0] ) - 1 ) ) {

        $errmsg .= $pointy;
    }
    else {

    }
    require Carp;
    Carp::croak("$errmsg via $target, as used");
}


1;

} # --- END Cpanel/CPAN/Locale/Maketext.pm


{ # --- BEGIN Cpanel/Locale/Utils/Normalize.pm
package Cpanel::Locale::Utils::Normalize;


use strict;
use warnings;


sub normalize_tag {
    my ($tag) = @_;
    return if !defined $tag;
    $tag =~ tr/A-Z/a-z/;
    $tag =~ tr{\r\n \t\f}{}d;
    if ( $tag =~ tr{a-z0-9}{}c ) {
        $tag =~ s{[^a-z0-9]+$}{};    # I18N::LangTags::locale2language_tag() does not allow trailing '_'
        $tag =~ tr{a-z0-9}{_}c;
    }

    if ( length $tag > 8 ) {
        while ( $tag =~ s/([^_]{8})([^_])/$1\_$2/ ) { }    # I18N::LangTags::locale2language_tag() only allows parts between 1 and 8 character
    }
    return $tag;
}

1;

} # --- END Cpanel/Locale/Utils/Normalize.pm


{ # --- BEGIN Cpanel/CPAN/Locales/Legacy.pm
package Cpanel::CPAN::Locales::Legacy;

use strict;


sub numf {
    my ( $self, $always_return ) = @_;
    my $class = ref($self) ? ref($self) : $self;
    $always_return ||= 0;
    $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'}   = '' if !defined $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'};
    $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} = '' if !defined $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'};

    if ( !$self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} || !$self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} ) {
        if ($always_return) {
            if ( $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} || !$self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} ) {
                return 2 if $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} eq '.';
                return 1;
            }
            elsif ( !$self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} || $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} ) {
                return 2 if $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} eq ',';
                return 1;
            }
            else {
                return 1;
            }
        }
    }

    if ( $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'decimal'} eq "\#\,\#\#0\.\#\#\#" ) {
        if ( $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} eq ',' && $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} eq '.' ) {
            return 1;
        }
        elsif ( $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} eq '.' && $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} eq ',' ) {
            return 2;
        }
    }
    elsif ( $always_return && $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} && $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} ) {
        return 2 if $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} eq ',';
        return 2 if $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} eq '.';
        return 1;
    }

    return [
        $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'decimal'},
        $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'},
        $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'},
    ];
}

1;

} # --- END Cpanel/CPAN/Locales/Legacy.pm


{ # --- BEGIN Cpanel/CPAN/Locales/DB/LocaleDisplayPattern/Tiny.pm
package Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny;

use strict;



$Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny::VERSION = '0.09';

$Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny::cldr_version = '2.0';

my %locale_display_lookup = (
    'ksh' => '{0} en {1}',
    'ja'  => '{0}({1})',
    'zh'  => '{0}({1})',
    'ko'  => '{0}({1})',
);

sub get_locale_display_pattern {
    if ( exists $locale_display_lookup{ $_[0] } ) {
        return $locale_display_lookup{ $_[0] };
    }
    else {
        require Cpanel::CPAN::Locales;
        my ($l) = Cpanel::CPAN::Locales::split_tag( $_[0] );
        if ( $l ne $_[0] ) {
            return $locale_display_lookup{$l} if exists $locale_display_lookup{$l};
        }
        return "\{0\}\ \(\{1\}\)";
    }
}

1;

} # --- END Cpanel/CPAN/Locales/DB/LocaleDisplayPattern/Tiny.pm


{ # --- BEGIN Cpanel/CPAN/Locales/DB/CharacterOrientation/Tiny.pm
package Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny;

use strict;



$Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny::VERSION = '0.09';

$Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny::cldr_version = '2.0';

my %rtl = (
    'ur' => '',
    'ku' => '',
    'he' => '',
    'fa' => '',
    'ps' => '',
    'ar' => '',
);

sub get_orientation {
    if ( exists $rtl{ $_[0] } ) {
        return 'right-to-left';
    }
    else {
        require Cpanel::CPAN::Locales;
        my ($l) = Cpanel::CPAN::Locales::split_tag( $_[0] );
        if ( $l ne $_[0] ) {
            return 'right-to-left' if exists $rtl{$l};
        }
        return 'left-to-right';
    }
}

1;

} # --- END Cpanel/CPAN/Locales/DB/CharacterOrientation/Tiny.pm


{ # --- BEGIN Cpanel/CPAN/Locales/Compile.pm
package Cpanel::CPAN::Locales::Compile;

use strict;
use warnings;

sub plural_rule_string_to_code {
    my ( $plural_rule_string, $return ) = @_;
    if ( !defined $return ) {
        $return = 1;
    }


    my %m;
    while ( $plural_rule_string =~ m/mod ([0-9]+)/g ) {

        $m{$1} = "( (\$_[0] % $1) + (\$_[0]-int(\$_[0])) )";
    }

    my $perl_code = "sub { if (";

    for my $or ( split /\s+or\s+/i, $plural_rule_string ) {
        my $and_exp;
        for my $and ( split /\s+and\s+/i, $or ) {
            my $copy = $and;
            my $n    = '$_[0]';

            $copy =~ s/ ?n is not / $n \!\= /g;
            $copy =~ s/ ?n is / $n \=\= /g;

            $copy =~ s/ ?n mod ([0-9]+) is not / $m{$1} \!\= /g;
            $copy =~ s/ ?n mod ([0-9]+) is / $m{$1} \=\= /g;

            $copy =~ s/ ?n not in ([0-9]+)\s*\.\.\s*([0-9]+) ?/ int\($n\) \!\= $n \|\| $n < $1 \|\| $n \> $2 /g;
            $copy =~ s/ ?n mod ([0-9]+) not in ([0-9]+)\s*\.\.\s*([0-9]+) ?/ int\($n\) \!\= $n \|\| $m{$1} < $2 \|\| $m{$1} \> $3 /g;

            $copy =~ s/ ?n not within ([0-9]+)\s*\.\.\s*([0-9]+) ?/ \($n < $1 \|\| $n > $2\) /g;
            $copy =~ s/ ?n mod ([0-9]+) not within ([0-9]+)\s*\.\.\s*([0-9]+) ?/ \($m{$1} < $2 \|\| $m{$1} > $3\) /g;

            $copy =~ s/ ?n in ([0-9]+)\s*\.\.\s*([0-9]+) ?/ int\($n\) \=\= $n \&\& $n \>\= $1 \&\& $n \<\= $2 /g;
            $copy =~ s/ ?n mod ([0-9]+) in ([0-9]+)\s*\.\.\s*([0-9]+) ?/ int\($n\) \=\= $n \&\& $m{$1} \>\= $2 \&\& $m{$1} \<\= $3 /g;

            $copy =~ s/ ?n within ([0-9]+)\s*\.\.\s*([0-9]+) ?/ $n \>\= $1 \&\& $n \<\= $2 /g;
            $copy =~ s/ ?n mod ([0-9]+) within ([0-9]+)\s*\.\.\s*([0-9]+) ?/ $m{$1} \>\= $2 \&\& $m{$1} \<\= $3 /g;

            if ( $copy eq $and ) {
                require Carp;
                Carp::carp("Unknown plural rule syntax");
                return;
            }
            else {
                $and_exp .= "($copy) && ";
            }
        }
        $and_exp =~ s/\s+\&\&\s*$//;

        if ($and_exp) {
            $perl_code .= " ($and_exp) || ";
        }
    }
    $perl_code =~ s/\s+\|\|\s*$//;

    $perl_code .= ") { return '$return'; } return;}";

    return $perl_code;
}

sub plural_rule_string_to_javascript_code {
    my ( $plural_rule_string, $return ) = @_;
    my $perl = plural_rule_string_to_code( $plural_rule_string, $return );
    $perl =~ s/sub \{ /function (n) \{/;
    $perl =~ s/\$_\[0\]/n/g;
    $perl =~ s/ \(n \% ([0-9]+)\) \+ \(n-int\(n\)\) /n % $1/g;
    $perl =~ s/int\(/parseInt\(/g;
    return $perl;
}

1;

} # --- END Cpanel/CPAN/Locales/Compile.pm


{ # --- BEGIN Cpanel/CPAN/Locales.pm
package Cpanel::CPAN::Locales;

use strict;

# use Cpanel::Locale::Utils::Normalize ();

$Cpanel::CPAN::Locales::VERSION      = 0.30_1;    # change in POD
$Cpanel::CPAN::Locales::cldr_version = '2.0';     # change in POD
my $FORCE_REGEX_LAZY = '';

*normalize_tag = *Cpanel::Locale::Utils::Normalize::normalize_tag;

my %singleton_stash;

sub get_cldr_version {
    return $Cpanel::CPAN::Locales::cldr_version;
}

sub new {
    my ( $class, $tag ) = @_;
    $tag = normalize_tag($tag) || 'en';

    if ( !exists $singleton_stash{$tag} ) {

        my $locale = {
            'locale' => $tag,
        };

        if ( my $soft = tag_is_soft_locale($tag) ) {

            $locale->{'soft_locale_fallback'} = $soft;
            $tag = $soft;
        }

        my $inc_class = ref($class) ? ref($class) : $class;
        $inc_class =~ s{\:\:|\'}{/}g;    # per Module::Want::get_inc_key()

        if ( !exists $INC{"$inc_class/DB/Language/$tag.pm"} ) {
            local $SIG{'__DIE__'};       # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
            eval "require $class\::DB::Language::$tag" || return;    # Module::Want::have_mod("$class\::DB::Language::$tag");
        }

        my ( $language, $territory ) = split_tag( $locale->{'locale'} );

        $locale->{'language'} = $language;
        {

            BEGIN { $^H = 0; };                                      # cheap no strict to allow for ref copy

            $locale->{'language_data'} = {
                'VERSION'      => \${"$class\::DB::Language::$tag\::VERSION"},
                'cldr_version' => \${"$class\::DB::Language::$tag\::cldr_version"},
                'misc_info'    => \%{"$class\::DB::Language::$tag\::misc_info"},
            };
        }
        $locale->{'territory'} = $territory;

        $locale->{'misc'}{'list_quote_mode'} = 'none';

        $singleton_stash{$tag} = bless $locale, $class;
    }

    return $singleton_stash{$tag};
}

sub _load_territory_data {
    my ($self) = @_;

    my $tag       = $self->{'locale'};
    my $class     = scalar ref $self;
    my $inc_class = $class;
    $inc_class =~ s{\:\:|\'}{/}g;    # per Module::Want::get_inc_key()

    if ( !exists $INC{"$inc_class/DB/Territory/$tag.pm"} ) {
        local $SIG{'__DIE__'};       # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require $class\::DB::Territory::$tag" || return;    # Module::Want::have_mod("$class\::DB::Language::$tag");
    }
    {

        BEGIN { $^H = 0; };                                       # cheap no strict to allow for ref copy

        $self->{'territory_data'} = {
            'VERSION'      => \${"$class\::DB::Territory::$tag\::VERSION"},
            'cldr_version' => \${"$class\::DB::Territory::$tag\::cldr_version"},
            'code_to_name' => \%{"$class\::DB::Territory::$tag\::code_to_name"},
        };
    }
    return 1;
}

sub _load_language_data_code_to_name {
    my ($self) = @_;

    my $tag       = $self->{'locale'};
    my $class     = scalar ref $self;
    my $inc_class = $class;
    $inc_class =~ s{\:\:|\'}{/}g;    # per Module::Want::get_inc_key()

    if ( !exists $INC{"$inc_class/DB/Language/code_to_name/$tag.pm"} ) {
        local $SIG{'__DIE__'};       # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require $class\::DB::Language::code_to_name::$tag" || return;    # Module::Want::have_mod("$class\::DB::Language::$tag");
    }

    {

        BEGIN { $^H = 0; };                                                    # cheap no strict to allow for ref copy
        $self->{'language_data'}{'code_to_name'} = \%{"$class\::DB::Language::$tag\::code_to_name"};
    }

    return 1;
}


sub get_soft_locale_fallback {
    return $_[0]->{'soft_locale_fallback'} if $_[0]->{'soft_locale_fallback'};
    return;
}

sub get_locale { shift->{'locale'} }

sub get_territory { shift->{'territory'} }

sub get_language { shift->{'language'} }

sub get_native_language_from_code {
    my ( $self, $code, $always_return ) = @_;

    my $class = ref($self) ? ref($self) : $self;
    if ( !exists $self->{'native_data'} ) {
        local $SIG{'__DIE__'};                            # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require $class\::DB::Native;" || return;    # Module::Want::have_mod("$class\::DB::Native");
        {

            BEGIN { $^H = 0; };                           # cheap no strict to allow for ref copy

            $self->{'native_data'} = {
                'VERSION'      => \${"$class\::DB::Native::VERSION"},
                'cldr_version' => \${"$class\::DB::Native::cldr_version"},
                'code_to_name' => \%{"$class\::DB::Native::code_to_name"},
            };
        }
    }

    $code ||= $self->{'locale'};
    $code = normalize_tag($code);
    return if !defined $code;

    $always_return ||= 1 if $code eq $self->get_locale() && $self->get_soft_locale_fallback();    # force $always_return under soft locale objects
    $always_return ||= 0;

    if ( exists $self->{'native_data'}{'code_to_name'}{$code} ) {
        return $self->{'native_data'}{'code_to_name'}{$code};
    }
    elsif ($always_return) {
        my ( $l, $t ) = split_tag($code);
        my $ln = $self->{'native_data'}{'code_to_name'}{$l};

        $self->_load_territory_data() if !$self->{'territory_data'};

        my $tn = defined $t ? $self->{'territory_data'}{'code_to_name'}{$t} : '';

        return $code if !$ln && !$tn;

        if ( defined $t ) {
            my $tmp = Cpanel::CPAN::Locales->new($l);    # if we even get to this point: this is a singleton so it is cheap
            if ($tmp) {
                if ( $tmp->get_territory_from_code($t) ) {
                    $tn = $tmp->get_territory_from_code($t);
                }
            }
        }

        $ln ||= $l;
        $tn ||= $t;

        my $string = get_locale_display_pattern_from_code_fast($code) || $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'locale'} || '{0} ({1})';

        substr( $string, index( $string, '{0}' ), 3, $ln ) while index( $string, '{0}' ) > -1;
        substr( $string, index( $string, '{1}' ), 3, $tn ) while index( $string, '{1}' ) > -1;

        return $string;
    }
    return;
}

sub numf {
    require Cpanel::CPAN::Locales::Legacy if !$INC{'Cpanel/CPAN/Locales/Legacy.pm'};
    *numf = *Cpanel::CPAN::Locales::Legacy::numf;
    goto \&Cpanel::CPAN::Locales::Legacy::numf;
}

my $get_locale_display_pattern_from_code_fast = 0;

sub get_locale_display_pattern_from_code_fast {
    if ( !$get_locale_display_pattern_from_code_fast ) {
        $get_locale_display_pattern_from_code_fast++;
        require Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny;
    }

    if ( @_ == 1 && ref( $_[0] ) ) {
        return Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny::get_locale_display_pattern( $_[0]->get_locale() );
    }
    return Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny::get_locale_display_pattern( $_[-1] );    # last arg so it works as function or class method or object method
}

sub get_locale_display_pattern_from_code {
    my ( $self, $code, $always_return ) = @_;

    my $class = ref($self) ? ref($self) : $self;
    if ( !exists $self->{'locale_display_pattern_data'} ) {
        local $SIG{'__DIE__'};                                                                             # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require $class\::DB::LocaleDisplayPattern;" || return;                                       # Module::Want::have_mod("$class\::DB::LocaleDisplayPattern");

        {

            BEGIN { $^H = 0; };                                                                            # cheap no strict to allow for ref copy

            $self->{'locale_display_pattern_data'} = {
                'VERSION'         => \${"$class\::DB::LocaleDisplayPattern::VERSION"},
                'cldr_version'    => \${"$class\::DB::LocaleDisplayPattern::cldr_version"},
                'code_to_pattern' => \%{"$class\::DB::LocaleDisplayPattern::code_to_pattern"},
            };
        }
    }

    $code ||= $self->{'locale'};
    $code = normalize_tag($code);
    return if !defined $code;

    $always_return ||= 1 if $code eq $self->get_locale() && $self->get_soft_locale_fallback();    # force $always_return under soft locale objects
    $always_return ||= 0;

    if ( exists $self->{'locale_display_pattern_data'}{'code_to_pattern'}{$code} ) {
        return $self->{'locale_display_pattern_data'}{'code_to_pattern'}{$code};
    }
    elsif ($always_return) {
        my ( $l, $t ) = split_tag($code);
        if ( exists $self->{'locale_display_pattern_data'}{'code_to_pattern'}{$l} ) {
            return $self->{'locale_display_pattern_data'}{'code_to_pattern'}{$l};
        }
        return '{0} ({1})';
    }
    return;
}

my $get_character_orientation_from_code_fast = 0;

sub get_character_orientation_from_code_fast {
    if ( !$get_character_orientation_from_code_fast ) {
        $get_character_orientation_from_code_fast++;
        require Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny;
    }

    if ( @_ == 1 && ref( $_[0] ) ) {
        return Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny::get_orientation( $_[0]->get_locale() );
    }

    return Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny::get_orientation( $_[-1] );    # last arg so it works as function or class method or object method
}

sub get_character_orientation_from_code {
    my ( $self, $code, $always_return ) = @_;

    my $class = ref($self) ? ref($self) : $self;
    if ( !exists $self->{'character_orientation_data'} ) {
        local $SIG{'__DIE__'};                                                                  # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require $class\::DB::CharacterOrientation;" || return;                            # Module::Want::have_mod("$class\::DB::CharacterOrientation");
        {

            BEGIN { $^H = 0; };                                                                 # cheap no strict to allow for ref copy

            $self->{'character_orientation_data'} = {
                'VERSION'      => \${"$class\::DB::CharacterOrientation::VERSION"},
                'cldr_version' => \${"$class\::DB::CharacterOrientation::cldr_version"},
                'code_to_name' => \%{"$class\::DB::CharacterOrientation::code_to_name"},
            };
        }
    }

    $code ||= $self->{'locale'};
    $code = normalize_tag($code);
    return if !defined $code;

    $always_return ||= 1 if $code eq $self->get_locale() && $self->get_soft_locale_fallback();    # force $always_return under soft locale objects
    $always_return ||= 0;

    if ( exists $self->{'character_orientation_data'}{'code_to_name'}{$code} ) {
        return $self->{'character_orientation_data'}{'code_to_name'}{$code};
    }
    elsif ($always_return) {
        my ( $l, $t ) = split_tag($code);
        if ( exists $self->{'character_orientation_data'}{'code_to_name'}{$l} ) {
            return $self->{'character_orientation_data'}{'code_to_name'}{$l};
        }
        return 'left-to-right';
    }
    return;
}

sub get_plural_form_categories {
    return @{ $_[0]->{'language_data'}{'misc_info'}{'plural_forms'}{'category_list'} };
}

sub supports_special_zeroth {
    return 1 if $_[0]->get_plural_form(0) eq 'other';
    return;
}

sub plural_category_count {
    return scalar( $_[0]->get_plural_form_categories() );
}

sub get_plural_form {
    my ( $self, $n, @category_values ) = @_;
    my $category;
    my $has_extra_for_zero = 0;

    my $abs_n = abs($n);    # negatives keep same category as positive

    if ( !$self->{'language_data'}{'misc_info'}{'plural_forms'}{'category_rules_function'} ) {
        $self->{'language_data'}{'misc_info'}{'plural_forms'}{'category_rules_function'} = Cpanel::CPAN::Locales::plural_rule_hashref_to_code( $self->{'language_data'}{'misc_info'}{'plural_forms'} );
        if ( !defined $self->{'language_data'}{'misc_info'}{'plural_forms'}{'category_rules_function'} ) {
            require Carp;
            Carp::carp("Could not determine plural logic.");
        }
    }

    $category = $self->{'language_data'}{'misc_info'}{'plural_forms'}{'category_rules_function'}->($abs_n);

    my @categories = $self->get_plural_form_categories();

    if ( !@category_values ) {

        @category_values = @categories;
    }
    else {
        my $cat_len = @categories;
        my $val_len = @category_values;
        if ( $val_len == ( $cat_len + 1 ) ) {
            $has_extra_for_zero++;
        }
        elsif ( $cat_len != $val_len && $self->{'verbose'} ) {
            require Carp;
            Carp::carp("The number of given values ($val_len) does not match the number of categories ($cat_len).");
        }
    }

    if ( !defined $category ) {
        my $cat_idx = $has_extra_for_zero && $abs_n != 0 ? -2 : -1;
        return wantarray ? ( $category_values[$cat_idx], $has_extra_for_zero && $abs_n == 0 ? 1 : 0 ) : $category_values[$cat_idx];
    }
    else {
      GET_POSITION:
        my $cat_pos_in_list;
        my $index = -1;
      CATEGORY:
        for my $cat (@categories) {
            $index++;
            if ( $cat eq $category ) {
                $cat_pos_in_list = $index;
                last CATEGORY;
            }
        }

        if ( !defined $cat_pos_in_list && $category ne 'other' ) {
            require Carp;
            Carp::carp("The category ($category) is not used by this locale.");
            $category = 'other';
            goto GET_POSITION;
        }
        elsif ( !defined $cat_pos_in_list ) {
            my $cat_idx = $has_extra_for_zero && $abs_n != 0 ? -2 : -1;
            return wantarray ? ( $category_values[$cat_idx], $has_extra_for_zero && $abs_n == 0 ? 1 : 0 ) : $category_values[$cat_idx];
        }
        else {
            if ( $has_extra_for_zero && $category eq 'other' ) {    # and 'other' is at the end of the list? nah...  && $cat_pos_in_list + 1 == $#category_values
                my $cat_idx = $has_extra_for_zero && $abs_n == 0 ? -1 : $cat_pos_in_list;
                return wantarray ? ( $category_values[$cat_idx], $has_extra_for_zero && $abs_n == 0 ? 1 : 0 ) : $category_values[$cat_idx];
            }
            else {
                return wantarray ? ( $category_values[$cat_pos_in_list], 0 ) : $category_values[$cat_pos_in_list];
            }
        }
    }
}

sub _quote_get_list_items {
    my ( $self, $items_ar ) = @_;

    my $cnt = 0;

    if ( exists $self->{'misc'}{'list_quote_mode'} && $self->{'misc'}{'list_quote_mode'} ne 'none' ) {
        if ( $self->{'misc'}{'list_quote_mode'} eq 'all' ) {
            @{$items_ar} = ('') if @{$items_ar} == 0;

            for my $i ( 0 .. scalar( @{$items_ar} ) - 1 ) {
                $items_ar->[$i] = '' if !defined $items_ar->[$i];
                $items_ar->[$i] = $self->quote( $items_ar->[$i] );
                $cnt++;
            }
        }
        elsif ( $self->{'misc'}{'list_quote_mode'} eq 'some' ) {
            @{$items_ar} = ('') if @{$items_ar} == 0;

            for my $i ( 0 .. scalar( @{$items_ar} ) - 1 ) {
                $items_ar->[$i] = '' if !defined $items_ar->[$i];
                if ( $items_ar->[$i] eq '' || $items_ar->[$i] eq ' ' || $items_ar->[$i] eq "\xc2\xa0" ) {
                    $items_ar->[$i] = $self->quote( $items_ar->[$i] );
                    $cnt++;
                }
            }
        }
        else {
            require Carp;
            Carp::carp('$self->{misc}{list_quote_mode} is set to an unknown value');
        }
    }

    return $cnt;
}

sub get_list_and {
    my $self = shift;

    return $self->_get_list_joined(
        $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list'},
        @_,
    );
}

sub get_list_or {
    my $self = shift;

    return $self->_get_list_joined(
        $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list_or'},
        @_,
    );
}

sub _get_list_joined {
    my ( $self, $templates_hr, @items ) = @_;

    $self->_quote_get_list_items( \@items );

    return if !@items;
    return $items[0] if @items == 1;

    my $ix;    # used to cache index results in the following oneliner

    if ( @items == 2 ) {
        my $two = $templates_hr->{'2'};
        substr( $two, $ix, 3, $items[0] ) while ( $ix = index( $two, '{0}' ) ) > -1;
        substr( $two, $ix, 3, $items[1] ) while ( $ix = index( $two, '{1}' ) ) > -1;
        return $two;
    }
    else {
        for (@items) {
            next if !defined $_;
            substr( $_, $ix, 3, '__{__0__}__' ) while ( $ix = index( $_, '{0}' ) ) > -1;
            substr( $_, $ix, 3, '__{__1__}__' ) while ( $ix = index( $_, '{1}' ) ) > -1;
        }
        my $aggregate = $templates_hr->{'start'};
        substr( $aggregate, $ix, 3, $items[0] ) while ( $ix = index( $aggregate, '{0}' ) ) > -1;
        substr( $aggregate, $ix, 3, $items[1] ) while ( $ix = index( $aggregate, '{1}' ) ) > -1;

        for my $i ( 2 .. $#items ) {
            next if $i == $#items;
            my $middle = $templates_hr->{'middle'};
            substr( $middle, $ix, 3, $aggregate ) while ( $ix = index( $middle, '{0}' ) ) > -1;
            my $item = defined $items[$i] ? $items[$i] : '';
            substr( $middle, $ix, 3, $item ) while ( $ix = index( $middle, '{1}' ) ) > -1;
            $aggregate = $middle;
        }

        my $end = $templates_hr->{'end'};
        substr( $end, $ix, 3, $aggregate ) while ( $ix = index( $end, '{0}' ) ) > -1;
        substr( $end, $ix, 3, $items[-1] ) while ( $ix = index( $end, '{1}' ) ) > -1;

        substr( $end, $ix, 11, '{0}' ) while ( $ix = index( $end, '__{__0__}__' ) ) > -1;
        substr( $end, $ix, 11, '{1}' ) while ( $ix = index( $end, '__{__1__}__' ) ) > -1;

        return $end;
    }
}

sub quote {
    my ( $self, $value ) = @_;
    $value = '' if !defined $value;

    return $self->{'language_data'}{'misc_info'}{'delimiters'}{'quotation_start'} . $value . $self->{'language_data'}{'misc_info'}{'delimiters'}{'quotation_end'};
}

sub quote_alt {
    my ( $self, $value ) = @_;
    $value = '' if !defined $value;

    return $self->{'language_data'}{'misc_info'}{'delimiters'}{'alternate_quotation_start'} . $value . $self->{'language_data'}{'misc_info'}{'delimiters'}{'alternate_quotation_end'};
}

sub get_formatted_ellipsis_initial {
    my ( $self, $str ) = @_;
    my $pattern = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'ellipsis'}{'initial'} || '…{0}';
    substr( $pattern, index( $pattern, '{0}' ), 3, $str ) while index( $pattern, '{0}' ) > -1;
    return $pattern;
}

sub get_formatted_ellipsis_medial {
    my ($self) = @_;    # my ($self, $first, $second) = @_;
    my $pattern = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'ellipsis'}{'medial'} || '{0}…{1}';

    substr( $pattern, index( $pattern, '{0}' ), 3, $_[1] ) while index( $pattern, '{0}' ) > -1;
    substr( $pattern, index( $pattern, '{1}' ), 3, $_[2] ) while index( $pattern, '{1}' ) > -1;
    return $pattern;
}

sub get_formatted_ellipsis_final {
    my ( $self, $str ) = @_;
    my $pattern = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'ellipsis'}{'final'} || '{0}…';
    substr( $pattern, index( $pattern, '{0}' ), 3, $str ) while index( $pattern, '{0}' ) > -1;
    return $pattern;
}


sub get_formatted_decimal {
    my ( $self, $n, $max_decimal_places, $_my_pattern ) = @_;    # $_my_pattern not documented on purpose, it is only intended for internal use, and may dropepd/changed at any time


    return if !defined $n;



    my $is_negative = $n < 0 ? 1 : 0;

    my $max_len = defined $max_decimal_places ? abs( int($max_decimal_places) ) : 6;    # %f default is 6
    $max_len = 14 if $max_len > 14;

    if ( $n > 10_000_000_000 || $n < -10_000_000_000 ) {

        return $n if $n =~ tr/Ee//;                                                     # poor man's is exponential check.


        if ( $n =~ m/\.([0-9]{$max_len})([0-9])?/ ) {
            my $trim = $1;    # (defined $2 && $2 > 4) ? $1 + 1 : $1;

            if ( defined $2 && $2 > 4 ) {
                if ( ( $trim + 1 ) !~ tr/Ee// ) {    # poor man's is exponential check.
                    $trim++;
                }
            }

            $n =~ s/$FORCE_REGEX_LAZY\.[0-9]+/\.$trim/o;
        }
    }
    else {
        return $n if length $n < 3 && $n !~ tr{0-9}{}c;

        $n = sprintf( '%.' . $max_len . 'f', $n );

        return $n if $n =~ tr/Ee//;    # poor man's is exponential check.
    }

    $n =~ s{$FORCE_REGEX_LAZY([^0-9]+[0-9]*?[1-9])0+$}{$1}o;
    $n =~ s{$FORCE_REGEX_LAZY[^0-9]+0+$}{}o;

    if ( $n =~ tr{.0-9}{}c ) {    # Only strip signs if the string has non-numeric and '.' characters such as '+' or '-'
        substr( $n, 0, 1, '' ) while substr( $n, 1 ) =~ tr{0-9}{}c;
    }

    my $cldr_formats = $self->{'language_data'}{'misc_info'}{'cldr_formats'};

    my $format = $_my_pattern || $cldr_formats->{'decimal'};    # from http://unicode.org/repos/cldr-tmp/trunk/diff/by_type/number.pattern.html

    my ( $zero_positive_pat, $negative_pat, $err ) = split( /$FORCE_REGEX_LAZY(?<!\')\;(?!\')/o, $format );    # semi-colon that is not literal (?<!\')\;(?!\')

    if ($err) {
        require Carp;
        Carp::carp("Format had more than 2 pos/neg sections. Using default pattern.");
        $format = '#,##0.###';
    }
    elsif ( $is_negative && $negative_pat ) {
        $format = $negative_pat;
    }
    elsif ($zero_positive_pat) {
        $format = $zero_positive_pat;
    }

    my $dec_sec_cnt = 0;
    if ( index( $format, q{'} ) == -1 ) {
        $dec_sec_cnt = $format =~ tr{\.}{};
    }
    else {
        $dec_sec_cnt++ while ( $format =~ m/$FORCE_REGEX_LAZY(?<!\')\.(?!\')/og );
    }

    if ( $dec_sec_cnt != 1 ) {
        require Carp;
        Carp::carp("Format should have one decimal section. Using default pattern.");
        $format = '#,##0.###';
    }

    if ( !length $format || $format !~ tr{ \t\r\n\f}{}c ) {
        require Carp;
        Carp::carp("Format is empty. Using default pattern.");
        $format = '#,##0.###';
    }


    my $result = '';

    if ( $format eq '#,##0.###' ) {
        $result = $n;
        if ( $n =~ tr{0-9}{} > 3 ) {
            while ( $result =~ s/$FORCE_REGEX_LAZY^([-+]?\d+)(\d{3})/$1,$2/os ) { 1 }    # right from perlfaq5
        }
    }
    else {




        my ( $integer, $decimals ) = split( /\./, $n, 2 );

        my ( $i_pat, $d_pat ) = split( /$FORCE_REGEX_LAZY(?<!\')\.(?!\')/o, $format, 2 );
        my ( $cur_idx, $trailing_non_n, $cur_d, $cur_pat ) = ( 0, '' );    # buffer

        my @i_pat = reverse( split( /$FORCE_REGEX_LAZY(?<!\')\,(?!\')/o, $i_pat ) );

        my $next_to_last_pattern = @i_pat == 1 ? $i_pat[0] : $i_pat[-2];
        substr( $next_to_last_pattern, -1, 1, '#' ) if substr( $next_to_last_pattern, -1 ) eq '0';
        while ( $i_pat[0] =~ s/$FORCE_REGEX_LAZY((?:\'.\')+)$//o || $i_pat[0] =~ s/$FORCE_REGEX_LAZY([^0#]+)$//o ) {
            $trailing_non_n = "$1$trailing_non_n";
        }


        while ( CORE::length( $cur_d = CORE::substr( $integer, -1, 1, '' ) ) ) {


            if ( $cur_idx == $#i_pat && !CORE::length( $i_pat[$cur_idx] ) ) {
                $i_pat[$cur_idx] = $next_to_last_pattern;
            }

            if ( !CORE::length( $i_pat[$cur_idx] ) ) {    # this chunk is spent
                if ( defined $i_pat[ $cur_idx + 1 ] ) {    # there are more chunks ...
                    $cur_idx++;                            # ... next chunk please
                }
            }

            if ( CORE::length( $i_pat[$cur_idx] ) ) {

                if ( substr( $i_pat[$cur_idx], -3 ) eq q{','} ) {
                    $result = CORE::substr( $i_pat[$cur_idx], -3, 3, '' ) . $result;
                    redo;
                }

                $cur_pat = CORE::substr( $i_pat[$cur_idx], -1, 1, '' );

                if ( $cur_pat ne '0' && $cur_pat ne '#' ) {
                    $result = "$cur_pat$result";
                    redo;
                }
            }

            $result = !CORE::length( $i_pat[$cur_idx] ) && @i_pat != 1 ? ",$cur_d$result" : "$cur_d$result";

            if ( $cur_idx == $#i_pat - 1 && $i_pat[$#i_pat] eq '#' && !CORE::length( $i_pat[$cur_idx] ) ) {
                $cur_idx++;
                $i_pat[$cur_idx] = $next_to_last_pattern;
            }
        }
        if ( CORE::length( $i_pat[$cur_idx] ) ) {
            $i_pat[$cur_idx] =~ s/$FORCE_REGEX_LAZY(?<!\')\#(?!\')//og;    # remove any left over non-literal #
            $result = $result . $i_pat[$cur_idx];        # prepend it (e.g. 0 and -)
        }
        if ( substr( $result, 0, 1 ) eq ',' ) {
            substr( $result, 0, 1, '' );
        }
        $result .= $trailing_non_n;

        if ( defined $decimals && CORE::length($decimals) ) {

            my @d_pat = ($d_pat);                        # TODO ? support sepeartor in decimal, !definedvia CLDR, no patterns have that ATM ? split( /(?<!\')\,(?!\')/, $d_pat );

            $result .= '.';
            $cur_idx        = 0;
            $trailing_non_n = '';

            while ( $d_pat[-1] =~ s/$FORCE_REGEX_LAZY((?:\'.\')+)$//o || $d_pat[-1] =~ s/$FORCE_REGEX_LAZY([^0#]+)$//o ) {
                $trailing_non_n = "$1$trailing_non_n";
            }


            while ( CORE::length( $cur_d = CORE::substr( $decimals, 0, 1, '' ) ) ) {


                if ( !CORE::length( $d_pat[$cur_idx] ) ) {    # this chunk is spent
                    if ( !defined $d_pat[ $cur_idx + 1 ] ) {    # there are no more chunks
                        $cur_pat = '#';
                    }
                    else {                                      # next chunk please
                        $result .= ',';
                        $cur_idx++;
                    }
                }

                if ( CORE::length( $d_pat[$cur_idx] ) ) {

                    if ( index( $d_pat[$cur_idx], q{'.'} ) == 0 ) {
                        $result .= CORE::substr( $d_pat[$cur_idx], 0, 3, '' );
                        redo;
                    }
                    $cur_pat = CORE::substr( $d_pat[$cur_idx], 0, 1, '' );
                    if ( $cur_pat ne '0' && $cur_pat ne '#' ) {
                        $result .= $cur_pat;
                        redo;
                    }
                }

                $result .= $cur_d;
            }
            if ( substr( $result, -1, ) eq ',' ) {
                chop($result);
            }
            if ( defined $d_pat[$cur_idx] ) {
                $d_pat[$cur_idx] =~ s/$FORCE_REGEX_LAZY(?<!\')\#(?!\')//og;    # remove any left over non-literal #
                $result .= $d_pat[$cur_idx];                 # append it (e.g. 0 and -)
            }
            $result .= $trailing_non_n;
        }

    }

    my $used_place_holder = $cldr_formats->{_decimal_format_decimal} ne '.' && index( $result, '.' ) > -1 && $result =~ s/$FORCE_REGEX_LAZY(?<!\')\.(?!\')/_LOCALES-DECIMAL-PLACEHOLDER_/g;

    if ( $cldr_formats->{_decimal_format_group} ne ',' && index( $result, ',' ) > -1 ) {
        $result =~ s/$FORCE_REGEX_LAZY(?<!\')\,(?!\')/$cldr_formats->{_decimal_format_group}/og;
    }
    if ($used_place_holder) {
        my $ix;
        substr( $result, $ix, 29, $cldr_formats->{_decimal_format_decimal} ) while ( $ix = index( $result, '_LOCALES-DECIMAL-PLACEHOLDER_' ) ) > -1;
    }


    if ( $is_negative && !$negative_pat ) {

        $result = "-$result";
    }

    return $result;
}


sub get_territory_codes {
    $_[0]->_load_territory_data() if !$_[0]->{'territory_data'};

    return keys %{ shift->{'territory_data'}{'code_to_name'} };
}

sub get_territory_names {
    $_[0]->_load_territory_data() if !$_[0]->{'territory_data'};

    return values %{ shift->{'territory_data'}{'code_to_name'} };
}

sub get_territory_lookup {
    $_[0]->_load_territory_data() if !$_[0]->{'territory_data'};

    return %{ shift->{'territory_data'}{'code_to_name'} };
}

sub get_territory_from_code {
    my ( $self, $code, $always_return ) = @_;

    $code ||= $self->{'territory'};
    $code = normalize_tag($code);
    return if !defined $code;

    $self->_load_territory_data() if !$self->{'territory_data'};

    if ( exists $self->{'territory_data'}{'code_to_name'}{$code} ) {
        return $self->{'territory_data'}{'code_to_name'}{$code};
    }
    elsif ( !defined $self->{'territory'} || $code ne $self->{'territory'} ) {
        my ( $l, $t ) = split_tag($code);
        if ( $t && exists $self->{'territory_data'}{'code_to_name'}{$t} ) {
            return $self->{'territory_data'}{'code_to_name'}{$t};
        }
    }
    return $code if $always_return;
    return;
}

sub get_code_from_territory {
    my ( $self, $name ) = @_;
    return if !$name;
    my $key = normalize_for_key_lookup($name);

    $self->_load_territory_data() if !$self->{'territory_data'};

    if ( !$self->{'territory_data'}{'nam'} ) {
        $self->{'territory_data'}{'name_to_code'} = { map { normalize_for_key_lookup( $self->{'territory_data'}{'code_to_name'}->{$_} ) => $_ } keys %{ $self->{'territory_data'}{'code_to_name'} } };
    }
    if ( exists $self->{'territory_data'}{'name_to_code'}{$key} ) {
        return $self->{'territory_data'}{'name_to_code'}{$key};
    }
    return;
}

{
    no warnings 'once';
    *code2territory = *get_territory_from_code;
    *territory2code = *get_code_from_territory;
}


sub get_language_codes {
    $_[0]->_load_language_data_code_to_name() if !$_[0]->{'language_data'}{'code_to_name'};
    return keys %{ $_[0]->{'language_data'}{'code_to_name'} };
}

sub get_language_names {
    $_[0]->_load_language_data_code_to_name() if !$_[0]->{'language_data'}{'code_to_name'};
    return values %{ $_[0]->{'language_data'}{'code_to_name'} };
}

sub get_language_lookup {
    $_[0]->_load_language_data_code_to_name() if !$_[0]->{'language_data'}{'code_to_name'};
    return %{ $_[0]->{'language_data'}{'code_to_name'} };
}

sub get_language_from_code {
    my ( $self, $code, $always_return ) = @_;

    $code ||= $self->{'locale'};
    $code = normalize_tag($code);
    return if !defined $code;

    $always_return ||= 1 if $code eq $self->get_locale() && $self->get_soft_locale_fallback();    # force $always_return under soft locale objects
    $always_return ||= 0;

    $self->_load_language_data_code_to_name() if !$_[0]->{'language_data'}{'code_to_name'};
    if ( exists $self->{'language_data'}{'code_to_name'}{$code} ) {
        return $self->{'language_data'}{'code_to_name'}{$code};
    }
    elsif ($always_return) {
        $self->_load_territory_data() if !$self->{'territory_data'};

        my ( $l, $t ) = split_tag($code);
        my $ln = $self->{'language_data'}{'code_to_name'}{$l};
        my $tn = defined $t ? $self->{'territory_data'}{'code_to_name'}{$t} : '';

        return $code if !$ln && !$tn;
        $ln ||= $l;
        $tn ||= $t;

        my $string = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'locale'} || '{0} ({1})';

        substr( $string, index( $string, '{0}' ), 3, $ln ) while index( $string, '{0}' ) > -1;
        substr( $string, index( $string, '{1}' ), 3, $tn ) while index( $string, '{1}' ) > -1;

        return $string;
    }
    return;
}

sub get_code_from_language {
    my ( $self, $name ) = @_;
    return if !$name;
    my $key = normalize_for_key_lookup($name);

    $self->_load_language_data_code_to_name() if !$_[0]->{'language_data'}{'code_to_name'};
    if ( !$self->{'language_data'}{'name_to_code'} ) {
        $self->{'language_data'}{'name_to_code'} = { map { normalize_for_key_lookup( $self->{'language_data'}{'code_to_name'}->{$_} ) => $_ } keys %{ $self->{'language_data'}{'code_to_name'} } };
    }

    if ( exists $self->{'language_data'}{'name_to_code'}{$key} ) {
        return $self->{'language_data'}{'name_to_code'}{$key};
    }
    return;
}

{
    no warnings 'once';
    *code2language = *get_language_from_code;
    *language2code = *get_code_from_language;
}


sub tag_is_soft_locale {
    my ($tag) = @_;
    my ( $l, $t ) = split_tag($tag);

    return if !defined $l;    # invalid tag is not soft

    return if !$t;                             # no territory part means it is not soft
    return if tag_is_loadable($tag);           # if it can be loaded directly then it is not soft
    return if !territory_code_is_known($t);    # if the territory part is not known then it is not soft
    return if !tag_is_loadable($l);            # if the language part is not known then it is not soft
    return $l;                                 # it is soft, so return the value suitable for 'soft_locale_fallback'
}

sub tag_is_loadable {
    my ( $tag, $as_territory ) = @_;           # not documenting internal $as_territory, just use territory_code_is_known() directly

    if ( !exists $INC{"Cpanel/CPAN/Locales/DB/Loadable.pm"} ) {
        local $SIG{'__DIE__'};                 # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require Cpanel::CPAN::Locales::DB::Loadable" || return;    # Module::Want::have_mod("Cpanel::CPAN::Locales::DB::Loadable") || return;
    }

    if ($as_territory) {
        no warnings 'once';
        return 1 if exists $Cpanel::CPAN::Locales::DB::Loadable::territory{$tag};
    }
    else {
        return 1 if exists $Cpanel::CPAN::Locales::DB::Loadable::code{$tag};
    }

    return;
}

sub get_loadable_language_codes {
    if ( !exists $INC{"Cpanel/CPAN/Locales/DB/Loadable.pm"} ) {
        local $SIG{'__DIE__'};    # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
        eval "require Cpanel::CPAN::Locales::DB::Loadable" || return;    # Module::Want::have_mod("Cpanel::CPAN::Locales::DB::Loadable") || return;
    }

    return keys %Cpanel::CPAN::Locales::DB::Loadable::code;
}

sub territory_code_is_known {
    return tag_is_loadable( $_[0], 1 );
}

sub split_tag {
    return split( /_/, normalize_tag( $_[0] ), 2 );                      # we only do language[_territory]
}

sub get_i_tag_for_string {
    my $norm = normalize_tag( $_[0] );

    if ( substr( $norm, 0, 2 ) eq 'i_' ) {
        return $norm;
    }
    else {
        return 'i_' . $norm;
    }
}

my %non_locales = (
    'und' => 1,
    'zxx' => 1,
    'mul' => 1,
    'mis' => 1,
    'art' => 1,
);

sub non_locale_list {
    return ( sort keys %non_locales );
}

sub is_non_locale {
    my $tag = normalize_tag( $_[0] ) || return;
    return 1 if exists $non_locales{$tag};
    return;
}

sub typical_en_alias_list {
    return ( 'en_us', 'i_default' );
}

sub is_typical_en_alias {
    my $tag = normalize_tag( $_[0] ) || return;
    return 1 if $tag eq 'en_us' || $tag eq 'i_default';
    return;
}

sub normalize_tag_for_datetime_locale {
    my ( $pre, $pst ) = split_tag( $_[0] );    # we only do language[_territory]
    return if !defined $pre;

    if ($pst) {
        return $pre . '_' . uc($pst);
    }
    else {
        return $pre;
    }
}

sub normalize_tag_for_ietf {
    my ( $pre, $pst ) = split_tag( $_[0] );    # we only do language[_territory]
    return if !defined $pre;

    if ($pst) {
        return $pre . '-' . uc($pst);
    }
    else {
        return $pre;
    }
}

sub normalize_for_key_lookup {
    my $key = $_[0];
    return '' if !defined $key;
    $key =~ tr/A-Z/a-z/;                            # lowercase
    $key =~ s{\s+}{}g if $key =~ tr{ \t\r\n\f}{};
    $key =~ tr{\'\"\-\(\)\[\]\_}{}d;
    return $key;
}

sub plural_rule_string_to_javascript_code {
    require Cpanel::CPAN::Locales::Compile;
    *plural_rule_string_to_javascript_code = \&Cpanel::CPAN::Locales::Compile::plural_rule_string_to_javascript_code;
    goto \&Cpanel::CPAN::Locales::Compile::plural_rule_string_to_javascript_code;
}

sub plural_rule_string_to_code {
    require Cpanel::CPAN::Locales::Compile;
    *plural_rule_string_to_code = \&Cpanel::CPAN::Locales::Compile::plural_rule_string_to_code;
    goto \&Cpanel::CPAN::Locales::Compile::plural_rule_string_to_code;
}

sub plural_rule_hashref_to_code {
    my ($hr) = @_;

    if ( ref( $hr->{'category_rules'} ) ne 'HASH' ) {

        $hr->{'category_rules_compiled'} = {
            'one' => q{sub { return 'one' if ( ( $n == 1 ) ); return;};},
        };

        return sub {

            my ($n) = @_;
            return 'one' if $n == 1;
            return;
        };
    }
    else {
        for my $cat ( get_cldr_plural_category_list(1) ) {
            next if !exists $hr->{'category_rules'}{$cat};
            next if exists $hr->{'category_rules_compiled'}{$cat};
            $hr->{'category_rules_compiled'}{$cat} = plural_rule_string_to_code( $hr->{'category_rules'}{$cat}, $cat );
        }

        return sub {
            my ($n) = @_;
            my $match;
          PCAT:
            for my $cat ( get_cldr_plural_category_list(1) ) {    # use function instead of keys to preserve processing order
                next if !exists $hr->{'category_rules_compiled'}{$cat};


                if ( ref( $hr->{'category_rules_compiled'}{$cat} ) ne 'CODE' ) {
                    local $SIG{'__DIE__'};                        # cpanel specific: ensure a benign eval does not trigger cpsrvd's DIE handler (may be made moot by internal case 50857)
                    $hr->{'category_rules_compiled'}{$cat} = eval "$hr->{'category_rules_compiled'}{$cat}";    ## no critic (ProhibitStringyEval) # As of 0.22 this will be skipped for modules included w/ the main dist
                }

                if ( $hr->{'category_rules_compiled'}{$cat}->($n) ) {
                    $match = $cat;
                    last PCAT;
                }
            }

            return $match if $match;
            return;
        };
    }
}

sub get_cldr_plural_category_list {

    return qw(zero one two few many other) if $_[0];    # check order

    return qw(one two few many other zero);    # quant() arg order
}

sub get_fallback_list {
    my ( $self, $special_lookup ) = @_;

    my ( $super, $ter ) = split_tag( $self->{'locale'} );
    return (
        $self->{'locale'},
        ( $super ne $self->{'locale'} && $super ne 'i' ? $super : () ),
        ( @{ $self->{'language_data'}{'misc_info'}{'fallback'} } ),
        (
            defined $special_lookup && ref($special_lookup) eq 'CODE'
            ? ( map { my $n = Cpanel::Locale::Utils::Normalize::normalize_tag($_); $n ? ($n) : () } $special_lookup->( $self->{'locale'} ) )
            : ()
        ),
        'en'
    );
}

sub get_cldr_number_symbol_decimal {
    return $_[0]->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_decimal'} || '.';
}

sub get_cldr_number_symbol_group {
    return $_[0]->{'language_data'}{'misc_info'}{'cldr_formats'}{'_decimal_format_group'} || ',';
}

1;


} # --- END Cpanel/CPAN/Locales.pm


{ # --- BEGIN Cpanel/CPAN/Locale/Maketext/Utils.pm
package Cpanel::CPAN::Locale::Maketext::Utils;


$Cpanel::CPAN::Locale::Maketext::Utils::VERSION = 0.33_95;

# use Cpanel::CPAN::Locale::Maketext 1.13_89 ();    # our 1.13_89 contains some optimizations and support for external_lex_cache that made its way to CPAN by v1.22

@Cpanel::CPAN::Locale::Maketext::Utils::ISA = qw(Cpanel::CPAN::Locale::Maketext);

use constant LOCALE_FALLBACK_CACHE_DIR => '/usr/local/cpanel/etc/locale/fallback';
my $FORCE_REGEX_LAZY = '';

my %singleton_stash = ();

sub _compile {
    my ( $lh, $string ) = @_;

    substr( $string, index( $string, '_TILDE_' ), 7, '~~' ) while index( $string, '_TILDE_' ) > -1;    # this helps make parsing easier (via code or visually)

    my $compiled = $lh->SUPER::_compile($string);

    return $compiled if ref($compiled) ne 'CODE';

    return sub {
        return $compiled->( $_[0], @_[ 1 .. $#_ ] ) if !grep { defined && index( $_, '_' ) > -1 } @_[ 1 .. $#_ ];
        my ( $lh, @ref_args ) = @_;

        my $built = $compiled->(
            $lh,
            map {

                if ( defined && index( $_, '_' ) > -1 ) {
                    s/$FORCE_REGEX_LAZY\_(\-?[0-9]+|\*)/-!-$1-!-/og;
                }

                $_    # Change embedded-arg-looking-string to a

            } @ref_args

        );
        $built =~ s/$FORCE_REGEX_LAZY-!-(\-?[0-9]+|\*)-!-/_$1/og;    # Change placeholders back to their original
        return $built;
    };
}

sub get_handle {
    my ( $class, @langtags ) = @_;

    my $args_sig = join( ',', @langtags ) || 'no_args';

    if ( exists $singleton_stash{$class}{$args_sig} ) {
        $singleton_stash{$class}{$args_sig}->{'_singleton_reused'}++;
    }
    else {
        $singleton_stash{$class}{$args_sig} = $class->SUPER::get_handle(@langtags);
    }

    return $singleton_stash{$class}{$args_sig};
}

sub get_locales_obj {
    my ( $lh, $tag ) = @_;
    $tag ||= $lh->get_language_tag();

    if ( !exists $lh->{'Locales.pm'}{$tag} ) {
        require Cpanel::CPAN::Locales;
        $lh->{'Locales.pm'}{$tag} =
             Cpanel::CPAN::Locales->new($tag)
          || ( $tag ne substr( $tag, 0, 2 ) ? Cpanel::CPAN::Locales->new( substr( $tag, 0, 2 ) ) : '' )
          || (
            $lh->{'fallback_locale'}
            ?        ( Cpanel::CPAN::Locales->new( $lh->{'fallback_locale'} )
                  || ( $lh->{'fallback_locale'} ne substr( $lh->{'fallback_locale'}, 0, 2 ) ? Cpanel::CPAN::Locales->new( substr( $lh->{'fallback_locale'}, 0, 2 ) ) : '' ) )
            : ''
          )
          || Cpanel::CPAN::Locales->new('en');
    }

    return $lh->{'Locales.pm'}{$tag};
}

sub init {
    my ($lh) = @_;

    $lh->SUPER::init();
    $lh->remove_key_from_lexicons('_AUTO');

    no strict 'refs';
    for my $ns ( $lh->get_base_class(), $lh->get_language_class() ) {
        if ( defined ${ $ns . '::Encoding' } ) {
            $lh->{'encoding'} = ${ $ns . '::Encoding' } if ${ $ns . '::Encoding' };
        }
    }


    $lh->fail_with(
        sub {
            my ( $lh, $key, @args ) = @_;

            my $lookup;
            if ( exists $lh->{'_get_key_from_lookup'} ) {
                if ( ref $lh->{'_get_key_from_lookup'} eq 'CODE' ) {
                    $lookup = $lh->{'_get_key_from_lookup'}->( $lh, $key, @args );
                }
            }

            return $lookup if defined $lookup;

            if ( exists $lh->{'_log_phantom_key'} ) {
                if ( ref $lh->{'_log_phantom_key'} eq 'CODE' ) {
                    $lh->{'_log_phantom_key'}->( $lh, $key, @args );
                }
            }

            if ( $lh->{'use_external_lex_cache'} ) {
                local $lh->{'_external_lex_cache'}{'_AUTO'} = 1;

                if ( index( $key, '_' ) == 0 ) {
                    return $lh->{'_external_lex_cache'}{$key} = $key;
                }
                return $lh->maketext( $key, @args );
            }
            else {
                no strict 'refs';
                local ${ $lh->get_base_class() . '::Lexicon' }{'_AUTO'} = 1;

                if ( index( $key, '_' ) == 0 ) {
                    return ${ $lh->get_base_class() . '::Lexicon' }{$key} = $key;
                }

                return $lh->maketext( $key, @args );
            }
        }
    );
}

*makevar = \&Cpanel::CPAN::Locale::Maketext::maketext;


sub makethis {
    my ( $lh, $phrase, @phrase_args ) = @_;

    $lh->{'cache'}{'makethis'}{$phrase} ||= $lh->_compile($phrase);

    my $type = ref( $lh->{'cache'}{'makethis'}{$phrase} );

    if ( $type eq 'SCALAR' ) {
        return ${ $lh->{'cache'}{'makethis'}{$phrase} };
    }
    elsif ( $type eq 'CODE' ) {
        return $lh->{'cache'}{'makethis'}{$phrase}->( $lh, @phrase_args );
    }
    else {

        return $lh->{'cache'}{'makethis'}{$phrase};
    }
}

sub makethis_base {
    my ($lh) = @_;
    $lh->{'cache'}{'makethis_base'} ||= $lh->get_base_class()->get_handle( $lh->{'fallback_locale'} || 'en' );    # this allows to have a separate cache of compiled phrases (? get_handle() explicit or base_locales() (i.e. en en_us i_default || L::M->fallback_languages) ?)
    return $lh->{'cache'}{'makethis_base'}->makethis( @_[ 1 .. $#_ ] );
}

sub make_alias {
    my ( $lh, $pkgs, $is_base_class ) = @_;

    my $ns = $lh->get_language_class();
    return if $ns =~ tr{:0-9A-Za-z_-}{}c;
    my $base = $is_base_class ? $ns : $lh->get_base_class();

    no strict 'refs';
    for my $pkg ( ref $pkgs ? @{$pkgs} : $pkgs ) {
        next if $pkg =~ tr{:0-9A-Za-z_-}{}c;

        *{ $base . '::' . $pkg . '::Encoding' } = *{ $ns . '::Encoding' };
        *{ $base . '::' . $pkg . '::Lexicon' }  = *{ $ns . '::Lexicon' };
        @{ $base . '::' . $pkg . '::ISA' }      = ($ns);
    }
}

sub remove_key_from_lexicons {
    my ( $lh, $key ) = @_;
    my $idx = 0;

    for my $lex_hr ( @{ $lh->_lex_refs() } ) {
        $lh->{'_removed_from_lexicons'}{$idx}{$key} = delete $lex_hr->{$key} if exists $lex_hr->{$key};
        $idx++;
    }
}

my %grapheme_lookup = (
    'trademark'          => "\xE2\x84\xA2",    # 'TRADE MARK SIGN' (U+2122)
    'registered'         => "\xC2\xAE",        # 'REGISTERED SIGN' (U+00AE)
    'copyright'          => "\xC2\xA9",        # 'COPYRIGHT SIGN' (U+00A9)
    'left_double_quote'  => "\xE2\x80\x9C",    # 'LEFT DOUBLE QUOTATION MARK' (U+201C)
    'right_double_quote' => "\xE2\x80\x9D",    # 'RIGHT DOUBLE QUOTATION MARK' (U+201D)
    'ellipsis'           => "\xE2\x80\xA6",    # 'HORIZONTAL ELLIPSIS' (U+2026)
    'left_single_quote'  => "\xE2\x80\x98",    # 'LEFT SINGLE QUOTATION MARK' (U+2018)
    'right_single_quote' => "\xE2\x80\x99",    # 'RIGHT SINGLE QUOTATION MARK'
    'infinity'           => "\xE2\x88\x9E",    # 'INFINITY' (U+221E)
);

sub get_grapheme_helper_hashref {
    return {%grapheme_lookup};                 # copy
}

sub get_base_class {
    my $ns = $_[0]->get_language_class();
    return $ns if $ns eq 'Cpanel::Locale';
    return substr( $ns, 0, rindex( $ns, '::' ) );
}

sub append_to_lexicons {
    my ( $lh, $appendage ) = @_;
    return if ref $appendage ne 'HASH';

    no strict 'refs';
    for my $lang ( keys %{$appendage} ) {
        my $ns = $lh->get_base_class() . ( $lang eq '_' ? '' : "::$lang" ) . '::Lexicon';
        %{$ns} = ( %{$ns}, %{ $appendage->{$lang} } );
    }
}

sub langtag_is_loadable {
    my ( $lh, $wants_tag ) = @_;
    $wants_tag = Cpanel::CPAN::Locale::Maketext::language_tag($wants_tag);

    my $tag_obj = eval $lh->get_base_class() . q{->get_handle( $wants_tag );};

    my $has_tag = $tag_obj->language_tag();
    return $wants_tag eq $has_tag ? $tag_obj : 0;
}

sub get_language_tag {
    return ( split '::', $_[0]->get_language_class() )[-1];
}

sub print {
    local $Carp::CarpLevel = 1;
    print $_[0]->maketext( @_[ 1 .. $#_ ] );
}

sub fetch {
    local $Carp::CarpLevel = 1;
    return $_[0]->maketext( @_[ 1 .. $#_ ] );
}

sub say {
    local $Carp::CarpLevel = 1;
    my $text = $_[0]->maketext( @_[ 1 .. $#_ ] );
    local $/ = !defined $/ || !$/ ? "\n" : $/;    # otherwise assume they are not stupid
    print $text . $/ if $text;
}

sub get {
    local $Carp::CarpLevel = 1;
    my $text = $_[0]->maketext( @_[ 1 .. $#_ ] );
    local $/ = !defined $/ || !$/ ? "\n" : $/;    # otherwise assume they are not stupid
    return $text . $/ if $text;
    return;
}

sub get_language_tag_name {
    my ( $lh, $tag, $in_locale_tongue ) = @_;
    $tag ||= $lh->get_language_tag();

    my $loc_obj = $lh->get_locales_obj( $in_locale_tongue ? () : ($tag) );

    if ( $loc_obj->{'native_data'} && $tag eq $lh->get_language_tag() ) {
        return $loc_obj->get_native_language_from_code($tag);
    }

    return $loc_obj->get_language_from_code($tag);
}

sub get_html_dir_attr {
    my ( $lh, $raw_cldr, $is_tag ) = @_;

    if ($is_tag) {
        $raw_cldr = $lh->get_language_tag_character_orientation($raw_cldr);
    }
    else {
        $raw_cldr ||= $lh->get_language_tag_character_orientation();
    }

    if ( $raw_cldr eq 'left-to-right' ) {
        return 'ltr';
    }
    elsif ( $raw_cldr eq 'right-to-left' ) {
        return 'rtl';
    }

    return;
}

sub get_locale_display_pattern {

    require Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny;
    return Cpanel::CPAN::Locales::DB::LocaleDisplayPattern::Tiny::get_locale_display_pattern( $_[1] || $_[0]->{'fallback_locale'} || $_[0]->get_language_tag() );
}

sub get_language_tag_character_orientation {

    require Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny;
    return Cpanel::CPAN::Locales::DB::CharacterOrientation::Tiny::get_orientation( $_[1] || $_[0]->{'fallback_locale'} || $_[0]->get_language_tag() );
}

*lextext = *text;

sub text {

    if ( @_ != 2 ) {
        require Carp;
        Carp::croak('text() requires a singlef parameter');

    }

    my ( $handle, $phrase ) = splice( @_, 0, 2 );
    unless ( defined($handle) && defined($phrase) ) {
        require Carp;
        Carp::confess('No handle/phrase');

    }

    if ( !$handle->{'use_external_lex_cache'} ) {
        require Carp;
        Carp::carp("text() requires you to have 'use_external_lex_cache' enabled.");
        return;
    }

    local $@;



    my $value;
    foreach my $h_r ( @{ $handle->_lex_refs } ) {    # _lex_refs() caches itself

        if ( defined( $value = $h_r->{$phrase} ) ) {

            if ( ref $value ) {
                require Carp;
                Carp::carp("Previously compiled phrase ('use_external_lex_cache' enabled after phrase was compiled?)");
            }

            return $value eq '' ? $phrase : $value;
        }

        elsif ( index( $phrase, '_' ) != 0 and $h_r->{'_AUTO'} ) {

            return $phrase;
        }


    }


    return ( !defined $value || $value eq '' ) ? $phrase : $value;
}

our $_NATIVE_ONLY = 0;

sub lang_names_hashref_native_only {
    local $_NATIVE_ONLY = 1;
    return lang_names_hashref(@_);
}

sub lang_names_hashref {
    my ( $lh, @langcodes ) = @_;

    if ( !@langcodes ) {    # they havn't specified any langcodes...
        require File::Spec;    # only needed here, so we don't use() it

        my @search;
        my $path = $lh->get_base_class();

        substr( $path, index( $path, '::' ), 2, '/' ) while index( $path, '::' ) > -1;

        if ( ref $lh->{'_lang_pm_search_paths'} eq 'ARRAY' ) {
            @search = @{ $lh->{'_lang_pm_search_paths'} };
        }

        @search = @INC if !@search;    # they havn't told us where they are specifically

      DIR:
        for my $dir (@search) {
            my $lookin = File::Spec->catdir( $dir, $path );
            next DIR if !-d $lookin;
            if ( opendir my $dh, $lookin ) {
              PM:
                for my $pm ( grep { /^\w+\.pm$/ } grep !/^\.+$/, readdir($dh) ) {
                    substr( $pm, -3, 3, '' );    # checked above - if substr( $pm, -3 ) eq '.pm';
                    next PM if !$pm;
                    next PM if $pm eq 'Utils';
                    next PM if $pm eq 'Context';
                    next PM if $pm eq 'Lazy';
                    push @langcodes, $pm;
                }
                closedir $dh;
            }
        }
    }

    require Cpanel::CPAN::Locales;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();

    my $langname  = {};
    my $native    = wantarray && $Cpanel::CPAN::Locales::VERSION > 0.06 ? {} : undef;
    my $direction = wantarray && $Cpanel::CPAN::Locales::VERSION > 0.09 ? {} : undef;

    for my $code ( 'en', @langcodes ) {    # en since it is "built in"
        if ( defined $native ) {
            $native->{$code} = $lh->{'Locales.pm'}{'_main_'}->get_native_language_from_code( $code, 1 );
        }

        $langname->{$code} = $_NATIVE_ONLY ? $native->{$code} : $lh->{'Locales.pm'}{'_main_'}->get_language_from_code( $code, 1 );

        if ( defined $direction ) {
            $direction->{$code} = $lh->{'Locales.pm'}{'_main_'}->get_character_orientation_from_code_fast($code);
        }
    }

    return wantarray ? ( $langname, $native, $direction ) : $langname;
}

sub loadable_lang_names_hashref {
    my ( $lh, @langcodes ) = @_;

    my $langname = $lh->lang_names_hashref(@langcodes);

    for my $tag ( keys %{$langname} ) {
        delete $langname->{$tag} if !$lh->langtag_is_loadable($tag);
    }

    return $langname;
}

sub add_lexicon_override_hash {
    my ( $lh, $langtag, $name, $hr ) = @_;
    if ( @_ == 3 ) {
        $hr      = $name;
        $name    = $langtag;
        $langtag = $lh->get_language_tag();
    }

    my $ns = $lh->get_language_tag() eq $langtag ? $lh->get_language_class() : $lh->get_base_class();

    no strict 'refs';
    if ( my $ref = tied( %{ $ns . '::Lexicon' } ) ) {
        return 1 if $lh->{'add_lex_hash_silent_if_already_added'} && exists $ref->{'hashes'} && exists $ref->{'hashes'}{$name};
        if ( $ref->can('add_lookup_override_hash') ) {
            return $ref->add_lookup_override_hash( $name, $hr );
        }
    }

    my $cur_errno = $!;
    if ( eval { require Sub::Todo } ) {
        goto &Sub::Todo::todo;
    }
    else {
        $! = $cur_errno;
        return;
    }
}

sub add_lexicon_fallback_hash {
    my ( $lh, $langtag, $name, $hr ) = @_;
    if ( @_ == 3 ) {
        $hr      = $name;
        $name    = $langtag;
        $langtag = $lh->get_language_tag();
    }

    my $ns = $lh->get_language_tag() eq $langtag ? $lh->get_language_class() : $lh->get_base_class();

    no strict 'refs';
    if ( my $ref = tied( %{ $ns . '::Lexicon' } ) ) {
        return 1 if $lh->{'add_lex_hash_silent_if_already_added'} && exists $ref->{'hashes'} && exists $ref->{'hashes'}{$name};
        if ( $ref->can('add_lookup_fallback_hash') ) {
            return $ref->add_lookup_fallback_hash( $name, $hr );
        }
    }

    my $cur_errno = $!;
    if ( eval { require Sub::Todo } ) {
        goto &Sub::Todo::todo;
    }
    else {
        $! = $cur_errno;
        return;
    }
}

sub del_lexicon_hash {
    my ( $lh, $langtag, $name ) = @_;

    if ( @_ == 2 ) {
        return if $langtag eq '*';
        $name    = $langtag;
        $langtag = '*';
    }

    return if !$langtag;

    my $count = 0;
    if ( $langtag eq '*' ) {
        no strict 'refs';
        for my $ns ( $lh->get_base_class(), $lh->get_language_class() ) {
            if ( my $ref = tied( %{ $ns . '::Lexicon' } ) ) {
                if ( $ref->can('del_lookup_hash') ) {
                    $ref->del_lookup_hash($name);
                    $count++;
                }
            }
        }

        return 1 if $count;

        my $cur_errno = $!;
        if ( eval { require Sub::Todo } ) {
            goto &Sub::Todo::todo;
        }
        else {
            $! = $cur_errno;
            return;
        }
    }
    else {
        my $ns = $lh->get_language_tag() eq $langtag ? $lh->get_language_class() : $lh->get_base_class();

        no strict 'refs';
        if ( my $ref = tied( %{ $ns . '::Lexicon' } ) ) {
            if ( $ref->can('del_lookup_hash') ) {
                return $ref->del_lookup_hash($name);
            }
        }

        my $cur_errno = $!;
        if ( eval { require Sub::Todo } ) {
            goto &Sub::Todo::todo;
        }
        else {
            $! = $cur_errno;
            return;
        }
    }
}

sub get_language_class {
    return ref( $_[0] ) || $_[0];
}


sub get_base_class_dir {
    my ($lh) = @_;
    if ( !exists $lh->{'Cpanel::CPAN::Locale::Maketext::Utils'}{'_base_clase_dir'} ) {
        $lh->{'Cpanel::CPAN::Locale::Maketext::Utils'}{'_base_clase_dir'} = undef;

        my $inc_key = $lh->get_base_class();

        substr( $inc_key, index( $inc_key, '::' ), 2, '/' ) while index( $inc_key, '::' ) > -1;
        $inc_key .= '.pm';
        if ( exists $INC{$inc_key} ) {
            if ( -e $INC{$inc_key} ) {
                my $hr = $lh->{'Cpanel::CPAN::Locale::Maketext::Utils'};
                $hr->{'_base_clase_dir'} = $INC{$inc_key};
                substr( $hr->{'_base_clase_dir'}, -3, 3, '' ) if substr( $hr->{'_base_clase_dir'}, -3 ) eq '.pm';
            }
        }
    }

    return $lh->{'Cpanel::CPAN::Locale::Maketext::Utils'}{'_base_clase_dir'};
}

sub list_available_locales {
    my ($lh) = @_;

    die "List context only!" if !wantarray;

    my $main_ns_dir = $lh->get_base_class_dir() || return;
    local $!;
    opendir my $dh, $main_ns_dir or die "Failed to open: $main_ns_dir: $!";

    return map { ( substr( $_, -3 ) eq '.pm' && $_ ne 'Utils.pm' && $_ ne 'Lazy.pm' && $_ ne 'Context.pm' && $_ ne 'Fallback.pm' ) ? substr( $_, 0, -3 ) : () } readdir($dh);    #de-taint
}

sub get_asset {
    my ( $lh, $code, $tag ) = @_;                                                                                                                                                # No caching since $code can do anything.

    my $root = $tag || $lh->get_language_tag;
    my $ret;

    die "Invalid locale: $root" if index( $root, '/' ) > -1;

    $ret = $code->($root);
    return $ret if defined $ret;

    my $loc;    # buffer
    my %seen = ( $root => 1 );

    my @fallback_locales;
    if ( $lh->_has_fallback_list($root) ) {
        my $loc_obj = $lh->get_locales_obj($tag);
        @fallback_locales = $loc_obj->get_fallback_list( $lh->{'Locales.pm'}{'get_fallback_list_special_lookup_coderef'} );
    }
    elsif ( $root ne 'en' ) {

        my $super = ( split( m{_}, $root ) )[0];
        @fallback_locales = (
            ( $super ne $root && $super ne 'i' ? $super : () ),
            'en'
        );
    }

    for $loc (@fallback_locales) {
        next if $seen{$loc};    # get_fallback_list can provide back dupes and its expensive to enumerate each one

        $ret = $code->($loc);
        $seen{$loc}++;
        last if defined $ret;
    }

    return $ret if defined $ret;
    return;
}

sub _has_fallback_list {
    return $_[0]->{'_has_fallback_list'}{ $_[1] } if defined $_[0]->{'_has_fallback_list'}{ $_[1] };
    my $size = -s LOCALE_FALLBACK_CACHE_DIR . '/' . $_[1];
    return ( $_[0]->{'_has_fallback_list'}{ $_[1] } = ( !defined $size || $size ) ? 1 : 0 );
}

sub get_asset_file {
    my ( $lh, $find, $return ) = @_;
    $return = $find if !defined $return;

    return $lh->{'cache'}{'get_asset_file'}{$find}{$return} if exists $lh->{'cache'}{'get_asset_file'}{$find}{$return};

    $lh->{'cache'}{'get_asset_file'}{$find}{$return} = $lh->get_asset(
        sub {
            return sprintf( $return, $_[0] ) if -f sprintf( $find, $_[0] );
            return;
        }
    );

    return $lh->{'cache'}{'get_asset_file'}{$find}{$return} if defined $lh->{'cache'}{'get_asset_file'}{$find}{$return};
    return;
}

sub get_asset_dir {
    my ( $lh, $find, $return ) = @_;
    $return = $find if !defined $return;

    return $lh->{'cache'}{'get_asset_dir'}{$find}{$return} if exists $lh->{'cache'}{'get_asset_dir'}{$find}{$return};

    $lh->{'cache'}{'get_asset_dir'}{$find}{$return} = $lh->get_asset(
        sub {
            return sprintf( $return, $_[0] ) if -d sprintf( $find, $_[0] );
            return;
        }
    );

    return $lh->{'cache'}{'get_asset_dir'}{$find}{$return} if defined $lh->{'cache'}{'get_asset_dir'}{$find}{$return};
    return;
}

sub delete_cache {
    my ( $lh, $which ) = @_;
    if ( defined $which ) {
        return delete $lh->{'cache'}{$which};
    }
    else {
        return delete $lh->{'cache'};
    }
}


sub quant {
    my ( $handle, $num, @forms ) = @_;

    my $max_decimal_places = 3;

    if ( ref($num) eq 'ARRAY' ) {
        $max_decimal_places = $num->[1];
        $num                = $num->[0];
    }

    $handle->{'Locales.pm'}{'_main_'} ||= $handle->get_locales_obj();

    my ( $string, $spec_zero ) = $handle->{'Locales.pm'}{'_main_'}->get_plural_form( $num, @forms );

    if ( index( $string, '%s' ) > -1 ) {
        return sprintf( $string, $handle->numf( $num, $max_decimal_places ) );
    }
    elsif ( $num == 0 && $spec_zero ) {
        return $string;
    }
    else {
        $handle->numf( $num, $max_decimal_places ) . " $string";
    }
}

sub numerate {
    my ( $handle, $num, @forms ) = @_;

    $handle->{'Locales.pm'}{'_main_'} ||= $handle->get_locales_obj();

    return scalar( $handle->{'Locales.pm'}{'_main_'}->get_plural_form( $num, @forms ) );
}



sub numf {
    my ( $handle, $num, $max_decimal_places ) = @_;

    $handle->{'Locales.pm'}{'_main_'} ||= $handle->get_locales_obj();

    return $handle->{'Locales.pm'}{'_main_'}->get_formatted_decimal( $num, $max_decimal_places );
}




sub join {
    shift;
    return CORE::join( shift, map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @_ );
}

sub list_and {
    my $lh = shift;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();

    return $lh->{'Locales.pm'}{'_main_'}->get_list_and( map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @_ );
}

sub list_or {
    my $lh = shift;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();

    return $lh->{'Locales.pm'}{'_main_'}->get_list_or( map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @_ );
}

sub list_and_quoted {
    my ( $lh, @args ) = @_;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();
    local $lh->{'Locales.pm'}{'_main_'}{'misc'}{'list_quote_mode'} = 'all';
    return $lh->list_and(@args);
}

sub list_or_quoted {
    my ( $lh, @args ) = @_;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();
    local $lh->{'Locales.pm'}{'_main_'}{'misc'}{'list_quote_mode'} = 'all';
    return $lh->list_or(@args);
}

sub output_asis {
    return $_[1];
}

sub asis {
    return $_[0]->output( 'asis', $_[1] );    # this allows for embedded methods but still called via [asis,...] instead of [output,asis,...]
}

sub comment {
    return '';
}

sub is_future {
    my ( $lh, $dt, $future, $past, $current, $current_type ) = @_;

    if ( $dt =~ tr{0-9}{}c ) {
        $dt = __get_dt_obj_from_arg( $dt, 0 );
        $dt = $dt->epoch();
    }

    if ($current) {
        if ( !ref $dt ) {
            $dt = __get_dt_obj_from_arg( $dt, 0 );
        }
        $current_type ||= 'hour';

        if ( $current_type eq 'day' ) {

        }
        elsif ( $current_type eq 'minute' ) {

        }
        else {

        }
    }

    return ref $dt ? $dt->epoch() : $dt > time() ? $future : $past;
}

sub __get_dt_obj_from_arg {
    require    # hide from Cpanel::Static
      DateTime;
    return
       !defined $_[0] || $_[0] eq ''                                 ? DateTime->now()
      : ref $_[0] eq 'HASH'                                          ? DateTime->new( %{ $_[0] } )
      : $_[0] =~ m{ \A (\d+ (?: [.] \d+ )? ) (?: [:] (.*) )? \z }xms ? DateTime->from_epoch( 'epoch' => $1, 'time_zone' => ( $2 || 'UTC' ) )
      : !ref $_[0]                                                   ? DateTime->now( 'time_zone' => ( $_[0] || 'UTC' ) )
      : $_[1]                                                        ? $_[0]->clone()
      :                                                                $_[0];
}

sub current_year {
    $_[0]->datetime( '', 'YYYY' );
}

sub datetime {
    my ( $lh, $dta, $str ) = @_;
    my $dt = __get_dt_obj_from_arg( $dta, 1 );

    if ( !$INC{'DateTime/Locale.pm'} ) {    # __get_dt_obj_from_arg is loading DateTime
        eval q{ require DateTime::Locale; 1 } or die "Cannot load DateTime::Locale: $!";
    }

    $dt->{'locale'} = DateTime::Locale->load( $lh->language_tag() );
    my $format = ref $str eq 'CODE' ? $str->($dt) : $str;
    if ( defined $format ) {
        if ( $dt->{'locale'}->can($format) ) {
            $format = $dt->{'locale'}->$format();
        }
    }
    $format = '' if !defined $format;

    return $dt->format_cldr( $dt->{'locale'}->format_for($format) || $format || $dt->{'locale'}->date_format_long() );
}

sub output_amp  { return $_[0]->output_chr(38) }
sub output_lt   { return $_[0]->output_chr(60) }    # TODO: ? make the rest of these embeddable like amp() ?
sub output_gt   { return $_[0]->output_chr(62) }
sub output_apos { return $_[0]->output_chr(39) }
sub output_quot { return $_[0]->output_chr(34) }
sub output_shy  { return $_[0]->output_chr(173) }


use constant output_nbsp => "\xC2\xA0";



my $space;

sub format_bytes {
    my ( $lh, $bytes, $max_decimal_place ) = @_;
    $bytes ||= 0;

    if ( !defined $max_decimal_place ) {
        $max_decimal_place = 2;
    }
    else {
        $max_decimal_place = int( abs($max_decimal_place) );
    }

    my $absnum = abs($bytes);

    $space ||= $lh->output_nbsp();    # avoid method call if we already have it

    if ( $absnum < 1024 ) {

        return ( $lh->{'_format_bytes_cache'}{ $bytes . '_' . $max_decimal_place } ||= $lh->maketext( '[quant,_1,%s byte,%s bytes]', [ $bytes, $max_decimal_place ] ) );    # the space between the '%s' and the 'b' is a non-break space (e.g. option-spacebar, not spacebar)
    }
    elsif ( $absnum < 1048576 ) {
        return $lh->numf( ( $bytes / 1024 ), $max_decimal_place ) . $space . 'KB';
    }
    elsif ( $absnum < 1073741824 ) {
        return $lh->numf( ( $bytes / 1048576 ), $max_decimal_place ) . $space . 'MB';
    }
    elsif ( $absnum < 1099511627776 ) {
        return $lh->numf( ( $bytes / 1073741824 ), $max_decimal_place ) . $space . 'GB';
    }
    elsif ( $absnum < 1125899906842624 ) {
        return $lh->numf( ( $bytes / 1099511627776 ), $max_decimal_place ) . $space . 'TB';
    }
    elsif ( $absnum < ( 1125899906842624 * 1024 ) ) {
        return $lh->numf( ( $bytes / 1125899906842624 ), $max_decimal_place ) . $space . 'PB';
    }
    elsif ( $absnum < ( 1125899906842624 * 1024 * 1024 ) ) {
        return $lh->numf( ( $bytes / ( 1125899906842624 * 1024 ) ), $max_decimal_place ) . $space . 'EB';
    }
    elsif ( $absnum < ( 1125899906842624 * 1024 * 1024 * 1024 ) ) {
        return $lh->numf( ( $bytes / ( 1125899906842624 * 1024 * 1024 ) ), $max_decimal_place ) . $space . 'ZB';
    }
    else {

        return $lh->numf( ( $bytes / ( 1125899906842624 * 1024 * 1024 * 1024 ) ), $max_decimal_place ) . $space . 'YB';

    }
}

sub convert {
    die __PACKAGE__ . "::convert is not supported (missing Math::Units)";
}

sub is_defined {
    my ( $lh, $value, $is_defined, $not_defined, $is_defined_but_false ) = @_;

    return __proc_string_with_embedded_under_vars($not_defined) if !defined $value;

    if ( defined $is_defined_but_false && !$value ) {
        return __proc_string_with_embedded_under_vars($is_defined_but_false);
    }
    else {
        return __proc_string_with_embedded_under_vars($is_defined);
    }
}

sub boolean {
    my ( $lh, $boolean, $true, $false, $null ) = @_;
    if ($boolean) {
        return __proc_string_with_embedded_under_vars($true);
    }
    else {
        if ( !defined $boolean && defined $null ) {
            return __proc_string_with_embedded_under_vars($null);
        }
        return __proc_string_with_embedded_under_vars($false);
    }
}

sub __proc_string_with_embedded_under_vars {
    my $str = $_[0];
    return $str if index( $str, '_' ) == -1 || $str !~ m/$FORCE_REGEX_LAZY\_(?:\-?[0-9]+)/o;
    my @args = __caller_args( $_[1] );    # this way be dragons
    $str =~ s/$FORCE_REGEX_LAZY\_(\-?[0-9]+)/$args[$1]/og;
    return $str;
}

sub __caller_args {

    package DB;
    () = caller( $_[0] + 3 );
    return @DB::args;
}

sub __proc_emb_meth {
    my ( $lh, $str ) = @_;

    $str =~ s/$FORCE_REGEX_LAZY(su[bp])\(((?:\\\)|[^\)])+?)\)/my $s=$2;my $m="output_$1";$s=~s{\\\)}{\)}g;$lh->$m($s)/oeg if index( $str, 'su' ) > -1;
    $str =~ s/${FORCE_REGEX_LAZY}chr\(((?:\d+|[\S]))\)/$lh->output_chr($1)/oeg                                            if index( $str, 'chr(' ) > -1;
    $str =~ s/${FORCE_REGEX_LAZY}numf\((\d+(?:\.\d+)?)\)/$lh->numf($1)/oeg                                                if index( $str, 'numf(' ) > -1;
    substr( $str, index( $str, 'amp()' ), 5, $lh->output_amp() ) while index( $str, 'amp()' ) > -1;

    return $str;
}

sub output {
    my ( $lh, $output_function, $string, @output_function_args ) = @_;

    if ( defined $string && $string ne '' && index( $string, '(' ) > -1 ) {
        $string = __proc_emb_meth( $lh, $string );
    }

    if ( $output_function eq 'url' && defined $output_function_args[0] && $output_function_args[0] ne '' && index( $output_function_args[0], '(' ) > -1 ) {
        $output_function_args[0] = __proc_emb_meth( $lh, $output_function_args[0] );
    }
    if ( my $cr = ( $lh->{'_output_function_cache'}{$output_function} ||= $lh->can( 'output_' . $output_function ) ) ) {
        return $cr->( $lh, $string, @output_function_args );
    }
    else {
        my $cur_errno = $!;
        if ( eval { require Sub::Todo } ) {
            $! = Sub::Todo::get_errno_func_not_impl();
        }
        else {
            $! = $cur_errno;
        }
        return $string;
    }
}

sub output_encode_puny {
    my ( $self, $s ) = @_;
    require    # do not include it in updatenow.static
      Cpanel::Encoder::Punycode;
    return Cpanel::Encoder::Punycode::punycode_encode_str($s);
}

sub output_decode_puny {
    my ( $self, $s ) = @_;
    require    # do not include it in updatenow.static
      Cpanel::Encoder::Punycode;
    return Cpanel::Encoder::Punycode::punycode_decode_str($s);
}

my $has_encode;    # checking for Encode this way facilitates only checking @INC once for the module on systems that do not have Encode

sub output_chr {
    my ( $lh, $chr_num ) = @_;

    if ( $chr_num !~ m/$FORCE_REGEX_LAZY\A\d+\z/o ) {
        return          if length($chr_num) != 1;
        return $chr_num if !$lh->context_is_html();

        return
            $chr_num eq '"' ? '&quot;'
          : $chr_num eq '&' ? '&amp;'
          : $chr_num eq "'" ? '&#39;'
          : $chr_num eq '<' ? '&lt;'
          : $chr_num eq '>' ? '&gt;'
          :                   $chr_num;
    }
    return if $chr_num !~ m/$FORCE_REGEX_LAZY\A\d+\z/o;
    my $chr = chr($chr_num);

    if ( $chr_num > 127 ) {

        if ( !defined $has_encode ) {
            $has_encode = 0;
            eval { require Encode; $has_encode = 1; };
        }

        if ($has_encode) {
            $chr = Encode::encode( $lh->encoding(), $chr );
        }

        else {




            $chr = eval '"\x{' . sprintf( '%04X', $chr_num ) . '}"';
        }
    }

    if ( !$lh->context_is_html() ) {
        return $chr;
    }
    else {
        return
            $chr_num == 34 || $chr_num == 147 || $chr_num == 148 ? '&quot;'
          : $chr_num == 38                                       ? '&amp;'
          : $chr_num == 39 || $chr_num == 145 || $chr_num == 146 ? '&#39;'
          : $chr_num == 60                                       ? '&lt;'
          : $chr_num == 62                                       ? '&gt;'
          : $chr_num == 173                                      ? '&shy;'
          :                                                        $chr;
    }
}

sub output_class {
    my ( $lh, $string, @classes ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if $lh->context_is_plain();

    return $lh->context_is_ansi() ? "\e[1m$string\e[0m" : qq{<span class="@classes">$string</span>};
}

sub output_asis_for_tests {
    my ( $lh, $string ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string;
}

sub __make_attr_str_from_ar {
    my ( $attr_ar, $strip_hr, $addin ) = @_;
    if ( ref($attr_ar) eq 'HASH' ) {
        $strip_hr = $attr_ar;
        $attr_ar  = [];
    }

    my $attr       = '';
    my $general_hr = ref( $attr_ar->[-1] ) eq 'HASH' ? pop( @{$attr_ar} ) : undef;

    my $idx    = 0;
    my $ar_len = @{$attr_ar};

    $idx = 1 if $ar_len % 2;    # handle “Odd number of elements” …

    my $did_addin;

    while ( $idx < $ar_len ) {
        if ( exists $strip_hr->{ $attr_ar->[$idx] } ) {
            $idx += 2;
            next;
        }
        my $atr = $attr_ar->[$idx];
        my $val = $attr_ar->[ ++$idx ];
        if ( exists $addin->{$atr} ) {
            $val = "$addin->{$atr} $val";
            $did_addin->{$atr}++;
        }

        $attr .= qq{ $atr="$val"};
        $idx++;
    }

    if ($general_hr) {
        for my $k ( keys %{$general_hr} ) {
            next if exists $strip_hr->{$k};
            if ( exists $addin->{$k} ) {
                $general_hr->{$k} = "$addin->{$k} $general_hr->{$k}";
                $did_addin->{$k}++;
            }
            $attr .= qq{ $k="$general_hr->{$k}"};
        }
    }

    for my $r ( keys %{$addin} ) {
        if ( !exists $did_addin->{$r} ) {
            $attr .= qq{ $r="$addin->{$r}"};
        }
    }

    return $attr;
}

sub output_inline {
    my ( $lh, $string, @attrs ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if !$lh->context_is_html();

    my $attr = __make_attr_str_from_ar( \@attrs );
    return qq{<span$attr>$string</span>};
}

*output_attr = \&output_inline;

sub output_block {
    my ( $lh, $string, @attrs ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if !$lh->context_is_html();

    my $attr = __make_attr_str_from_ar( \@attrs );
    return qq{<div$attr>$string</div>};
}

sub output_img {
    my ( $lh, $src, $alt, @attrs ) = @_;

    if ( !defined $alt || $alt eq '' ) {
        $alt = $src;
    }
    else {
        $alt = __proc_string_with_embedded_under_vars( $alt, 1 );
    }

    return $alt if !$lh->context_is_html();

    my $attr = __make_attr_str_from_ar( \@attrs, { 'alt' => 1, 'src' => 1 } );
    return qq{<img src="$src" alt="$alt"$attr/>};
}

sub output_abbr {
    my ( $lh, $abbr, $full, @attrs ) = @_;
    return !$lh->context_is_html()
      ? "$abbr ($full)"
      : qq{<abbr title="$full"} . __make_attr_str_from_ar( \@attrs, { 'title' => 1 } ) . qq{>$abbr</abbr>};
}

sub output_acronym {
    my ( $lh, $acronym, $full, @attrs ) = @_;

    return !$lh->context_is_html()
      ? "$acronym ($full)"
      : qq{<abbr title="$full"} . __make_attr_str_from_ar( \@attrs, { 'title' => 1 }, { 'class' => 'initialism' } ) . qq{>$acronym</abbr>};
}

sub output_sup {
    my ( $lh, $string, @attrs ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return !$lh->context_is_html() ? $string : qq{<sup} . __make_attr_str_from_ar( \@attrs ) . qq{>$string</sup>};
}

sub output_sub {
    my ( $lh, $string, @attrs ) = @_;
    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return !$lh->context_is_html() ? $string : qq{<sub} . __make_attr_str_from_ar( \@attrs ) . qq{>$string</sub>};
}

sub output_underline {
    my ( $lh, $string, @attrs ) = @_;

    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if $lh->context_is_plain();
    return $lh->context_is_ansi() ? "\e[4m$string\e[0m" : qq{<span style="text-decoration: underline"} . __make_attr_str_from_ar( \@attrs ) . qq{>$string</span>};
}

sub output_strong {
    my ( $lh, $string, @attrs ) = @_;

    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if $lh->context_is_plain();
    return $lh->context_is_ansi() ? "\e[1m$string\e[0m" : '<strong' . __make_attr_str_from_ar( \@attrs ) . ">$string</strong>";
}

sub output_em {
    my ( $lh, $string, @attrs ) = @_;

    $string = __proc_string_with_embedded_under_vars( $string, 1 );
    return $string if $lh->context_is_plain();

    return $lh->context_is_ansi() ? "\e[3m$string\e[0m" : '<em' . __make_attr_str_from_ar( \@attrs ) . ">$string</em>";
}


sub output_url {
    my ( $lh, $url, @args ) = @_;
    $url ||= '';    # carp() ?

    my $arb_args_hr = ref $args[-1] eq 'HASH' ? pop(@args) : {};
    my ( $url_text, %output_config ) = @args % 2 ? @args : ( undef, @args );

    my $return = $url;

    if ( !$lh->context_is_html() ) {
        if ($url_text) {
            return "$url_text ($url)";
        }

        if ( exists $output_config{'plain'} ) {
            $output_config{'plain'} ||= $url;
            my $orig = $output_config{'plain'};
            $output_config{'plain'} = __proc_string_with_embedded_under_vars( $output_config{'plain'}, 1 );
            $return = $orig ne $output_config{'plain'} && $output_config{'plain'} =~ m/\Q$url\E/ ? $output_config{'plain'} : "$output_config{'plain'} $url";
        }
    }
    else {
        if ( exists $output_config{'html'} ) {
            $output_config{'html'} = __proc_string_with_embedded_under_vars( $output_config{'html'}, 1 );
        }

        $output_config{'html'} ||= $url_text || $url;

        my $attr = __make_attr_str_from_ar(
            [ @args, $arb_args_hr ],
            {
                'html'  => 1,
                'plain' => 1,
                '_type' => 1,
            }
        );

        $return = exists $output_config{'_type'}
          && $output_config{'_type'} eq 'offsite' ? qq{<a$attr target="_blank" class="offsite" href="$url">$output_config{'html'}</a>} : qq{<a$attr href="$url">$output_config{'html'}</a>};
    }

    return $return;
}



sub set_context_html {
    my ($lh) = @_;
    my $cur = $lh->get_context();
    $lh->set_context('html');
    return if !$lh->context_is_html();
    return $cur;
}

sub set_context_ansi {
    my ($lh) = @_;
    my $cur = $lh->get_context();
    $lh->set_context('ansi');
    return if !$lh->context_is_ansi();
    return $cur;
}

sub set_context_plain {
    my ($lh) = @_;
    my $cur = $lh->get_context();
    $lh->set_context('plain');
    return if !$lh->context_is_plain();
    return $cur;
}

my %contexts = (
    'plain' => undef(),
    'ansi'  => 1,
    'html'  => 0,
);

sub set_context {
    my ( $lh, $context ) = @_;

    if ( !$context ) {
        $lh->{'-t-STDIN'} = -t *STDIN ? 1 : 0;
    }
    elsif ( exists $contexts{$context} ) {
        $lh->{'-t-STDIN'} = $contexts{$context};
    }
    else {
        require Carp;
        local $Carp::CarpLevel = 1;
        Carp::carp("Given context '$context' is unknown.");
        $lh->{'-t-STDIN'} = $context;
    }
}

sub context_is_html {
    return $_[0]->get_context() eq 'html';
}

sub context_is_ansi {
    return $_[0]->get_context() eq 'ansi';
}

sub context_is_plain {
    return $_[0]->get_context() eq 'plain';
}

sub context_is {
    return $_[0]->get_context() eq $_[1];
}

sub get_context {
    $_[0]->set_context() if !exists $_[0]->{'-t-STDIN'};
    return
        !defined $_[0]->{'-t-STDIN'} ? 'plain'
      : $_[0]->{'-t-STDIN'}          ? 'ansi'
      :                                'html';
}

sub maketext_html_context {
    my ( $lh, @mt_args ) = @_;
    my $cur = $lh->set_context_html();
    my $res = $lh->maketext(@mt_args);
    $lh->set_context($cur);
    return $res;
}

sub maketext_ansi_context {
    my ( $lh, @mt_args ) = @_;
    my $cur = $lh->set_context_ansi();
    my $res = $lh->maketext(@mt_args);
    $lh->set_context($cur);
    return $res;
}

sub maketext_plain_context {
    my ( $lh, @mt_args ) = @_;
    my $cur = $lh->set_context_plain();
    my $res = $lh->maketext(@mt_args);
    $lh->set_context($cur);
    return $res;
}


1;

} # --- END Cpanel/CPAN/Locale/Maketext/Utils.pm


{ # --- BEGIN Cpanel/Locale/Utils/Paths.pm
package Cpanel::Locale::Utils::Paths;


use strict;
use warnings;

use constant {
    get_legacy_lang_cache_root => '/var/cpanel/lang.cache',
    get_i_locales_config_path  => '/var/cpanel/i_locales',
    get_custom_whitelist_path  => '/var/cpanel/maketext_whitelist'
};

sub get_locale_database_root   { return '/var/cpanel/locale' }
sub get_locale_yaml_root       { return '/usr/local/cpanel/locale' }
sub get_legacy_lang_root       { return '/usr/local/cpanel/lang' }
sub get_locale_yaml_local_root { return '/var/cpanel/locale.local' }

1;

} # --- END Cpanel/Locale/Utils/Paths.pm


{ # --- BEGIN Cpanel/Time/Local.pm
package Cpanel::Time::Local;


use strict;


our $server_offset_string;
our ( $timecacheref, $localtimecacheref ) = ( [ -1, '', -1 ], [ -1, '', -1 ] );

my $server_offset;
my $localtime_link_or_mtime;
our $ETC_LOCALTIME = q{/etc/localtime};

sub _clear_caches {
    undef $_
      for (
        $server_offset,
        $server_offset_string,
        $timecacheref,
        $localtimecacheref,
        $localtime_link_or_mtime,
      );
    return;
}

sub localtime2timestamp {
    my ( $time, $delimiter ) = @_;
    $delimiter ||= ' ';
    $time      ||= time();

    return $localtimecacheref->[2] if $localtimecacheref->[0] == $time && $localtimecacheref->[1] eq $delimiter;

    my $tz_offset = get_server_offset_as_offset_string($time);

    my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime $time;
    @{$localtimecacheref}[ 0, 1 ] = ( $time, $delimiter );
    return ( $localtimecacheref->[2] = sprintf( '%04d-%02d-%02d' . $delimiter . '%02d:%02d:%02d %s', $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $tz_offset ) );
}

sub get_server_offset_as_offset_string {
    my ($time_supplied) = @_;

    if ( !$time_supplied ) {
        my $link_or_mtime;
        if ( -l $ETC_LOCALTIME ) {
            $link_or_mtime = readlink($ETC_LOCALTIME);
        }
        else {
            $link_or_mtime = ( stat($ETC_LOCALTIME) )[9];
        }
        if ( defined $link_or_mtime ) {
            $localtime_link_or_mtime ||= $link_or_mtime;

            if ( $localtime_link_or_mtime ne $link_or_mtime ) {
                _clear_caches();
                $localtime_link_or_mtime = $link_or_mtime;
            }
        }
    }

    if ( $time_supplied || !defined $server_offset_string ) {

      UNTIL_SAME_SECOND: {
            my $starttime = time();
            my $time      = $time_supplied || $starttime;
            my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday ) = localtime $time;

            my ( $gmmin, $gmhour, $gmyear, $gmyday ) = ( gmtime($time) )[ 1, 2, 5, 7 ];

            redo UNTIL_SAME_SECOND if time != $starttime;

            my $yday_offset;
            if ( $year == $gmyear ) {
                $yday_offset = ( $yday <=> $gmyday );
            }
            elsif ( $year < $gmyear ) {
                $yday_offset = -1;
            }
            elsif ( $year > $gmyear ) {
                $yday_offset = 1;
            }

            my $gmoffset      = ( $hour * 60 + $min ) - ( $gmhour * 60 + $gmmin ) + 1440 * $yday_offset;
            my $offset_string = sprintf( '%+03d%02d', int( $gmoffset / 60 ), $gmoffset % 60 );
            if ($time_supplied) {
                return $offset_string;
            }
            else {
                $server_offset_string = $offset_string;
            }
        }
    }
    return $server_offset_string;
}

sub get_server_offset_in_seconds {
    if ( !defined $server_offset ) {
        if ( get_server_offset_as_offset_string() =~ m/([-+]?[0-9]{2})([0-9]{2})/ ) {
            my ( $hours, $minutes ) = ( $1, $2 );
            my $seconds = ( ( abs($hours) * 60 * 60 ) + ( $minutes * 60 ) );
            $server_offset = $hours < 0 ? "-$seconds" : $seconds;
        }
        else {

            $server_offset = 0;
        }
    }
    return $server_offset;
}

1;

} # --- END Cpanel/Time/Local.pm


{ # --- BEGIN Cpanel/Fcntl/Constants.pm
package Cpanel::Fcntl::Constants;


use strict;
use warnings;


BEGIN {
    our $O_RDONLY  = 0;
    our $O_WRONLY  = 1;
    our $O_RDWR    = 2;
    our $O_ACCMODE = 3;

    our $F_GETFD = 1;
    our $F_SETFD = 2;
    our $F_GETFL = 3;
    our $F_SETFL = 4;

    our $SEEK_SET    = 0;
    our $SEEK_CUR    = 1;
    our $SEEK_END    = 2;
    our $S_IWOTH     = 2;
    our $S_ISUID     = 2048;
    our $S_ISGID     = 1024;
    our $O_CREAT     = 64;
    our $O_EXCL      = 128;
    our $O_TRUNC     = 512;
    our $O_APPEND    = 1024;
    our $O_NONBLOCK  = 2048;
    our $O_DIRECTORY = 65536;
    our $O_NOFOLLOW  = 131072;
    our $O_CLOEXEC   = 524288;

    our $S_IFREG  = 32768;
    our $S_IFDIR  = 16384;
    our $S_IFCHR  = 8192;
    our $S_IFBLK  = 24576;
    our $S_IFIFO  = 4096;
    our $S_IFLNK  = 40960;
    our $S_IFSOCK = 49152;
    our $S_IFMT   = 61440;

    our $LOCK_SH = 1;
    our $LOCK_EX = 2;
    our $LOCK_NB = 4;
    our $LOCK_UN = 8;

    our $FD_CLOEXEC = 1;
}

1;

} # --- END Cpanel/Fcntl/Constants.pm


{ # --- BEGIN Cpanel/Fcntl.pm
package Cpanel::Fcntl;


use strict;
use warnings;

# use Cpanel::Fcntl::Constants ();

my %CONSTANTS;
my %CACHE;

sub or_flags {
    my (@flags) = @_;
    my $flag_cache_key = join( '|', @flags );
    return $CACHE{$flag_cache_key} if defined $CACHE{$flag_cache_key};
    my $numeric = 0;
    foreach my $o_const (@flags) {
        $numeric |= (
            $CONSTANTS{$o_const} ||= do {
                my $glob     = $Cpanel::Fcntl::Constants::{$o_const};
                my $number_r = $glob && *{$glob}{'SCALAR'};

                die "Missing \$Cpanel::Fcntl::Constants::$o_const! (does it need to be added?)" if !$number_r;

                $$number_r;
            }
        );
    }
    return ( $CACHE{$flag_cache_key} = $numeric );
}

1;

} # --- END Cpanel/Fcntl.pm


{ # --- BEGIN Cpanel/FileUtils/Open.pm
package Cpanel::FileUtils::Open;


use strict;

# use Cpanel::Fcntl ();

sub sysopen_with_real_perms {    ##no critic qw(RequireArgUnpacking)
    my ( $file, $mode, $custom_perms ) = ( @_[ 1 .. 3 ] );

    if ( $mode && substr( $mode, 0, 1 ) eq 'O' ) {
        $mode = Cpanel::Fcntl::or_flags( split m<\|>, $mode );
    }

    my ( $sysopen_perms, $original_umask );

    if ( defined $custom_perms ) {
        $custom_perms &= 0777;
        $original_umask = umask( $custom_perms ^ 07777 );
        $sysopen_perms  = $custom_perms;
    }
    else {
        $sysopen_perms = 0666;
    }

    my $ret = sysopen( $_[0], $file, $mode, $sysopen_perms );

    if ( defined $custom_perms ) {

        () = umask($original_umask);
    }

    return $ret;
}

1;

} # --- END Cpanel/FileUtils/Open.pm


{ # --- BEGIN Cpanel/Parser/Vars.pm
package Cpanel::Parser::Vars;


use strict;

our $current_tag            = '';
our $can_leave_cpanelaction = 1;
our $buffer                 = '';

our $loaded_api   = 0;
our $trial_mode   = 0;
our $sent_headers = 0;
our $live_socket_file;

our $incpanelaction = 0;
our $altmode        = 0;
our $jsonmode       = 0;
our $javascript     = 0;
our $title          = 0;
our $input          = 0;
our $style          = 0;
our $embtag         = 0;
our $textarea       = 0;

our $file           = '[stdin]';
our $firstfile      = '[stdin]';
our $trap_defaultfh = undef;       # Known to be boolean.

our %BACKCOMPAT;

our $cptag;
our $sent_content_type;

1;

} # --- END Cpanel/Parser/Vars.pm


{ # --- BEGIN Cpanel/Encoder/Tiny/Rare.pm
package Cpanel::Encoder::Tiny::Rare;


use strict;
use warnings;



sub angle_bracket_decode {
    my ($string) = @_;
    $string =~ s{ &lt; }{<}xmsg;
    $string =~ s{ &gt; }{>}xmsg;
    return $string;
}


sub decode_utf8_html_entities {
    my $str = shift;
    $str =~ s/&\#(\d{4})\;/chr($1);/eg;
    return $str;
}

my %uri_encoding_cache = (
    '"'  => '%22',
    q{'} => '%27',
    '('  => '%28',
    ')'  => '%29',
    q{ } => '%20',
    "\t" => '%09',
);


sub css_encode_str {
    my $str = shift;
    $str =~ s{([\(\)\s"'])}{
        $uri_encoding_cache{$1}
        || require Cpanel::Encoder::URI && Cpanel::Encoder::URI::uri_encode_str($1)
    }ge;
    return $str;
}

1;

} # --- END Cpanel/Encoder/Tiny/Rare.pm


{ # --- BEGIN Cpanel/Encoder/Tiny.pm
package Cpanel::Encoder::Tiny;


use strict;

my %XML_ENCODE_MAP  = ( '&'   => '&amp;', '<'  => '&lt;', '>'  => '&gt;', '"'    => '&quot;', "'"    => '&apos;' );
my %HTML_ENCODE_MAP = ( '&'   => '&amp;', '<'  => '&lt;', '>'  => '&gt;', '"'    => '&quot;', "'"    => '&#39;' );
my %HTML_DECODE_MAP = ( 'amp' => '&',     'lt' => '<',    'gt' => '>',    'quot' => '"',      'apos' => q{'}, '#39' => q{'} );

my $decode_regex = do { my $tmp = join( '|', keys %HTML_DECODE_MAP ); "&($tmp);"; };

sub angle_bracket_encode {
    my ($string) = @_;
    $string =~ s{<}{&lt;}xmsg;
    $string =~ s{>}{&gt;}xmsg;
    return $string;
}

sub safe_xml_encode_str {
    my $data = join( '', @_ );
    return $data if $data !~ tr/&<>"'//;
    $data =~ s/([&<>"'])/$XML_ENCODE_MAP{$1}/sg;
    return $data;
}

sub safe_html_encode_str {
    return $_[0] if !defined $_[0] || ( !defined $_[1] && $_[0] !~ tr/&<>"'// );
    my $data = defined $_[1] ? join( '', @_ ) : $_[0];
    return $data if $data !~ tr/&<>"'//;
    $data =~ s/([&<>"'])/$HTML_ENCODE_MAP{$1}/sg;
    return $data;
}

sub safe_html_decode_str {
    return undef if !defined $_[0];
    my $data = join( '', @_ );
    $data =~ s/$decode_regex/$HTML_DECODE_MAP{$1}/g;
    return $data;
}

sub css_encode_str {
    require Cpanel::Encoder::Tiny::Rare;
    *css_encode_str = *Cpanel::Encoder::Tiny::Rare::css_encode_str;
    goto \&Cpanel::Encoder::Tiny::Rare::css_encode_str;
}

1;

} # --- END Cpanel/Encoder/Tiny.pm


{ # --- BEGIN Cpanel/Regex.pm
package Cpanel::Regex;


use strict;

our $VERSION = '0.2.5';

my $dblquotedstr = q{"([^\\\\"]*(?:\\\\.[^\\\\"]*)*)"};
my $sglquotedstr = $dblquotedstr;
$sglquotedstr =~ tr{"}{'};

my $zero_through_255 = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?|0)';

our %regex = (
    'emailaddr'              => '[a-zA-Z0-9!#\$\-=?^_{}~]+(?:\.[a-zA-Z0-9!#\$\-=?^_{}~]+)*(?:\+[a-zA-Z0-9 \.=\-\_]+)*\@[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?(?:\.[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?)*',
    'oneplusdot'             => '\.+',
    'oneplusspacetab'        => '[\s\t]+',
    'multipledot'            => '\.{2,}',
    'commercialat'           => '\@',
    'plussign'               => '\+',
    'singledot'              => '\.',
    'newline'                => '\n',
    'doubledot'              => '\.\.',
    'lineofdigits'           => '^\d+$',
    'lineofnonprintingchars' => '^[\s\t]*$',
    'getemailtransport'      => '^from\s+.*\s+by\s+\S+\s+with\s+(\S+)',
    'getreceivedfrom'        => '^from\s+(.*)\s+by\s+',
    'emailheaderterminator'  => '^[\r\n]*$',
    'forwardslash'           => '\/',

    'backslash'             => chr(92) x 4,
    'singlequote'           => q('),
    'doublequote'           => '"',
    'allspacetabchars'      => '[\s\t]*',
    'beginswithspaceortabs' => '^[\s\t]',

    doublequotedstring => $dblquotedstr,
    singlequotedstring => $sglquotedstr,

    DUNS => '[0-9]{2}(?:-[0-9]{3}-[0-9]{4}|[0-9]{7})',

    YYYY_MM_DD => '[0-9]{4}-(?:1[012]|0[1-9])-(?:3[01]|[12][0-9]|0[1-9])',

    ipv4 => "(?:$zero_through_255\.){3}$zero_through_255",

    iso_z_time => '[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z',
);

1;

} # --- END Cpanel/Regex.pm


{ # --- BEGIN Cpanel/Carp.pm
package Cpanel::Carp;


use strict;

# use Cpanel::Parser::Vars ();

our ( $SHOW_TRACE, $OUTPUT_FORMAT, $VERBOSE ) = ( 1, 'text', 0 );

my $__CALLBACK_AFTER_DIE_SPEW;    # Set when we need to run a code ref after spewing on die

my $error_count = 0;

sub import { return enable(); }

sub enable {
    my (
        $callback_before_warn_or_die_spew,    # Runs before the spew on warn or die, currently used in cpanel to ensure we emit headers before body in the event of a warn or die spew
        $callback_before_die_spew,            # Runs before the spew on die, not currently used
        $callback_after_die_spew,             # Runs after the spew on die, currently used in whostmgr to ensure we emit the javascript footer when we die to avoid the UI breaking
    ) = @_;

    $SIG{'__WARN__'} = sub {                  ## no critic qw(Variables::RequireLocalizedPunctuationVars)
        my @caller = caller(1);
        return if defined $caller[3] && index( $caller[3], 'eval' ) > -1;    # Case 35335: Quiet spurious warn errors from evals

        ++$error_count;

        my $time = time();
        my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time);

        my ( $gmmin, $gmhour, $gmday ) = ( gmtime($time) )[ 1, 2, 3 ];

        my $gmoffset        = ( $hour * 60 + $min ) - ( $gmhour * 60 + $gmmin ) + 1440 * ( $mday <=> $gmday );
        my $tz              = sprintf( '%+03d%02d', int( $gmoffset / 60 ), $gmoffset % 60 );
        my $error_timestamp = sprintf( '%04d-%02d-%02d %02d:%02d:%02d %s', $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $tz );

        my $longmess;
        my $ignorable;
        if ( UNIVERSAL::isa( $_[0], 'Cpanel::Exception' ) ) {
            $longmess = Cpanel::Carp::safe_longmess( $_[0]->to_locale_string() );
        }
        elsif ( ref $_[0] eq 'Template::Exception' ) {
            $longmess = Cpanel::Carp::safe_longmess( "Template::Exception:\n\t[TYPE]=[" . $_[0]->[0] . "]\n\t[INFO]=[" . $_[0]->[1] . "]\n\t[TEXT]=[" . ( ref $_[0]->[2] eq 'SCALAR' ? ${ $_[0]->[2] } : $_[0]->[2] ) . "]\n" );
        }
        else {
            $longmess  = Cpanel::Carp::safe_longmess(@_);
            $ignorable = 1 if index( $_[0], 'Use of uninitialized value' ) == 0;
        }

        my $error_container_text = 'A warning occurred while processing this directive.';

        my $current_file = $Cpanel::Parser::Vars::file || 'unknown';
        print STDERR "[$error_timestamp] warn [Internal Warning while parsing $current_file $$] $longmess\n\n";

        return if ( $OUTPUT_FORMAT eq 'suppress' || $OUTPUT_FORMAT eq 'supress' || $ENV{'CPANEL_PHPENGINE'} );

        return if $ignorable && !$VERBOSE;

        _run_callback_without_die_handler($callback_before_warn_or_die_spew) if $callback_before_warn_or_die_spew;

        if ( $OUTPUT_FORMAT eq 'html' ) {
            if ($SHOW_TRACE) {
                _print_without_die_handler( _generate_html_error_message( 'warn', $error_container_text, $longmess ) );
            }
            else {
                _print_without_die_handler(qq{<span class="error" style="cursor:hand;cursor:pointer;">[$error_container_text]</span>});
            }
        }
        elsif ( $OUTPUT_FORMAT eq 'xml' ) {
            _print_without_die_handler("<error>$error_container_text</error>");
        }
        else {
            _print_without_die_handler("[$error_container_text]\n");
        }
    };

    $SIG{'__DIE__'} = sub {    ## no critic qw(Variables::RequireLocalizedPunctuationVars)

        return if $^S;

        die $_[0] unless defined $^S;

        delete $SIG{'__DIE__'};
        _run_callback_without_die_handler($callback_before_warn_or_die_spew) if $callback_before_warn_or_die_spew;
        _run_callback_without_die_handler($callback_before_die_spew)         if $callback_before_die_spew;

        $__CALLBACK_AFTER_DIE_SPEW = $callback_after_die_spew;

        goto \&spew_on_die;
    };

    return 1;
}

sub spew_on_die {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ($err) = @_;

    ++$error_count;

    my $time = time();
    my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time);

    my ( $gmmin, $gmhour, $gmday ) = ( gmtime($time) )[ 1, 2, 3 ];

    my $gmoffset        = ( $hour * 60 + $min ) - ( $gmhour * 60 + $gmmin ) + 1440 * ( $mday <=> $gmday );
    my $tz              = sprintf( '%+03d%02d', int( $gmoffset / 60 ), $gmoffset % 60 );
    my $error_timestamp = sprintf( '%04d-%02d-%02d %02d:%02d:%02d %s', $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $tz );

    my $error_text;
    if ( UNIVERSAL::isa( $err, 'Cpanel::Exception' ) ) {
        $error_text = Cpanel::Carp::safe_longmess( $err->to_locale_string() );
    }
    elsif ( UNIVERSAL::isa( $err, 'Template::Exception' ) ) {
        $error_text = Cpanel::Carp::safe_longmess( "Template::Exception:\n\t[TYPE]=[" . $err->type() . "]\n\t[INFO]=[" . $err->info() . "]\n\t[TEXT]=[" . $err->text() . "]\n" );
    }
    else {
        $error_text = Cpanel::Carp::safe_longmess(@_);
    }

    my $current_file = $Cpanel::Parser::Vars::file || 'unknown';
    print STDERR "[$error_timestamp] die [Internal Death while parsing $current_file $$] $error_text\n\n";

    return if ( $OUTPUT_FORMAT eq 'suppress' || $OUTPUT_FORMAT eq 'supress' || $ENV{'CPANEL_PHPENGINE'} );

    my $error_container_text = 'A fatal error or timeout occurred while processing this directive.';

    if ( $OUTPUT_FORMAT eq 'html' ) {
        if ($SHOW_TRACE) {
            _print_without_die_handler( _generate_html_error_message( 'error', $error_container_text, $error_text ) );
        }
        else {
            _print_without_die_handler(qq{<span class="error" style="cursor:hand;cursor:pointer;">[$error_container_text]</span>});
        }
    }
    elsif ( $OUTPUT_FORMAT eq 'xml' ) {
        _print_without_die_handler("<error>[$error_container_text]</error>");
    }
    else {
        _print_without_die_handler("[$error_container_text]\n");
    }

    _run_callback_without_die_handler($__CALLBACK_AFTER_DIE_SPEW) if $__CALLBACK_AFTER_DIE_SPEW;

    return;
}

my @SAFE_LONGMESS_KEY_REGEXP_ITEMS = (
    '(?<![a-zA-Z0-9_])pw(?![a-zA-Z0-9_])',
    qw(
      hash
      pass
      auth
      root
      key
      fullbackup
    ),
);

my @SAFE_LONGMESS_FUNCTION_REGEXP_ITEMS = (
    @SAFE_LONGMESS_KEY_REGEXP_ITEMS,
    '__ANON__',
);

sub _print_without_die_handler {
    my ($text) = @_;

    local $SIG{'__WARN__'} = sub { };
    local $SIG{'__DIE__'}  = 'DEFAULT';

    return print $text;
}

sub _run_callback_without_die_handler {
    my ($callback) = @_;
    local $SIG{'__WARN__'} = sub { };
    local $SIG{'__DIE__'}  = 'DEFAULT';

    return $callback->();
}

sub _generate_html_error_message {
    my ( $type, $error_container_message, $error_message ) = @_;

    require Cpanel::Encoder::Tiny;
    my $safe_error_message = Cpanel::Encoder::Tiny::safe_html_encode_str($error_message);


    return qq[
<style type="text/css">.cpanel_internal_message_container {display: inline-block; margin: 10px; width: auto;} .cpanel_internal_message { border: 1px solid #fff; outline-style: solid; outline-width: 1px; outline-color: #aaa; padding: 5px; } .cpanel_internal_error_warn { background-color: #FFF6CF; } .cpanel_internal_error_error { background-color: #F8E7E6; }</style>
<div id="cpanel_notice_item_$error_count" class="cjt-pagenotice-container cjt-notice-container cpanel_internal_message_container internal-error-container">
    <div class="yui-module cjt-notice cjt-pagenotice cjt-notice-$type">
        <div class="cpanel_internal_message cpanel_internal_error_$type bd">
            <div class="cjt-notice-content" style="width: 420px;">
                <span>
                    $error_container_message
                    <a
                        class="error"
                        style="cursor:hand;cursor:pointer;"
                        onClick="document.getElementById('cpanel_internal_error_$error_count').style.display='';this.style.display='none'; return false;">
                        [show]
                    </a>
                    <a
                        class="error"
                        style="cursor:hand;cursor:pointer;"
                        onClick="document.getElementById('cpanel_notice_item_$error_count').style.display='none'; return false;">
                        [close]
                    </a>
                </span>
                <div id="cpanel_internal_error_$error_count" style="display:none;">
                    <textarea class="cpanel_internal_error_$type" style="font-weight:900; height:200px; width:410px; color: black;">$safe_error_message</textarea>
                </div>
            </div>
        </div>
    </div>
</div>
    ];
}

sub safe_longmess {
    require Carp;
    $Carp::Internal{'Cpanel::Carp'} = 1;
    return sanitize_longmess( scalar Carp::longmess(@_) );
}

my ( $key_regexp, $key_regexp_double, $function_regexp );

sub sanitize_longmess {

    _build_regexes() if !$key_regexp;

    return join(
        "\n",
        map {
            ( tr{'"}{} && ( m{$key_regexp}o || m{$key_regexp_double}o || ( ( $_ =~ m{^[ \t]*([^\(]+)\(} )[0] || '' ) =~ m{$function_regexp}o ) )    # matches a line that needs to be sanitized
              && _sanitize_line($_);                                                                                                                # sanitize
            $_
        } split( m{\n}, $_[0] )
    ) . "\n";
}

sub _sanitize_line {    # Operates directly on $_[0] for speed
    if ( !$INC{'Cpanel/Regex.pm'} ) {    # PPI NO PARSE - inc check
        local $@;
        eval {
            local $SIG{__DIE__};
            local $SIG{__WARN__};
            require Cpanel::Regex;    # PPI NO PARSE - inc check
        };
    }
    $_[0] =~ s/$Cpanel::Regex::regex{'singlequotedstring'}/__CPANEL_HIDDEN__/go if index( $_[0], q{'} ) != -1;
    $_[0] =~ s/$Cpanel::Regex::regex{'doublequotedstring'}/__CPANEL_HIDDEN__/go if index( $_[0], q{"} ) != -1;
    return 1;
}

sub _build_regexes {

    my $key_regexp_items = join '|', @SAFE_LONGMESS_KEY_REGEXP_ITEMS;
    $key_regexp = qr<
        '
        .*?
        (?:
            $key_regexp_items
        )
        .*?
        '
        \s*
        ,
    >x;

    $key_regexp_double = $key_regexp;
    $key_regexp_double =~ tr{'}{"};    # "' fix for poor editors

    my $function_regexp_items = join '|', @SAFE_LONGMESS_FUNCTION_REGEXP_ITEMS;
    $function_regexp = qr<
        ::
        .*?
        (?:
            $function_regexp_items
        )
        .*?
        $
    >x;

    return 1;
}

1;

} # --- END Cpanel/Carp.pm


{ # --- BEGIN Cpanel/Set.pm
package Cpanel::Set;


use strict;
use warnings;



sub difference {
    my ($super_ar) = @_;

    my %lookup;
    @lookup{ map { @$_ } @_[ 1 .. $#_ ] } = ();

    return grep { !exists $lookup{$_} } @$super_ar;
}


sub intersection {
    my ( $super_ar, $sub_ar ) = @_;

    my %lookup;
    @lookup{@$sub_ar} = ();

    return grep { exists $lookup{$_} } @$super_ar;
}

1;

} # --- END Cpanel/Set.pm


{ # --- BEGIN Cpanel/TimeHiRes.pm
package Cpanel::TimeHiRes;


use strict;
use warnings;


use constant {
    _gettimeofday => 96,

    _clock_gettime  => 228,
    _CLOCK_REALTIME => 0,

    _EINTR => 4,

    _PACK_TEMPLATE => 'L!L!',
};


sub clock_gettime {
    my $timeval = pack( _PACK_TEMPLATE, () );

    _get_time_from_syscall(
        _clock_gettime,
        _CLOCK_REALTIME,
        $timeval,
    );

    return unpack( _PACK_TEMPLATE, $timeval );
}


sub time {
    my ( $secs, $nsecs ) = clock_gettime();

    return $secs + ( $nsecs / 1_000_000_000 );
}


sub sleep {
    my ($secs) = @_;


    local $!;
    my $retval = select( undef, undef, undef, $secs );
    if ( $retval == -1 && $! != _EINTR ) {
        require Cpanel::Exception;
        die 'Cpanel::Exception'->can('create')->( 'SystemCall', 'The system failed to suspend command execution for [quant,_1,second,seconds] because of an error: [_2]', [ $secs, $! ] );
    }

    return $secs;
}


sub gettimeofday {
    my $timeval = pack( _PACK_TEMPLATE, () );

    _get_time_from_syscall(
        _gettimeofday,
        $timeval,
        undef,
    );

    return unpack( _PACK_TEMPLATE, $timeval );
}


sub _get_time_from_syscall {    ##no critic qw(RequireArgUnpacking)
    my $syscall_num = shift;

    local $!;
    my $retval = syscall( $syscall_num, @_ );
    if ( $retval == -1 ) {
        require Cpanel::Exception;
        die 'Cpanel::Exception'->can('create')->( 'SystemCall', 'The system failed to retrieve the time because of an error: [_1]', [$!] );
    }

    return;
}

1;

} # --- END Cpanel/TimeHiRes.pm


{ # --- BEGIN Cpanel/SafeFileLock.pm
package Cpanel::SafeFileLock;


use strict;
use warnings;


use constant {
    _ENOENT => 2,
    _EDQUOT => 122,
    DEBUG   => 0,

    MAX_LOCKFILE_SIZE => 8192,
};


sub new {
    my ( $class, $path_to_lockfile, $fh, $path_to_file_being_locked ) = @_;

    if ( scalar @_ != 4 ) {
        die 'Usage: Cpanel::SafeFileLock->new($path_to_lockfile, $fh, $path_to_file_being_locked)';
    }

    if ($fh) {
        write_lock_contents( $fh, $path_to_lockfile ) or return;
    }


    my $self = bless [
        $path_to_lockfile,
        $fh,
        $path_to_file_being_locked,
    ], $class;

    push @$self, @{ $self->stat_ar() }[ 1, 9 ];

    return $self;
}

sub new_before_lock {
    my ( $class, $path_to_lockfile, $path_to_file_being_locked ) = @_;

    if ( scalar @_ != 3 ) {
        die 'Usage: Cpanel::SafeFileLock->new_before_lock($path_to_lockfile, $path_to_file_being_locked)';
    }

    return bless [
        $path_to_lockfile,
        undef,
        $path_to_file_being_locked,
    ], $class;
}

sub set_filehandle_and_unlinker_after_lock {

    $_[0][1] = $_[1];

    push @{ $_[0] }, @{ $_[0]->stat_ar() }[ 1, 9 ];

    $_[0][5] = $_[2];
    return $_[0];
}

sub get_path {
    return $_[0]->[0];
}

sub get_path_to_file_being_locked {
    return $_[0]->[2] // die "get_path_to_file_being_locked requires the object to be instantiated with the path_to_file_being_locked";
}

sub set_filehandle {
    $_[0][1] = $_[1];
    return $_[0];
}

sub get_filehandle {
    return $_[0]->[1];
}

sub get_inode {
    return $_[0]->[3];
}

sub get_mtime {
    return $_[0]->[4];
}

sub get_path_fh_inode_mtime {
    return @{ $_[0] }[ 0, 1, 3, 4 ];
}

sub stat_ar {
    return [ stat( ( $_[0]->[1] && fileno( $_[0]->[1] ) ) ? $_[0]->[1] : $_[0]->[0] ) ];
}

sub lstat_ar {

    return [ $_[0]->[1] && fileno( $_[0]->[1] ) ? stat( $_[0]->[1] ) : lstat( $_[0]->[0] ) ];
}

sub close {

    return close $_[0]->[1] if ref $_[0]->[1];

    $_[0]->[5] = undef;

    return;
}


sub write_lock_contents {    ## no critic qw(Subroutines::RequireArgUnpacking) -- only unpack on the failure case
    local $!;

    if (DEBUG) {
        require Cpanel::Carp;
        return 1 if syswrite( $_[0], "$$\n$0\n" . Cpanel::Carp::safe_longmess() . "\n" );
    }
    return 1 if syswrite( $_[0], "$$\n$0\n" );

    my ( $fh, $path_to_lockfile ) = @_;
    my $write_error = $!;

    CORE::close($fh);
    unlink $path_to_lockfile;

    require Cpanel::Exception;
    die Cpanel::Exception::create( 'IO::FileWriteError', [ 'path' => $path_to_lockfile, 'error' => $write_error ] );
}

sub fetch_lock_contents_if_exists {
    my ($lockfile) = @_;

    die 'Need lock file!' if !$lockfile;

    open my $lockfile_fh, '<:stdio', $lockfile or do {
        return if $! == _ENOENT();

        die "open($lockfile): $!";
    };

    my $buffer;
    my $read_result = read( $lockfile_fh, $buffer, MAX_LOCKFILE_SIZE );

    if ( !defined $read_result ) {
        die "read($lockfile): $!";
    }

    my ( $pid_line, $lock_name, $lock_obj ) = split( /\n/, $buffer, 3 );
    chomp($lock_name) if length $lock_name;
    my ($lock_pid) = $pid_line && ( $pid_line =~ m/(\d+)/ );

    return ( $lock_pid, $lock_name || 'unknown', $lock_obj || 'unknown', $lockfile_fh );
}


1;


} # --- END Cpanel/SafeFileLock.pm


{ # --- BEGIN Cpanel/FHUtils/Tiny.pm
package Cpanel::FHUtils::Tiny;


use strict;
use warnings;




sub is_a {
    return !ref $_[0] ? 0 : ( ref $_[0] eq 'IO::Handle' || ref $_[0] eq 'GLOB' || UNIVERSAL::isa( $_[0], 'GLOB' ) ) ? 1 : 0;
}


sub are_same {
    my ( $fh1, $fh2 ) = @_;

    return 1 if $fh1 eq $fh2;

    if ( fileno($fh1) && ( fileno($fh1) != -1 ) && fileno($fh2) && ( fileno($fh2) != -1 ) ) {
        return 1 if fileno($fh1) == fileno($fh2);
    }

    return 0;
}


sub to_bitmask {
    my @fhs = @_;

    my $mask = q<>;

    for my $fh (@fhs) {
        vec( $mask, ref($fh) ? fileno($fh) : $fh, 1 ) = 1;
    }

    return $mask;
}

1;

} # --- END Cpanel/FHUtils/Tiny.pm


{ # --- BEGIN Cpanel/Debug.pm
package Cpanel::Debug;


use strict;
use warnings;



our $HOOKS_DEBUG_FILE = '/var/cpanel/debughooks';

our $level = ( exists $ENV{'CPANEL_DEBUG_LEVEL'} && $ENV{'CPANEL_DEBUG_LEVEL'} ? int $ENV{'CPANEL_DEBUG_LEVEL'} : 0 );



my $debug_hooks_value;
my $logger;


sub debug_level {
    my ($level) = @_;
    $Cpanel::Debug::level = $level if defined $level;
    return $Cpanel::Debug::level;
}

sub logger {
    $logger = shift if (@_);    # Set method for $logger if something is passed in.

    return $logger ||= do {
        local ( $@, $! );
        require Cpanel::Logger;

        Cpanel::Logger->new();
    };
}

sub log_error {
    local $!;                   #prevent logger from overwriting $!
    return logger()->error( $_[0] );
}


sub log_warn {
    local $!;    #prevent logger from overwriting $!
    return logger()->warn( $_[0] );
}

sub log_warn_no_backtrace {
    local $!;    #prevent logger from overwriting $!

    my $logger = logger();

    local $Cpanel::Logger::ENABLE_BACKTRACE = 0;

    return $logger->warn( $_[0] );
}

sub log_invalid {
    local $!;    #prevent logger from overwriting $!
    return logger()->invalid( $_[0] );
}

sub log_deprecated {
    local $!;    #prevent logger from overwriting $!
    return logger()->deprecated( $_[0] );
}

sub log_panic {
    local $!;    #prevent logger from overwriting $!
    return logger()->panic( $_[0] );
}

sub log_die {
    local $!;    #prevent logger from overwriting $!
    return logger()->die( $_[0] );
}

sub log_info {
    local $!;    #prevent logger from overwriting $!
    return logger()->info( $_[0] );
}

sub log_debug {
    local $!;    #prevent logger from overwriting $!
    return logger()->debug( $_[0] );
}

sub debug_hooks_value {
    return $debug_hooks_value if defined $debug_hooks_value;
    return ( $debug_hooks_value = ( stat($HOOKS_DEBUG_FILE) )[7] || 0 );
}

1;

} # --- END Cpanel/Debug.pm


{ # --- BEGIN Cpanel/Hash.pm
package Cpanel::Hash;



use strict;




*get_fastest_hash = \&fnv1a_32;


use constant FNV1_32A_INIT => 0x811c9dc5;

use constant FNV_32_PRIME => 0x01000193;

use constant FNV_32_MOD => 2**32;    # AKA 0x100000000 but that it non-portable;
sub fnv1a_32 {
    my $fnv32 = FNV1_32A_INIT();
    ( $fnv32 = ( ( $fnv32 ^ $_ ) * FNV_32_PRIME() ) % FNV_32_MOD ) for unpack( 'C*', $_[0] );
    return $fnv32;
}

1;

} # --- END Cpanel/Hash.pm


{ # --- BEGIN Cpanel/SafeFile/LockInfoCache.pm
package Cpanel::SafeFile::LockInfoCache;


use strict;
use warnings;

# use Cpanel::SafeFileLock ();


sub new {
    my ( $class, $pathname ) = @_;

    die 'need path!' if !$pathname;

    return bless { _path => $pathname }, $class;
}


sub get {
    my ( $self, $inode, $mtime ) = @_;

    die 'Need an inode & an mtime!' if !defined $inode || !defined $mtime;

    if ( !exists $self->{"_inode_${inode}_$mtime"} ) {
        my ( $pid, $name, $obj, $fh ) = Cpanel::SafeFileLock::fetch_lock_contents_if_exists( $self->{'_path'} );

        if ($pid) {

            my ( $real_inode, $real_mtime ) = ( stat $fh )[ 1, 9 ];
            $self->{"_inode_${real_inode}_$real_mtime"} = [ $pid, $name, $obj ];
        }
    }

    return $self->{"_inode_${inode}_$mtime"} ||= undef;
}

1;

} # --- END Cpanel/SafeFile/LockInfoCache.pm


{ # --- BEGIN Cpanel/SafeFile/LockWatcher.pm
package Cpanel::SafeFile::LockWatcher;


use strict;
use warnings;

use constant _ENOENT => 2;

use constant _FILEHANDLE_TTL => 2;


sub new {
    my ( $class, $lockfile ) = @_;

    my $self = bless { _path => $lockfile, _new => 1 }, $class;

    return $self->reload_from_disk();
}


sub reload_from_disk {
    my ($self) = @_;

    my $old_inode = $self->{'inode'};
    @{$self}{qw( inode  uid  size mtime)} = $self->_get_inode_uid_size_mtime();

    if ( delete $self->{'_new'} ) {
        $self->{'changed'} = 0;
    }
    else {
        $self->{'changed'} = ( $self->{'inode'} || 0 ) != ( $old_inode || 0 ) ? 1 : 0;
    }

    return $self;
}

sub _get_inode_uid_size_mtime {
    my ($self) = @_;

    my ( $inode, $uid, $size, $mtime );

    local $!;

    if ( open my $fh, '<', $self->{'_path'} ) {
        ( $inode, $uid, $size, $mtime ) = ( stat $fh )[ 1, 4, 7, 9 ];

        $self->_add_fh_if_needed( $fh, $inode );
    }
    elsif ( $! != _ENOENT ) {
        die "open(<, $self->{'_path'}): $!";
    }

    return ( $inode, $uid, $size, $mtime );
}

sub _add_fh_if_needed {
    my ( $self, $fh, $inode ) = @_;

    my $now        = time;
    my $fhs_hr     = $self->{'_time_fhs'} //= {};
    my $seen_inode = 0;

    for my $time ( keys %$fhs_hr ) {

        if ( ( $now - $time ) > _FILEHANDLE_TTL() ) {
            delete $fhs_hr->{$time};
            next;
        }

        if ( !$seen_inode ) {
            foreach my $entry ( @{ $fhs_hr->{$time} } ) {
                if ( $entry->[1] == $inode ) {
                    $seen_inode = 1;
                    last;
                }
            }
        }
    }

    return if $seen_inode;

    push @{ $fhs_hr->{ time() } }, [ $fh, $inode ];

    return;
}

1;

} # --- END Cpanel/SafeFile/LockWatcher.pm


{ # --- BEGIN Cpanel/Autodie.pm
package Cpanel::Autodie;


use strict;
use warnings;



sub _ENOENT { return 2; }
sub _EEXIST { return 17; }
sub _EINTR  { return 4; }

sub import {
    shift;

    _load_function($_) for @_;

    return;
}

our $AUTOLOAD;

sub AUTOLOAD {
    substr( $AUTOLOAD, 0, 1 + rindex( $AUTOLOAD, ':' ) ) = q<>;

    _load_function($AUTOLOAD);

    goto &{ Cpanel::Autodie->can($AUTOLOAD) };
}

sub _load_function {
    _require("Cpanel/Autodie/CORE/$_[0].pm");

    return;
}

sub _require {
    local ( $!, $^E, $@ );

    require $_[0];
    return;
}

1;

} # --- END Cpanel/Autodie.pm


{ # --- BEGIN Cpanel/Pack.pm
package Cpanel::Pack;



use strict;

sub new {
    my ( $class, $template_ar ) = @_;

    if ( @$template_ar % 2 ) {
        die "Cpanel::Pack::new detected an odd number of elements in hash assignment!";
    }

    my $self = bless {
        'template_str' => '',
        'keys'         => [],
    }, $class;

    my $ti = 0;
    while ( $ti < $#$template_ar ) {
        push @{ $self->{'keys'} }, $template_ar->[$ti];
        $self->{'template_str'} .= $template_ar->[ 1 + $ti ];
        $ti += 2;
    }

    return $self;
}

sub unpack_to_hashref {    ## no critic (RequireArgUnpacking)
    my %result;
    @result{ @{ $_[0]->{'keys'} } } = unpack( $_[0]->{'template_str'}, $_[1] );
    return \%result;
}

sub pack_from_hashref {
    my ( $self, $opts_ref ) = @_;
    no warnings 'uninitialized';
    return pack( $self->{'template_str'}, @{$opts_ref}{ @{ $self->{'keys'} } } );
}

sub sizeof {
    my ($self) = @_;
    return ( $self->{'sizeof'} ||= length pack( $self->{'template_str'}, () ) );
}

sub malloc {
    my ($self) = @_;

    return pack( $self->{'template_str'} );
}

1;

} # --- END Cpanel/Pack.pm


{ # --- BEGIN Cpanel/Syscall.pm
package Cpanel::Syscall;



use strict;

my %NAME_TO_NUMBER = qw(
  close             3
  fcntl            72
  lchown           94
  getrlimit        97
  getsid          124
  gettimeofday     96
  sendfile         40
  setrlimit       160
  splice          275
  write             1
  setsid          112
  getsid          124
  inotify_init1     294
  inotify_add_watch 254
  inotify_rm_watch  255
  setresuid       117
  setresgid       119
  setgroups       116
  umount2         166
);

sub name_to_number {
    my ($name) = @_;

    return $NAME_TO_NUMBER{$name} || _die_unknown_syscall($name);
}

sub _die_unknown_syscall {
    my ($name) = @_;

    die "Unknown system call: “$name”";
}

sub syscall {    ##no critic qw(RequireArgUnpacking)
    local $!;

    _die_unknown_syscall( $_[0] ) unless defined $_[0] && $NAME_TO_NUMBER{ $_[0] };

    my $ret = CORE::syscall( $NAME_TO_NUMBER{ $_[0] }, scalar @_ > 1 ? @_[ 1 .. $#_ ] : () );
    if ( ( $ret == -1 ) && $! ) {
        if ( $INC{'Cpanel/Exception.pm'} ) {
            die Cpanel::Exception::create( 'SystemCall', [ name => $_[0], error => $!, arguments => [ @_[ 1 .. $#_ ] ] ] );
        }
        else {
            die "Failed system call “$_[0]”: $!";
        }
    }

    return $ret;
}

1;

} # --- END Cpanel/Syscall.pm


{ # --- BEGIN Cpanel/Inotify.pm
package Cpanel::Inotify;



use strict;
use warnings;

# use Cpanel::Autodie          ();
# use Cpanel::Context          ();
# use Cpanel::Exception        ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::Pack             ();
# use Cpanel::Syscall          ();

use constant POLL_SIZE => 65536;

use constant READ_TEMPLATE => (
    wd     => 'i',    #int        Watch descriptor
    mask   => 'I',    #uint32_t   Mask of events
    cookie => 'I',    #uint32_t   Unique cookie associating related events
    len    => 'I',    #uint32_t   Size of “name” field
);

my %add_flags;
my %read_flags;
my %init1_flag;

my $UNPACK_OBJ;
my $UNPACK_SIZE;


sub new {
    my ( $class, %opts ) = @_;

    if ( !$UNPACK_OBJ ) {
        $UNPACK_OBJ  = Cpanel::Pack->new( [ READ_TEMPLATE() ] );
        $UNPACK_SIZE = $UNPACK_OBJ->sizeof();

        _setup_flags();
    }

    my @given_flags = $opts{'flags'} ? @{ $opts{'flags'} } : ();

    my $mask = 0;
    for my $f (@given_flags) {
        $mask |= $init1_flag{$f} || do {
            die Cpanel::Exception->create_raw("Invalid inotify_init1 flag: “$f”");
        };
    }

    my $fd = Cpanel::Syscall::syscall( 'inotify_init1', $mask );

    my %self = (
        _fd => $fd,
    );
    Cpanel::Autodie::open( $self{'_fh'}, '<&=', $fd );

    return bless \%self, $class;
}


sub add {
    my ( $self, $path, %opts ) = @_;

    my @flags = @{ $opts{'flags'} };

    my $mask = 0;
    for my $f (@flags) {
        $mask |= $add_flags{$f} || do {
            die Cpanel::Exception->create_raw("Invalid inotify_add_watch flag: “$f”");
        };
    }

    my $wd = Cpanel::Syscall::syscall(
        'inotify_add_watch',
        $self->{'_fd'},
        $path,
        $mask,
    );

    if ( $wd < 1 ) {
        die Cpanel::Exception->create_raw("inotify watch descriptor “$wd” means something is wrong?");
    }

    $self->{'_watches'}{$wd} = $path;

    return $wd;
}


sub remove {
    my ( $self, $wd ) = @_;

    Cpanel::Syscall::syscall( 'inotify_rm_watch', $self->{'_fd'}, $wd );

    return;
}


sub poll {
    my ($self) = @_;

    Cpanel::Context::must_be_list();

    my $buf = q<>;

    Cpanel::Autodie::sysread_sigguard( $self->{'_fh'}, $buf, POLL_SIZE() );

    my @events;

    while ( length $buf ) {
        my $evt = $UNPACK_OBJ->unpack_to_hashref( substr( $buf, 0, $UNPACK_SIZE, q<> ) );
        $evt->{'name'} = substr( $buf, 0, delete( $evt->{'len'} ), q<> );
        $evt->{'name'} =~ s<\0+\z><>;    #trailing NULs

        $evt->{'flags'} = _mask_to_flags_ar( delete $evt->{'mask'} );

        push @events, $evt;
    }

    return @events;
}


sub fileno {
    my ($self) = @_;
    return fileno( $self->{'_fh'} );
}


sub _mask_to_flags_ar {
    my ($mask) = @_;

    my @flags;
    for my $k ( keys %read_flags ) {
        push @flags, $k if $mask & $read_flags{$k};
    }

    @flags = sort @flags;

    return \@flags;
}

sub _setup_flags {

    my %flag_num = (
        ACCESS        => 0x1,      # File was accessed
        MODIFY        => 0x2,      # File was modified
        ATTRIB        => 0x4,      # Metadata changed
        CLOSE_WRITE   => 0x8,      # File opened for writing was closed
        CLOSE_NOWRITE => 0x10,     # File not opened for writing was closed
        OPEN          => 0x20,     # File was opened
        MOVED_FROM    => 0x40,     # File was moved from X
        MOVED_TO      => 0x80,     # File was moved to Y
        CREATE        => 0x100,    # Subfile was created
        DELETE        => 0x200,    # Subfile was deleted
        DELETE_SELF   => 0x400,    # Self was deleted
        MOVE_SELF     => 0x800,    # Self was moved
    );

    %read_flags = (
        %flag_num,

        UNMOUNT    => 0x00002000,    # Backing fs was unmounted
        Q_OVERFLOW => 0x00004000,    # Event queued overflowed ('wd' is -1)
        IGNORED    => 0x00008000,    # Watch was removed
        ISDIR      => 0x40000000,    # event occurred against dir
    );

    %add_flags = (
        %flag_num,

        ONLYDIR     => 0x01000000,    # only watch the path if it is a directory
        DONT_FOLLOW => 0x02000000,    # don't follow a sym link
        EXCL_UNLINK => 0x04000000,    # exclude events on unlinked objects
        MASK_ADD    => 0x20000000,    # add to the mask of an already existing watch
        ONESHOT     => 0x80000000,    # only send event once

        CLOSE => $read_flags{'CLOSE_WRITE'} | $read_flags{'CLOSE_NOWRITE'},
        MOVE  => $read_flags{'MOVED_FROM'} | $read_flags{'MOVED_TO'},
    );

    my $mask = 0;
    $mask |= $_ for values %flag_num;

    $add_flags{'ALL_EVENTS'} = $mask;

    %init1_flag = (
        CLOEXEC  => $Cpanel::Fcntl::Constants::O_CLOEXEC,
        NONBLOCK => $Cpanel::Fcntl::Constants::O_NONBLOCK,
    );

    return;
}

1;

} # --- END Cpanel/Inotify.pm


{ # --- BEGIN Cpanel/SafeFile.pm
package Cpanel::SafeFile;


use strict;
use warnings;



# use Cpanel::TimeHiRes        ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::SafeFileLock     ();
# use Cpanel::FHUtils::Tiny    ();

use constant {
    _EWOULDBLOCK => 11,
    _EACCES      => 13,
    _EDQUOT      => 122,
    _ENOENT      => 2,
    _EINTR       => 4,
    _EEXIST      => 17,
    _ENOSPC      => 28,
    _EPERM       => 1,

    MAX_LOCK_CREATE_ATTEMPTS => 90,

    NO_PERM_TO_WRITE_TO_DOTLOCK_DIR => -1,

    INOTIFY_FILE_DISAPPEARED => 2,

    CREATE_FCNTL_VALUE => ( $Cpanel::Fcntl::Constants::O_WRONLY | $Cpanel::Fcntl::Constants::O_EXCL | $Cpanel::Fcntl::Constants::O_CREAT | $Cpanel::Fcntl::Constants::O_NONBLOCK ),
    UNLOCK_FCNTL_VALUE => $Cpanel::Fcntl::Constants::LOCK_UN,

    LOCK_FILE_PERMS => 0644,

    DEFAULT_LOCK_WAIT_TIME => 196,

    MAX_LOCK_WAIT_TIME => 400,

    MAX_LOCK_FILE_LENGTH => 225,
};

$Cpanel::SafeFile::VERSION = '5.0';

my $OVERWRITE_FCNTL_VALUE;
my $verbose = 0;    # initialized in safelock

our $LOCK_WAIT_TIME;    #allow lock wait time to be overwritten

my $OPEN_LOCKS = 0;

our $TIME_BETWEEN_DOTLOCK_CHECKS = 0.3;
our $TIME_BETWEEN_FLOCK_CHECKS   = 0.05;
our $MAX_FLOCK_WAIT              = 60;     # allowed to be overwritten in tests

our $_SKIP_DOTLOCK_WHEN_NO_PERMS = 0;

our $_SKIP_WARN_ON_OPEN_FAIL = 0;


my $DOUBLE_LOCK_DETECTED = 4096;

sub safeopen {    #fh, open()-style mode, path
    my ( $mode, $file ) = _get_open_args( @_[ 1 .. $#_ ] );

    my $open_method_coderef = sub {
        my $ret = open( $_[0], $_[1], $_[2] ) || do {
            _log_warn("open($_[1], $_[2]): $!");
            return undef;
        };
        return $ret;
    };

    return _safe_open( $_[0], $mode, $file, $open_method_coderef, 'safeopen' );
}

sub safesysopen_no_warn_on_fail {
    local $_SKIP_WARN_ON_OPEN_FAIL = 1;

    return safesysopen(@_);
}

sub safesysopen_skip_dotlock_if_not_root {
    local $_SKIP_DOTLOCK_WHEN_NO_PERMS = $> == 0 ? 0 : 1;

    return safesysopen(@_);
}

sub safeopen_skip_dotlock_if_not_root {
    local $_SKIP_DOTLOCK_WHEN_NO_PERMS = $> == 0 ? 0 : 1;

    return safeopen(@_);
}

sub safelock_skip_dotlock_if_not_root {
    local $_SKIP_DOTLOCK_WHEN_NO_PERMS = $> == 0 ? 0 : 1;

    return safelock(@_);
}

sub safereopen {    ##no critic qw(RequireArgUnpacking)
    my $fh = shift;

    if ( !$fh ) {
        require Cpanel::Carp;
        die Cpanel::Carp::safe_longmess("Undefined filehandle not allowed!");
    }
    elsif ( !fileno $fh ) {
        require Cpanel::Carp;
        die Cpanel::Carp::safe_longmess("Closed filehandle ($fh) not allowed!");
    }

    my ( $mode, $file ) = _get_open_args(@_);

    my $open_method_coderef = sub {
        return open( $_[0], $_[1], $_[2] ) || do {
            _log_warn("open($_[1], $_[2]): $!");
            return undef;
        };
    };

    return _safe_re_open( $fh, $mode, $file, $open_method_coderef, 'safereopen' );
}

sub safesysopen {    ##no critic qw(RequireArgUnpacking)
    my ( $file, $open_mode, $custom_perms ) = ( @_[ 1 .. 3 ] );

    my ( $sysopen_perms, $original_umask );

    $open_mode = _sanitize_open_mode($open_mode);

    my $open_method_coderef = sub {
        return sysopen( $_[0], $_[2], $_[1], $sysopen_perms ) || do {
            _log_warn("open($_[2], $_[1], $sysopen_perms): $!") unless $_SKIP_WARN_ON_OPEN_FAIL;
            return undef;
        };
    };

    if ( defined $custom_perms ) {
        $custom_perms &= 0777;
        $original_umask = umask( $custom_perms ^ 07777 );
        $sysopen_perms  = $custom_perms;
    }
    else {
        $sysopen_perms = 0666;
    }

    my $lock_ref;

    local $@;
    my $ok = eval {
        $lock_ref = _safe_open( $_[0], $open_mode, $file, $open_method_coderef, 'safesysopen' );
        1;
    };

    if ( defined $custom_perms ) {
        umask($original_umask);
    }

    die if !$ok;

    return $lock_ref;
}

sub safeclose {
    my ( $fh, $lockref, $do_something_before_releasing_lock ) = @_;

    if ( $do_something_before_releasing_lock && ref $do_something_before_releasing_lock eq 'CODE' ) {
        $do_something_before_releasing_lock->();
    }

    my $success = 1;
    if ( $fh && defined fileno $fh ) {

        flock( $fh, UNLOCK_FCNTL_VALUE ) or _log_warn( "flock(LOCK_UN) on “" . $lockref->get_path() . "” failed with error: $!" );    # LOCK_UN
        $success = close $fh;
    }

    my $safe_unlock = safeunlock($lockref);

    $OPEN_LOCKS-- if ( $safe_unlock && $success );

    return ( $safe_unlock && $success );
}

sub safelock {
    my ($file) = @_;

    my $lock_obj = _safelock($file);


    return if !ref $lock_obj;

    return $lock_obj;
}

sub _safelock {
    my ($file) = @_;
    if ( !$file || $file =~ tr/\0// ) {
        _log_warn('safelock: Invalid arguments');
        return;
    }
    $verbose ||= ( _verbose_flag_file_exists() ? 1 : -1 );

    my $lockfile      = _calculate_lockfile($file);
    my $safefile_lock = Cpanel::SafeFileLock->new_before_lock( $lockfile, $file );
    my ( $lock_status, $lock_fh, $attempts, $last_err );

    {
        local $@;

        while ( ++$attempts < MAX_LOCK_CREATE_ATTEMPTS ) {

            ( $lock_status, $lock_fh ) = _lock_wait( $file, $safefile_lock, $lockfile );

            last if $lock_status;

            $last_err = $!;

            if ( $lock_fh && $lock_fh == $DOUBLE_LOCK_DETECTED ) {
                return 0;
            }
        }

    }

    if ( $lock_fh == 1 ) {
        return 1;
    }
    elsif ( $lock_status && $lock_fh ) {
        return $safefile_lock;
    }

    _log_warn( 'safelock: waited for lock (' . $lockfile . ') ' . $attempts . ' times' );
    require Cpanel::Exception;
    die Cpanel::Exception::create( 'IO::FileCreateError', [ 'path' => $lockfile, 'error' => $last_err ] );
}

sub _write_temp_lock_file {
    my ($lockfile) = @_;

    my $temp_file = sprintf(
        '%s-%x-%x-%x',
        $lockfile,
        substr( rand, 2 ),
        scalar( reverse time ),
        scalar( reverse $$ ),
    );

    my ( $ok, $fh_or_err ) = _create_lockfile($temp_file);
    if ( !$ok ) {


        if ( $fh_or_err == _EPERM() || $fh_or_err == _EACCES() ) {

            local $!;

            my $lock_dir = _getdir($lockfile);
            if ( !-w $lock_dir ) {


                if ($_SKIP_DOTLOCK_WHEN_NO_PERMS) {    # A hack to allow /etc/valiases to still be flock()ed until we can refactor
                    return ( NO_PERM_TO_WRITE_TO_DOTLOCK_DIR, $fh_or_err );
                }
                else {
                    _log_warn("safelock: Failed to create a lockfile '$temp_file' in the directory '$lock_dir' that isn't writable: $fh_or_err");
                }
            }
        }

        return ( 0, $fh_or_err );
    }

    Cpanel::SafeFileLock::write_lock_contents( $fh_or_err, $temp_file );

    return ( $temp_file, $fh_or_err );
}

sub _try_to_install_lockfile {
    my ( $temp_file, $lockfile ) = @_;

    link( $temp_file => $lockfile ) or do {
        return 0 if $! == _EEXIST;

        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::LinkError', [ oldpath => $temp_file, newpath => $lockfile, error => $! ] );
    };

    return 1;
}

sub safeunlock {
    my $lockref = shift;

    if ( !$lockref ) {
        _log_warn('safeunlock: Invalid arguments');
        return;
    }
    elsif ( !ref $lockref ) {
        return 1 if $lockref eq '1';    # No lock file created so just succeed
        $lockref = Cpanel::SafeFileLock->new( $lockref, undef, undef );
        if ( !$lockref ) {
            _log_warn("safeunlock: failed to generate a Cpanel::SafeFileLock object from a path");
            return;
        }
    }
    my ( $lock_path, $fh, $lock_inode, $lock_mtime ) = $lockref->get_path_fh_inode_mtime();

    my ( $filesys_lock_ino, $filesys_lock_mtime ) = ( lstat $lock_path )[ 1, 9 ];

    if ( $fh && !defined fileno($fh) ) {

        return 1;
    }
    elsif ( !$filesys_lock_mtime ) {
        _log_warn( 'Lock on ' . $lockref->get_path_to_file_being_locked() . ' lost!' );
        $lockref->close();
        return;    # return false on false
    }

    elsif ( $lock_inode && ( $lock_inode == $filesys_lock_ino ) && $lock_path && ( $lock_mtime == $filesys_lock_mtime ) ) {
        unlink $lock_path or do {
            _log_warn("Could not unlink lock file “$lock_path” as ($>/$)): $!\n");
            $lockref->close();
            return;    # return false on false
        };
        return $lockref->close();
    }

    $lockref->close();
    my ( $lock_pid, $lock_name, $lock_obj ) = Cpanel::SafeFileLock::fetch_lock_contents_if_exists($lock_path);

    if ($lock_pid) {

        $lock_inode ||= 0;
        $lock_mtime ||= 0;

        _log_warn("[$$] Attempt to unlock file that was locked by another process [LOCK_PATH]=[$lock_path] [LOCK_PID]=[$lock_pid] [LOCK_PROCESS]=[$lock_name] [LOCK_INODE]=[$filesys_lock_ino] [LOCK_MTIME]=[$filesys_lock_mtime] -- [NON_LOCK_PID]=[$$] [NON_LOCK_PROCESS]=[$0] [NON_LOCK_INODE]=[$lock_inode] [NON_LOCK_MTIME]=[$lock_mtime]");
    }
    return;
}

sub _safe_open {

    my ( undef, $open_mode, $file, $open_method_coderef, $open_method ) = @_;

    if ( !defined $open_mode || !$open_method_coderef || !$file || $file =~ tr/\0// ) {
        _log_warn('_safe_open: Invalid arguments');
        return;
    }
    elsif ( defined $_[0] ) {
        my $fh_type = ref $_[0];
        if ( !Cpanel::FHUtils::Tiny::is_a( $_[0] ) ) {
            _log_warn("Invalid file handle type '$fh_type' provided for $open_method of '$file'");
            return;
        }
    }

    if ( my $lockref = _safelock($file) ) {
        if ( $open_method_coderef->( $_[0], $open_mode, $file ) ) {
            if ( my $err = _do_flock_or_return_exception( $_[0], $open_mode, $file ) ) {
                safeunlock($lockref);
                local $@ = $err;
                die;
            }

            $OPEN_LOCKS++;
            return $lockref;
        }
        else {

            local $!;

            safeunlock($lockref);
            return;
        }
    }
    else {
        _log_warn("safeopen: could not acquire a lock for '$file': $!");
        return;
    }
}

my $_lock_ex_nb;
my $_lock_sh_nb;

sub _do_flock_or_return_exception {
    my ( $fh, $open_mode, $path ) = @_;

    my $flock_start_time;

    my $lock_op =
      _is_write_open_mode($open_mode)
      ? ( $_lock_ex_nb //= $Cpanel::Fcntl::Constants::LOCK_EX | $Cpanel::Fcntl::Constants::LOCK_NB )
      : ( $_lock_sh_nb //= $Cpanel::Fcntl::Constants::LOCK_SH | $Cpanel::Fcntl::Constants::LOCK_NB );

    local $!;
    my $flock_err;

    my $flock_max_wait_time_is_whole_number = int($MAX_FLOCK_WAIT) == $MAX_FLOCK_WAIT;

    while ( !flock $fh, $lock_op ) {
        $flock_err = $!;

        if ( $flock_err == _EINTR || $flock_err == _EWOULDBLOCK ) {
            if ( !$flock_start_time ) {
                $flock_start_time = $flock_max_wait_time_is_whole_number ? time() : Cpanel::TimeHiRes::time();
                next;
            }

            if ( ( ( $flock_max_wait_time_is_whole_number ? time() : Cpanel::TimeHiRes::time() ) - $flock_start_time ) > $MAX_FLOCK_WAIT ) {
                require Cpanel::Exception;
                return _timeout_exception( $path, $MAX_FLOCK_WAIT );
            }
            else {
                Cpanel::TimeHiRes::sleep($TIME_BETWEEN_FLOCK_CHECKS);
            }
            next;
        }

        require Cpanel::Exception;
        return Cpanel::Exception::create( 'IO::FlockError', [ path => $path, error => $flock_err, operation => $lock_op ] );
    }

    return undef;
}

sub _safe_re_open {
    my ( $fh, $open_mode, $file, $open_method_coderef, $open_method ) = @_;

    if ( !defined $open_mode || !$open_method_coderef || !$file || $file =~ tr/\0// ) {
        _log_warn('_safe_re_open: Invalid arguments');
        return;
    }
    else {
        my $fh_type = ref $fh;
        if ( !Cpanel::FHUtils::Tiny::is_a($fh) ) {
            _log_warn("Invalid file handle type '$fh_type' provided for $open_method of '$file'");
            return;
        }
    }

    close $fh;
    if ( $open_method_coderef->( $fh, $open_mode, $file ) ) {
        if ( my $err = _do_flock_or_return_exception( $fh, $open_mode, $file ) ) {
            die $err;
        }

        return $fh;
    }
    return;
}

sub _log_warn {
    require Cpanel::Debug;
    goto &Cpanel::Debug::log_warn;
}

sub _get_open_args {
    my ( $mode, $file ) = @_;
    if ( !$file ) {
        ( $mode, $file ) = $mode =~ m/^([<>+|]+|)(.*)/;
        if ( $file && !$mode ) {
            $mode = '<';
        }
        elsif ( !$file ) {
            return;
        }
    }

    $mode =
        $mode eq '<'   ? '<'
      : $mode eq '>'   ? '>'
      : $mode eq '>>'  ? '>>'
      : $mode eq '+<'  ? '+<'
      : $mode eq '+>'  ? '+>'
      : $mode eq '+>>' ? '+>>'
      :                  return;

    return ( $mode, $file );
}

sub _sanitize_open_mode {
    my ($mode) = @_;

    return if $mode =~ m/[^0-9]/;

    my $safe_mode = ( $mode & $Cpanel::Fcntl::Constants::O_RDONLY );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_WRONLY );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_RDWR );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_CREAT );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_EXCL );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_APPEND );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_TRUNC );
    $safe_mode |= ( $mode & $Cpanel::Fcntl::Constants::O_NONBLOCK );

    return $safe_mode;
}

sub _calculate_lockfile {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $lockfile = $_[0] =~ tr{<>}{} ? ( ( $_[0] =~ /^[><]*(.*)/ )[0] . '.lock' ) : $_[0] . '.lock';

    return $lockfile if ( length $lockfile <= MAX_LOCK_FILE_LENGTH );

    require File::Basename;
    my $lock_basename = File::Basename::basename($lockfile);

    return $lockfile if ( length $lock_basename <= MAX_LOCK_FILE_LENGTH );

    require Cpanel::Hash;
    my $hashed_lock_basename = Cpanel::Hash::get_fastest_hash($lock_basename) . ".lock";

    if ( $lockfile eq $lock_basename ) {
        return $hashed_lock_basename;
    }
    else {
        return File::Basename::dirname($lockfile) . '/' . $hashed_lock_basename;
    }
}

sub is_locked {
    my ($file) = @_;
    my $lockfile = _calculate_lockfile($file);
    my ( $lock_pid, $lock_name, $lock_obj ) = Cpanel::SafeFileLock::fetch_lock_contents_if_exists($lockfile);

    if ( _is_valid_pid($lock_pid) && _pid_is_alive($lock_pid) ) {
        return 1;
    }

    return 0;
}

sub _timeout_exception {
    my ( $path, $waited ) = @_;

    require Cpanel::Exception;
    return Cpanel::Exception::create( 'Timeout', 'The system failed to lock the file “[_1]” after [quant,_2,second,seconds].', [ $path, $waited ] );
}

sub _die_if_file_is_flocked_cuz_already_waited_a_while {
    my ( $file, $waited ) = @_;

    if ( _open_to_write( my $fh, $file ) ) {
        $_lock_ex_nb //= $Cpanel::Fcntl::Constants::LOCK_EX | $Cpanel::Fcntl::Constants::LOCK_NB;
        if ( flock( $fh, $_lock_ex_nb ) == 1 ) {


            flock $fh, UNLOCK_FCNTL_VALUE or die "Failed to unlock “$file” after having just locked it: $!";
        }
        else {
            require Cpanel::Exception;

            if ( $! == _EWOULDBLOCK ) {
                die _timeout_exception( $file, $waited );
            }
            else {
                die Cpanel::Exception::create( 'IO::FlockError', [ path => $file, error => $!, operation => $_lock_ex_nb ] );
            }
        }
    }

    return;
}

sub _lock_wait {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $file, $safefile_lock, $lockfile ) = @_;

    my ( $temp_file, $fh ) = _write_temp_lock_file( $lockfile, $file );

    if ( $temp_file eq NO_PERM_TO_WRITE_TO_DOTLOCK_DIR ) {
        return ( 1, 1 );
    }

    if ( !$temp_file ) {
        return ( 0, $fh );
    }

    $safefile_lock->set_filehandle_and_unlinker_after_lock( $fh, Cpanel::SafeFile::_temp->new($temp_file) );

    return ( 1, $fh ) if _try_to_install_lockfile( $temp_file, $lockfile );

    local $0 = ( $verbose == 1 ) ? "$0 - waiting for lock on $file" : "$0 - waiting for lock";

    require Cpanel::SafeFile::LockInfoCache;
    require Cpanel::SafeFile::LockWatcher;

    my $watcher = Cpanel::SafeFile::LockWatcher->new($lockfile);

    my $waittime = _calculate_waittime_for_file($file);

    my ( $inotify_obj, $inotify_mask, $inotify_file_disappeared );

    my $start_time = time;
    my $waited     = 0;

    my $lockfile_cache = Cpanel::SafeFile::LockInfoCache->new($lockfile);

    my ( $inotify_inode, $inotify_mtime );

  LOCK_WAIT:
    while (1) {
        $waited = ( time() - $start_time );

        if ( $waited > $waittime ) {

            _die_if_file_is_flocked_cuz_already_waited_a_while( $file, $waited );

            if ( defined $watcher->{'inode'} ) {
                require Cpanel::Debug;
                Cpanel::Debug::log_warn( sprintf "Replacing stale lock file: $lockfile. The kernel’s lock is gone, last modified %s seconds ago (mtime=$watcher->{'mtime'}), and waited over $waittime seconds.", time - $watcher->{'mtime'} );
            }

            return ( 1, $fh ) if _overwrite_lockfile_if_inode_mtime_matches( $temp_file, $lockfile, $watcher->{'inode'}, $watcher->{'mtime'} );

            die _timeout_exception( $file, $waittime );
        }

        if ( $watcher->{'inode'} ) {
            my $lock_get = $lockfile_cache->get( @{$watcher}{ 'inode', 'mtime' } );

            if ( !$lock_get ) {


                my $size_before_reload = $watcher->{'size'};
                $watcher->reload_from_disk();

                if ( $size_before_reload == 0 && $watcher->{'size'} == 0 ) {
                    _log_warn("[$$] UID $> clobbering empty lock file “$lockfile” (UID $watcher->{'uid'}) written by “unknown” at $watcher->{'mtime'}");


                    return ( 1, $fh ) if _overwrite_lockfile_if_inode_mtime_matches( $temp_file, $lockfile, $watcher->{'inode'}, $watcher->{'mtime'} );
                }

                next LOCK_WAIT;
            }

            my ( $lock_pid, $lock_name, $lock_obj ) = @$lock_get;

            if ( $lock_pid == $$ ) {
                $watcher->reload_from_disk();

                _log_warn("[$$] Double locking detected by self [LOCK_PATH]=[$lockfile] [LOCK_PID]=[$lock_pid] [LOCK_OBJ]=[$lock_obj] [LOCK_PROCESS]=[$lock_name] [ACTUAL_INODE]=[$watcher->{'inode'}] [ACTUAL_MTIME]=[$watcher->{'mtime'}]");
                return ( 0, $DOUBLE_LOCK_DETECTED );
            }
            elsif ( !_pid_is_alive($lock_pid) ) {

                my $time = time();

                if ( _overwrite_lockfile_if_inode_mtime_matches( $temp_file, $lockfile, $watcher->{'inode'}, $watcher->{'mtime'} ) ) {
                    _log_warn("[$$] TIME $time UID $> clobbered stale lock file “$lockfile” (NAME “$lock_name”, UID $watcher->{'uid'}) written by PID $lock_pid at $watcher->{'mtime'}");
                    return ( 1, $fh );
                }

                $watcher->reload_from_disk();
                next LOCK_WAIT;
            }
            else {
                require Cpanel::Debug;
                Cpanel::Debug::log_info("[$$] Waiting for lock on $file held by $lock_name with pid $lock_pid") if $verbose == 1;
            }
        }

        return ( 1, $fh ) if _try_to_install_lockfile( $temp_file, $lockfile );



        $watcher->reload_from_disk();

        if ( !$inotify_obj || !$inotify_inode || !$watcher->{'inode'} || $inotify_inode != $watcher->{'inode'} || $inotify_mtime != $watcher->{'mtime'} ) {

          INOTIFY: {
                ( $inotify_obj, $inotify_mask, $inotify_file_disappeared ) = _generate_inotify_for_lock_file($lockfile);

                $watcher->reload_from_disk();

                if ( $inotify_file_disappeared || !$watcher->{'inode'} ) {

                    undef $inotify_obj;

                    next LOCK_WAIT;
                }

                redo INOTIFY if $watcher->{'changed'};

                ( $inotify_inode, $inotify_mtime ) = @{$watcher}{ 'inode', 'mtime' };
            }
        }

        my $selected = _select( my $m = $inotify_mask, undef, undef, $TIME_BETWEEN_DOTLOCK_CHECKS );

        if ( $selected == -1 ) {

            die "select() error: $!" if $! != _EINTR();
        }
        elsif ($selected) {
            return ( 1, $fh ) if _try_to_install_lockfile( $temp_file, $lockfile );

            $watcher->reload_from_disk();

            () = $inotify_obj->poll();
        }
    }

    return;
}

sub _select {
    return select( $_[0], $_[1], $_[2], $_[3] );
}

sub _generate_inotify_for_lock_file {
    my ($file) = @_;
    require Cpanel::Inotify;
    my $inotify_obj;
    my $rin = '';

    local $@;
    eval {
        $inotify_obj = Cpanel::Inotify->new( flags => ['NONBLOCK'] );

        $inotify_obj->add( $file, flags => [ 'ATTRIB', 'DELETE_SELF' ] );

        vec( $rin, $inotify_obj->fileno(), 1 ) = 1;
    };

    if ($@) {
        my $err = $@;

        if ( eval { $err->isa('Cpanel::Exception::SystemCall') } ) {
            my $err = $err->get('error');
            if ( $err == _ENOENT ) {
                return ( undef, undef, INOTIFY_FILE_DISAPPEARED );
            }
            elsif ( $err != _EACCES ) {    # Don’t warn if EACCES
                local $@ = $err;
                warn;
            }
        }
        else {
            local $@ = $err;
            warn;
        }

        return;
    }

    return ( $inotify_obj, $rin, 0 );
}

sub _pid_is_alive {
    my ($pid) = @_;

    local $!;

    if ( kill( 0, $pid ) ) {
        return 1;
    }

    elsif ( $! == _EPERM ) {
        return !!( stat "/proc/$pid" )[0];
    }

    return 0;
}

sub _calculate_waittime_for_file {
    my ($file) = @_;

    return $LOCK_WAIT_TIME if $LOCK_WAIT_TIME;

    my $waittime = DEFAULT_LOCK_WAIT_TIME;

    if ( -e $file ) {
        $waittime = int( ( stat _ )[7] / 10000 );

        $waittime = $waittime > MAX_LOCK_WAIT_TIME ? MAX_LOCK_WAIT_TIME : $waittime < DEFAULT_LOCK_WAIT_TIME ? DEFAULT_LOCK_WAIT_TIME : $waittime;
    }

    return $waittime;
}

sub _is_valid_pid {
    my $pid = shift;

    return 0 unless defined $pid;

    return $pid =~ tr{0-9}{}c ? 0 : 1;
}

sub _getdir {
    my @path = split( /\/+/, $_[0] );
    return join( '/', (@path)[ 0 .. ( $#path - 1 ) ] ) || '.';
}

sub _create_lockfile {
    my $lock_fh;

    return sysopen( $lock_fh, $_[0], CREATE_FCNTL_VALUE, LOCK_FILE_PERMS ) ? ( 1, $lock_fh ) : ( 0, $! );
}

sub _open_to_write {
    my $path = $_[1];

    $OVERWRITE_FCNTL_VALUE ||= ( $Cpanel::Fcntl::Constants::O_WRONLY | $Cpanel::Fcntl::Constants::O_NONBLOCK | $Cpanel::Fcntl::Constants::O_APPEND | $Cpanel::Fcntl::Constants::O_NOFOLLOW );

    return sysopen( $_[0], $path, $OVERWRITE_FCNTL_VALUE, LOCK_FILE_PERMS );
}

sub _overwrite_lockfile_if_inode_mtime_matches {
    my ( $temp_file, $lockfile, $lockfile_inode, $lockfile_mtime ) = @_;

    my ( $inode, $mtime ) = ( stat $lockfile )[ 1, 9 ];

    if ( !$inode ) {
        die "stat($lockfile): $!" if $! != _ENOENT();
    }


    if ( !$inode || ( $inode == $lockfile_inode && $mtime == $lockfile_mtime ) ) {
        rename( $temp_file, $lockfile ) or do {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'IO::RenameError', [ oldpath => $temp_file, newpath => $lockfile, error => $! ] );
        };

        return 1;
    }

    return 0;
}

sub _is_write_open_mode {
    my ($mode) = @_;

    if ( $mode =~ tr{0-9}{}c ) {
        if ( $mode && ( -1 != index( $mode, '>' ) || -1 != index( $mode, '+' ) ) ) {
            return 1;
        }
    }
    else {
        if ( $mode && ( ( $mode & $Cpanel::Fcntl::Constants::O_WRONLY ) || ( $mode & $Cpanel::Fcntl::Constants::O_RDWR ) ) ) {
            return 1;
        }
    }
    return 0;
}

sub _verbose_flag_file_exists {
    return -e '/var/cpanel/safefile_verbose';
}


package Cpanel::SafeFile::_temp;


use constant _ENOENT => 2;

sub new { return bless [ $_[1], $_SKIP_DOTLOCK_WHEN_NO_PERMS, $$ ], $_[0]; }

sub DESTROY {
    local $!;

    unlink $_[0]->[0] or do {
        if ( !$_[0]->[1] && $! != _ENOENT && $_[0]->[2] == $$ ) {
            warn "unlink($_[0]->[0]): $!";
        }
    };

    return;
}

1;


} # --- END Cpanel/SafeFile.pm


{ # --- BEGIN Cpanel/LoadModule.pm
package Cpanel::LoadModule;


use strict;

# use Cpanel::Exception         ();
# use Cpanel::LoadModule::Utils ();

my $logger;
my $has_perl_dir = 0;

sub _logger_warn {
    my ( $msg, $fail_ok ) = @_;

    return if $fail_ok && $ENV{'CPANEL_BASE_INSTALL'} && index( $^X, '/usr/local/cpanel' ) == -1;

    if ( $INC{'Cpanel/Logger.pm'} ) {
        $logger ||= 'Cpanel::Logger'->new();
        $logger->warn($msg);
    }
    return warn $msg;
}

sub _reset_has_perl_dir {
    $has_perl_dir = 0;
    return;
}

sub load_perl_module {    ## no critic qw(Subroutines::RequireArgUnpacking)
    if ( -1 != index( $_[0], q<'> ) ) {
        die Cpanel::Exception::create_raw( 'InvalidParameter', "Module names with single-quotes are prohibited. ($_[0])" );
    }

    return $_[0] if Cpanel::LoadModule::Utils::module_is_loaded( $_[0] );

    my ( $mod, @LIST ) = @_;

    local ( $!, $@ );

    if ( !is_valid_module_name($mod) ) {
        die Cpanel::Exception::create( 'InvalidParameter', '“[_1]” is not a valid name for a Perl module.', [$mod] );
    }

    my $args_str;
    if (@LIST) {
        $args_str = join ',', map {
            die "Only scalar arguments allowed in LIST! (@LIST)" if ref;
            _single_quote($_);
        } @LIST;
    }
    else {
        $args_str = q<>;
    }

    eval "use $mod ($args_str);";    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)

    if ($@) {
        die Cpanel::Exception::create( 'ModuleLoadError', [ module => $mod, error => $@ ] );
    }

    return $mod;
}

*module_is_loaded = *Cpanel::LoadModule::Utils::module_is_loaded;

*is_valid_module_name = *Cpanel::LoadModule::Utils::is_valid_module_name;


sub loadmodule {
    return 1 if cpanel_namespace_module_is_loaded( $_[0] );

    return _modloader( $_[0] );
}

sub lazy_load_module {
    my $mod = shift;

    my $mod_path = $mod;
    $mod_path =~ s{::}{/}g;
    if ( exists $INC{ $mod_path . '.pm' } ) {
        return;
    }

    if ( !is_valid_module_name($mod) ) {
        _logger_warn("Cpanel::LoadModule: Invalid module name ($mod)");
        return;
    }

    eval "use $mod ();";

    if ($@) {
        delete $INC{ $mod_path . '.pm' };
        _logger_warn( "Cpanel::LoadModule:: Failed to load module $mod - $@", 1 );
        return;
    }

    return 1;
}


sub cpanel_namespace_module_is_loaded {
    my ($modpart) = @_;
    $modpart =~ s{::}{/}g;
    return exists $INC{"Cpanel/$modpart.pm"} ? 1 : 0;
}

sub _modloader {
    my $module = shift;
    if ( !$module ) {
        _logger_warn("Empty module name passed to modloader");
        return;
    }
    if ( !is_valid_module_name($module) ) {
        _logger_warn("Invalid module name ($module) passed to modloader");
        return;
    }

    eval qq[ use Cpanel::${module}; Cpanel::${module}::${module}_init() if "Cpanel::${module}"->can("${module}_init"); ];    # PPI USE OK - This looks like usage of the Cpanel module and it's not.

    if ($@) {
        _logger_warn("Error loading module $module - $@");
        return;
    }

    return 1;
}

sub _single_quote {
    local ($_) = $_[0];
    s/([\\'])/\\$1/g;
    return qq('$_');
}

1;

} # --- END Cpanel/LoadModule.pm


{ # --- BEGIN Cpanel/Linux/Constants.pm
package Cpanel::Linux::Constants;


use strict;
use warnings;

use constant {
    NAME_MAX => 255,
    PATH_MAX => 4096,
};

1;

} # --- END Cpanel/Linux/Constants.pm


{ # --- BEGIN Cpanel/Validate/FilesystemNodeName.pm
package Cpanel::Validate::FilesystemNodeName;


use strict;
use warnings;

# use Cpanel::Exception        ();
# use Cpanel::Linux::Constants ();

sub is_valid {
    my ($node) = @_;

    local $@;
    eval { validate_or_die($node); };

    return $@ ? 0 : 1;
}

sub validate_or_die {
    my ($name) = @_;

    if ( !length $name ) {
        die Cpanel::Exception::create('Empty');
    }
    elsif ( $name eq '.' || $name eq '..' ) {
        die Cpanel::Exception::create( 'Reserved', [ value => $name ] );
    }
    elsif ( length $name > Cpanel::Linux::Constants::NAME_MAX() ) {
        die Cpanel::Exception::create( 'TooManyBytes', [ value => $name, maxlength => Cpanel::Linux::Constants::NAME_MAX() ] );
    }
    elsif ( index( $name, '/' ) != -1 ) {
        die Cpanel::Exception::create( 'InvalidCharacters', [ value => $name, invalid_characters => ['/'] ] );
    }
    elsif ( index( $name, "\0" ) != -1 ) {
        die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a [asis,NUL] byte.', [ value => $name, invalid_characters => ["\0"] ] );
    }

    return 1;
}

1;

} # --- END Cpanel/Validate/FilesystemNodeName.pm


{ # --- BEGIN Cpanel/Notify.pm
package Cpanel::Notify;


use strict;
use warnings;

# use Cpanel::Set                          ();
# use Cpanel::Fcntl                        ();
# use Cpanel::SafeFile                     ();
# use Cpanel::LoadModule                   ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Exception                    ();
# use Cpanel::Debug                        ();

our $VERSION = '1.8';

my $DEFAULT_CONTENT_TYPE = 'text/plain; charset=utf-8';
our $NOTIFY_INTERVAL_STORAGE_DIR = '/var/cpanel/notifications';

sub notification_class {
    my (%args) = @_;

    if ( !defined $args{'interval'} ) {
        $args{'interval'} = 1;
    }

    if ( !defined $args{'status'} ) {
        $args{'status'} = 'No status set';
    }

    foreach my $param (qw(application status class constructor_args)) {
        die Cpanel::Exception::create( 'MissingParameter', [ 'name' => $param ] ) if !defined $args{$param};
    }

    if ( my @unwelcome_params = Cpanel::Set::difference( [ keys %args ], [qw(application status class constructor_args interval)] ) ) {
        die Cpanel::Exception::create_raw(
            'InvalidParameters',
            "The following parameters don't belong as an argument to notification_class(); you may have meant to pass these in constructor_args instead: " . join( ' ', @unwelcome_params )
        );
    }

    my $constructor_args = { @{ $args{'constructor_args'} } };

    if ( $constructor_args->{'skip_send'} ) {
        my $class = "Cpanel::iContact::Class::$args{'class'}";
        Cpanel::LoadModule::load_perl_module($class);

        return $class->new(%$constructor_args);
    }

    return _notification_backend(
        $args{'application'},
        $args{'status'},
        $args{'interval'},
        sub {
            my $class = "Cpanel::iContact::Class::$args{'class'}";
            Cpanel::LoadModule::load_perl_module($class);
            return $class->new(%$constructor_args);
        },
    );
}

sub notification {
    my %AGS = @_;

    my $app = $AGS{'app'} || $AGS{'application'} || 'Notice';

    return _notification_backend(
        $app,
        $AGS{'status'},
        $AGS{'interval'} || 0,
        sub {
            my $module = "Cpanel::iContact";
            Cpanel::LoadModule::load_perl_module($module);

            my $from              = $AGS{'from'};
            my $to                = $AGS{'to'};
            my $msgheader         = $AGS{'msgheader'} || $AGS{'subject'};
            my $message           = $AGS{'message'};
            my $plaintext_message = $AGS{'plaintext_message'};
            my $priority          = $AGS{'priority'}     || 3;
            my $attach_files      = $AGS{'attach_files'} || [];

            my $content_type = $AGS{'content-type'} || $DEFAULT_CONTENT_TYPE;

            "$module"->can('icontact')->(
                'attach_files'      => $attach_files,
                'application'       => $app,
                'level'             => $priority,
                'from'              => $from,
                'to'                => $to,
                'subject'           => $msgheader,
                'message'           => $message,
                'plaintext_message' => $plaintext_message,
                'content-type'      => $content_type,
            );
        }
    );
}

sub _notification_backend {
    my ( $app, $status, $interval, $todo_cr ) = @_;

    my $is_ready = _checkstatusinterval(
        'app'      => $app,
        'status'   => $status,
        'interval' => $interval,
    );

    if ($is_ready) {
        return $todo_cr->();
    }
    elsif ( $Cpanel::Debug::level > 3 ) {
        Cpanel::Debug::log_warn("not sending notify app=[$app] status=[$status] interval=[$interval]");
    }

    return $is_ready ? 1 : 0;
}

sub notify_blocked {
    my %AGS      = @_;
    my $app      = $AGS{'app'};
    my $status   = $AGS{'status'};
    my $interval = $AGS{'interval'};

    return 0 if $interval <= 1;    # Special Case (ignore interval check);

    $app    =~ s{/}{_}g;           # Its possible to have slashes in the app name
    $status =~ s{:}{_}g;           # Its possible to have colons in the status

    my $db_file = "$NOTIFY_INTERVAL_STORAGE_DIR/$app";

    return 0 if !-e $db_file;

    my %notifications;
    my $notify_db_fh;
    if (
        my $nlock = Cpanel::SafeFile::safesysopen(
            $notify_db_fh, $db_file, Cpanel::Fcntl::or_flags('O_RDONLY'),
            0600
        )
    ) {
        local $/;
        %notifications = map { ( split( /:/, $_, 2 ) )[ 0, 1 ] } split( m{\n}, readline($notify_db_fh) );
        Cpanel::SafeFile::safeclose( $notify_db_fh, $nlock );
    }
    else {
        Cpanel::Debug::log_warn("Could not open $db_file: $!");
        return;
    }

    if ( $notifications{$status} && ( ( $notifications{$status} + $interval ) > time() ) ) {
        return 1;
    }

    return 0;
}

{
    no warnings 'once';
    *update_notification_time_if_interval_reached = \&_checkstatusinterval;
}

sub _checkstatusinterval {
    my %AGS      = @_;
    my $app      = $AGS{'app'};
    my $status   = $AGS{'status'};
    my $interval = $AGS{'interval'};

    return 1 if $interval <= 1;    # Special Case (ignore interval check);

    $app    =~ s{/}{_}g;           # Its possible to have slashes in the app name
    $status =~ s{:}{_}g;           # Its possible to have colons in the status
    Cpanel::Validate::FilesystemNodeName::validate_or_die($app);

    my $notify = 0;

    if ( !-e $NOTIFY_INTERVAL_STORAGE_DIR ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::SafeDir::MK');
        Cpanel::SafeDir::MK::safemkdir( $NOTIFY_INTERVAL_STORAGE_DIR, '0700' );
        if ( !-d $NOTIFY_INTERVAL_STORAGE_DIR ) {
            Cpanel::Debug::log_warn("Failed to setup notifications directory: $NOTIFY_INTERVAL_STORAGE_DIR: $!");
            return;
        }
    }

    my %notifications;
    my $notify_db_fh;
    my $db_file = "$NOTIFY_INTERVAL_STORAGE_DIR/$app";
    if ( my $nlock = Cpanel::SafeFile::safesysopen( $notify_db_fh, $db_file, Cpanel::Fcntl::or_flags(qw( O_RDWR O_CREAT )), 0600 ) ) {
        local $/;
        %notifications = map { ( split( /:/, $_, 2 ) )[ 0, 1 ] } split( m{\n}, readline($notify_db_fh) );
        if ( !exists $notifications{$status} || ( int( $notifications{$status} ) + int($interval) ) < time() ) {
            $notifications{$status} = time;
            $notify = 1;
        }
        seek( $notify_db_fh, 0, 0 );
        print {$notify_db_fh} join( "\n", map { $_ . ':' . $notifications{$_} } sort keys %notifications );
        truncate( $notify_db_fh, tell($notify_db_fh) );
        Cpanel::SafeFile::safeclose( $notify_db_fh, $nlock );
    }
    else {
        Cpanel::Debug::log_warn("Could not open $db_file: $!");
        return;
    }

    return $notify;
}

1;

} # --- END Cpanel/Notify.pm


{ # --- BEGIN Cpanel/Server/Utils.pm
package Cpanel::Server::Utils;


use strict;

sub is_subprocess_of_cpsrvd {
    return 0 if $INC{'cpanel/cpsrvd.pm'};    # If we ARE cpsrvd we do not want this behavior
    return $ENV{'CPANEL'} ? 1 : 0;
}

1;

} # --- END Cpanel/Server/Utils.pm


{ # --- BEGIN Cpanel/Logger.pm
package Cpanel::Logger;


use strict;

# use Cpanel::Time::Local ();

my $is_sandbox;
my $is_smoker;
our $VERSION = 1.3;

use constant TRACE_TOUCH_FILE => '/var/cpanel/log_stack_traces';

our $ENABLE_BACKTRACE;

our $DISABLE_OUTPUT;    # used by cpanminus
our $ALWAYS_OUTPUT_TO_STDERR;

our $STD_LOG_FILE   = '/usr/local/cpanel/logs/error_log';
our $PANIC_LOG_FILE = '/usr/local/cpanel/logs/panic_log';

my ( $cached_progname, $cached_prog_pid, %singleton_stash );

sub new {
    my ( $class, $hr_args ) = @_;

    if ( $hr_args->{'open_now'} && $hr_args->{'use_no_files'} ) {
        die "“open_now” and “use_no_files” mutually exclude!";
    }

    my $args_sig = 'no_args';
    if ( $hr_args && ref($hr_args) eq 'HASH' ) {

        $args_sig = join( ',', map { $_ . '=>' . $hr_args->{$_} } sort keys %{$hr_args} );    # Storable::freeze($hr_args);
    }

    my $no_load_from_cache = $hr_args->{'no_load_from_cache'} ? 1 : 0;

    if ( exists $singleton_stash{$class}{$args_sig} and !$no_load_from_cache ) {
        $singleton_stash{$class}{$args_sig}->{'cloned'}++;
    }
    else {
        $singleton_stash{$class}{$args_sig} = bless( {}, $class );
        if ( $hr_args && ref($hr_args) eq 'HASH' ) {
            foreach my $k ( keys %$hr_args ) {
                $singleton_stash{$class}{$args_sig}->{$k} = $hr_args->{$k};
            }
        }
    }
    my $self = $singleton_stash{$class}{$args_sig};

    if ( !$self->{'cloned'} ) {

        if ( $self->{'open_now'} && !$self->{'use_no_files'} ) {
            $self->_open_logfile();
        }
    }

    $self->_set_backtrace( $ENABLE_BACKTRACE // $self->{'backtrace'} // _get_backtrace_touchfile() );

    return $self;
}

sub __Logger_pushback {
    if ( @_ && index( ref( $_[0] ), __PACKAGE__ ) == 0 ) {
        return @_;
    }
    return ( __PACKAGE__->new(), @_ );
}

sub invalid {
    my ( $self, @list ) = __Logger_pushback(@_);

    my %log = (
        'message'   => $list[0],
        'level'     => 'invalid',
        'output'    => 0,
        'service'   => $self->find_progname(),
        'backtrace' => $self->get_backtrace(),
        'die'       => 0,
    );

    if ( is_sandbox() ) {
        if ( !-e '/var/cpanel/DEBUG' ) {
            $self->notify( 'invalid', \%log );
        }
        $log{'output'} = _stdin_is_tty() ? 2 : 1;
    }
    return $self->logger( \%log );
}    # end of invalid

sub is_sandbox {
    return 0           if $INC{'B/C.pm'};        # avoid cache during compile
    return $is_sandbox if defined $is_sandbox;
    return ( $is_sandbox = -e '/var/cpanel/dev_sandbox' ? 1 : 0 );
}

sub is_smoker {
    return 0          if $INC{'B/C.pm'};         # avoid cache during compile
    return $is_smoker if defined $is_smoker;
    return ( $is_smoker = -e '/var/cpanel/smoker' ? 1 : 0 );
}

sub deprecated {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ( $self, @list ) = __Logger_pushback(@_);

    my %log = (
        'message'   => $list[0],
        'level'     => 'deprecated',
        'output'    => 0,
        'service'   => $self->find_progname(),
        'backtrace' => $self->get_backtrace(),
        'die'       => 0,
    );

    unless ( is_sandbox() ) {
        $self->logger( \%log );
        return;
    }

    $self->notify( 'deprecated', \%log );

    $log{'output'} = _stdin_is_tty() ? 2 : 1;
    $log{'die'}    = 1;

    return $self->logger( \%log );
}

sub debug {
    my ( $self, $message, $conf_hr ) = @_;    # not appropriate for debug() : __Logger_pushback(@_);

    $self = $self->new() if !ref $self;

    $conf_hr ||= {
        'force'     => 0,
        'backtrace' => 0,
        'output'    => 1,    # Logger's debug level should output to STDOUT
    };
    return unless $conf_hr->{'force'} || ( defined $Cpanel::Debug::level && $Cpanel::Debug::level );    ## PPI NO PARSE - avoid recursive use statements

    if ( !defined $message ) {
        my @caller = caller();
        $message = "debug() at $caller[1] line $caller[2].";
    }

    my %log = (
        'message'   => $message,
        'level'     => 'debug',
        'output'    => $conf_hr->{'output'},
        'backtrace' => $conf_hr->{'backtrace'},
    );

    if ( ref $log{'message'} ) {

        my $outmsg = $log{'message'};
        eval 'local $SIG{__DIE__}; local $SIG{__WARN__}; require Cpanel::YAML::Syck; $outmsg = YAML::Syck::Dump($outmsg);';
        my @caller = caller();
        $log{'message'} = "$log{'message'} at $caller[1] line $caller[2]:\n" . $outmsg;
    }
    elsif ( $log{'message'} =~ m/\A\d+(?:\.\d+)?\z/ ) {
        $log{'message'} = "debug() number $log{'message'}";
    }

    $self->logger( \%log );

    return \%log;
}

sub info {
    my ( $self, @list ) = __Logger_pushback(@_);
    return $self->logger(
        {
            'message' => $list[0],
            'level'   => 'info',

            'output'    => $self->{'open_now'} ? 0 : 1,    # FB#59177: info level should output to STDOUT
            'backtrace' => 0

        }
    );
}    # end of info

sub warn {
    my ( $self, @list ) = __Logger_pushback(@_);
    return $self->logger(
        {
            'message'   => $list[0],
            'level'     => 'warn',
            'output'    => _stdin_is_tty() ? 2 : 0,
            'backtrace' => $self->get_backtrace()
        }
    );
}    # end of warn

sub error {
    my ( $self, @list ) = __Logger_pushback(@_);
    return $self->logger(
        {
            'message'   => $list[0],
            'level'     => 'error',
            'output'    => -t STDIN ? 2 : 0,
            'backtrace' => $self->get_backtrace()
        }
    );
}    # end of error

sub die {
    my ( $self, @list ) = __Logger_pushback(@_);
    my %log = (
        'message'   => $list[0],
        'level'     => 'die',
        'output'    => _stdin_is_tty() ? 2 : 0,
        'backtrace' => $self->get_backtrace()
    );
    return $self->logger( \%log );
}    # end of die

sub panic {
    my ( $self, @list ) = __Logger_pushback(@_);
    my %log = (
        'message'   => $list[0],
        'level'     => 'panic',
        'output'    => 2,
        'backtrace' => $self->get_backtrace()
    );
    return $self->logger( \%log );
}    # end of panic

sub raw {
    return $_[0]->logger(
        {
            'message'   => $_[1],
            'level'     => 'raw',
            'output'    => 0,
            'backtrace' => 0
        }
    );
}

sub cplog {
    my $msg      = shift;
    my $loglevel = shift;
    my $service  = shift;
    my $nostdout = shift;
    if ( !$nostdout ) {
        $nostdout = 1;
    }
    else {
        $nostdout = 0;
    }
    logger( { 'message' => $msg, 'level' => $loglevel, 'service' => $service, 'output' => $nostdout, 'backtrace' => $ENABLE_BACKTRACE // _get_backtrace_touchfile() } );
}    # end of cplog (deprecated)


sub _get_configuration_for_logger {
    my ( $self, $cfg_or_msg ) = @_;

    my $hr = ref($cfg_or_msg) eq 'HASH' ? $cfg_or_msg : { 'message' => $cfg_or_msg };

    $hr->{'message'} ||= 'Something is wrong';

    $hr->{'level'}  ||= '';
    $hr->{'output'} ||= 0;

    $hr->{'output'} = 0 if $DISABLE_OUTPUT;
    if ( !exists $hr->{'backtrace'} ) {
        $hr->{'backtrace'} = $self->get_backtrace();
    }

    $hr->{'use_no_files'} ||= 0;
    $hr->{'use_fullmsg'}  ||= 0;

    return $hr;
}

sub _write {
    return print { $_[0] } $_[1];
}

sub get_backtrace {
    my ($self) = __Logger_pushback(@_);

    return $ENABLE_BACKTRACE // $self->{'backtrace'};
}

sub _set_backtrace {
    my ( $self, @args ) = __Logger_pushback(@_);
    $self->{'backtrace'} = $args[0] ? 1 : 0;
    return;
}

sub _get_backtrace_touchfile {
    return -e TRACE_TOUCH_FILE ? 1 : 0;
}

sub get_fh {
    my ($self) = @_;
    return $self->{'log_fh'};
}

sub set_fh {
    my ( $self, $fh ) = @_;
    $self->{'log_fh'} = $fh;
    return 1;
}
sub logger {    ## no critic(RequireArgUnpacking)
    my ( $self, @list ) = __Logger_pushback(@_);
    my $hr = $self->_get_configuration_for_logger( $list[0] );
    my ( $msg, $time, $status );
    $status = 1;

    my ($msg_maybe_bt) = $hr->{'backtrace'} ? $self->backtrace( $hr->{'message'} ) : $hr->{'message'} . "\n";

    if ( $hr->{'level'} eq 'raw' ) {
        $msg = $hr->{'message'};
    }
    else {
        $time ||= Cpanel::Time::Local::localtime2timestamp();
        $hr->{'service'} ||= $self->find_progname();                       # only compute the service name if we HAVE to do so as it can be expensive

        if ( $self->{'log_pid'} ) {
            $msg = "[$time] $hr->{'level'} [$hr->{'service'}] [$$] $msg_maybe_bt";
        }
        else {
            $msg = "[$time] $hr->{'level'} [$hr->{'service'}] $msg_maybe_bt";
        }
    }
    unless ( $hr->{'use_no_files'} ) {

        local $self->{'log_fh'} = \*STDERR if $ALWAYS_OUTPUT_TO_STDERR;

        $self->_open_logfile() if !$self->{'log_fh'} || ( !eval { fileno( $self->{'log_fh'} ) } && !UNIVERSAL::isa( $self->{'log_fh'}, 'IO::Scalar' ) );
        _write( $self->{'log_fh'}, $msg ) or $status = 0;

        if ( $hr->{'level'} eq 'panic' || $hr->{'level'} eq 'invalid' || $hr->{'level'} eq 'deprecated' ) {
            my $panic_fh;
            require Cpanel::FileUtils::Open;
            if ( Cpanel::FileUtils::Open::sysopen_with_real_perms( $panic_fh, $PANIC_LOG_FILE, 'O_WRONLY|O_APPEND|O_CREAT', 0600 ) ) {
                $time ||= Cpanel::Time::Local::localtime2timestamp();
                $hr->{'service'} ||= $self->find_progname();                       # only compute the service name if we HAVE to do so as it can be expensive
                _write( $panic_fh, "$time $hr->{level} [$hr->{'service'}] $msg_maybe_bt" );
                close $panic_fh;
            }
        }
    }

    if ( $hr->{'output'} ) {
        $hr->{'service'} ||= $self->find_progname();    # only compute the service name if we HAVE to do so as it can be expensive
        my $out = "$hr->{level} [$hr->{'service'}] $hr->{'message'}\n";
        if ( $self->{'timestamp_prefix'} ) {
            $out = "[$time] $out";
        }
        $out = $msg if $hr->{'use_fullmsg'};

        $status &&= $self->_write_message( $hr, $out );
    }

    if ( ( $hr->{'level'} eq 'die' || $hr->{'level'} eq 'panic' || $hr->{'die'} ) ) {
        CORE::die "exit level [$hr->{'level'}] [pid=$$] ($hr->{'message'})\n";    # make sure we die if die is overwritten
    }

    return $status;
}    # end of logger

sub _write_message {
    my ( $self, $hr, $out ) = @_;
    my $status = 1;

    if ( $hr->{'output'} == 3 ) {
        _write( \*STDOUT, $out ) or $status = 0;
        _write( \*STDERR, $out ) or $status = 0;
    }
    elsif ( $hr->{'output'} == 1 && ( $self->{'use_stdout'} || _stdout_is_tty() ) ) {
        _write( \*STDOUT, $out ) or $status = 0;
    }
    elsif ( $hr->{'output'} == 2 ) {
        _write( \*STDERR, $out ) or $status = 0;
    }
    return $status;
}

sub find_progname {
    if ( $cached_progname && $cached_prog_pid == $$ ) {
        return $cached_progname;
    }
    my $s = $0;

    if ( !length $s ) {    # Someone _could_ set $0 = '';
        my $i = 1;         # 0 is always find_progname
        while ( my @service = caller( $i++ ) ) {
            last             if ( $service[3] =~ /::BEGIN$/ );
            $s = $service[1] if ( $service[1] ne '' );
        }
    }

    $s =~ s@.+/(.+)$@$1@ if $s =~ tr{/}{};

    $s =~ s@\..+$@@ if $s =~ tr{\.}{};

    $s =~ s@ .*$@@ if $s =~ tr{ }{};

    $cached_progname = $s;
    $cached_prog_pid = $$;

    return $s;
}

sub backtrace {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ( $self, @list ) = __Logger_pushback(@_);
    if ( ref $list[0] ) {
        return $list[0] if scalar @list == 1;
        return (@list);
    }
    require Cpanel::Carp;
    local $_;    # Protect surrounding program - just in case...
    local $Carp::Internal{ (__PACKAGE__) } = 1;
    local $Carp::Internal{'Cpanel::Debug'} = 1;
    return Cpanel::Carp::safe_longmess(@list);

}

sub redirect_stderr_to_error_log {
    return open( STDERR, '>>', $STD_LOG_FILE );
}

sub notify {
    my ( $self, $call, $log_ref ) = @_;

    my $time = Cpanel::Time::Local::localtime2timestamp();
    my ($bt) = $self->backtrace( $log_ref->{'message'} );
    $log_ref->{'service'} //= '';
    my $logfile = qq{$time [$log_ref->{'service'}] } . ( $bt // '' );

    if ( eval { require Cpanel::LoadModule; Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Logger::Notify'); 1; } ) {

        eval {
            require Cpanel::Notify;
            Cpanel::Notify::notification_class(
                'class'            => 'Logger::Notify',
                'application'      => 'Logger::Notify',
                'constructor_args' => [
                    'origin'       => $log_ref->{'service'},
                    'logger_call'  => $call,
                    'attach_files' => [ { name => 'cpanel-logger-log.txt', content => \$logfile } ],
                    'subject'      => $log_ref->{'subject'},
                ]
            );
        };

    }

    elsif ( eval { require Cpanel::LoadModule; Cpanel::LoadModule::load_perl_module('Cpanel::iContact'); 1; } ) {
        Cpanel::iContact::icontact(
            'application' => $log_ref->{'service'},
            'subject'     => $log_ref->{'subject'} ? $log_ref->{'subject'} : qq{Cpanel::Logger::$call called in $log_ref->{'service'}},
            'message'     => $logfile,
        );

    }
    else {
        CORE::warn( $log_ref->{'subject'} ? $log_ref->{'subject'} : qq{Cpanel::Logger::$call called in $log_ref->{'service'}} . ": $logfile" );
    }

    return;
}

*fatal   = *die;
*out     = *info;
*success = *info;
*throw   = *die;
*warning = *warn;

sub _is_subprocess_of_cpsrvd {
    require Cpanel::Server::Utils;
    goto \&Cpanel::Server::Utils::is_subprocess_of_cpsrvd;
}

sub _open_logfile {
    my ($self) = @_;
    my $usingstderr = 0;
    my $log_fh;

    $self->{'alternate_logfile'} ||= $STD_LOG_FILE;
    if ( $STD_LOG_FILE eq $self->{'alternate_logfile'} && _is_subprocess_of_cpsrvd() ) {
        $log_fh      = \*STDERR;
        $usingstderr = 1;
    }
    else {
        require Cpanel::FileUtils::Open;
        if ( !Cpanel::FileUtils::Open::sysopen_with_real_perms( $log_fh, $self->{'alternate_logfile'}, 'O_WRONLY|O_APPEND|O_CREAT', 0600 ) ) {
            ( $usingstderr, $log_fh ) = ( 1, \*STDERR );
        }

        select( ( select($log_fh), $| = 1 )[0] );    ## no critic qw(Variables::RequireLocalizedPunctuationVars InputOutput::ProhibitOneArgSelect) -- Cpanel::FHUtils::Autoflush would be expensive to load every time
    }

    $self->{'log_fh'}      = $log_fh;
    $self->{'usingstderr'} = $usingstderr;
    return 1;
}

sub _stdin_is_tty {
    local $@;
    return eval { -t STDIN };
}

sub _stdout_is_tty {
    local $@;
    return eval { -t STDOUT };
}

sub clear_singleton_stash {
    %singleton_stash = ();
    return;
}

1;


} # --- END Cpanel/Logger.pm


{ # --- BEGIN Cpanel/Locale/Utils.pm
package Cpanel::Locale::Utils;


use strict;
use warnings;

BEGIN {
    eval { require CDB_File; };
}

# use Cpanel::Locale::Utils::Paths ();


$Cpanel::Locale::Utils::i_am_the_compiler = 0;

my $logger;

sub _logger {
    require Cpanel::Logger;
    $logger ||= Cpanel::Logger->new();
}



sub get_readonly_tie {
    my ( $cdb_file, $cdb_hr ) = @_;
    if ( !$cdb_file ) {
        _logger()->warn('Undefined CDB file specified for readonly operation');
        return;
    }
    elsif ( !$INC{'CDB_File.pm'} || !exists $CDB_File::{'TIEHASH'} ) {
        _logger()->warn("Failed to load CDB_File.pm") if $^X ne '/usr/bin/perl';
        return;
    }

    my $tie_obj = tie %{$cdb_hr}, 'CDB_File', $cdb_file;

    if ( !$tie_obj && !-e $cdb_file ) {
        _logger()->warn("Missing CDB file $cdb_file specified for readonly operation");
        return;

    }

    eval { exists $cdb_hr->{'__VERSION'} };
    if ($@) {
        $tie_obj = undef;
        untie %$cdb_hr;
    }

    if ( !$tie_obj ) {
        _logger()->warn("CDB_File could not get read-only association to '$cdb_file': $!");
    }

    return $tie_obj;
}

sub create_cdb {
    my ( $cdb_file, $cdb_hr ) = @_;

    if ( !$cdb_file ) {
        _logger()->warn('Undefined CDB file specified for writable operation');
        return;
    }

    return CDB_File::create( %{$cdb_hr}, $cdb_file, "$cdb_file.$$" );
}

sub get_writable_tie {
    require Carp;
    Carp::confess("cdb files are not writable");
}

sub init_lexicon {
    my ( $langtag, $hr, $version_sr, $encoding_sr ) = @_;
    my $cdb_file;
    my $db_root = Cpanel::Locale::Utils::Paths::get_locale_database_root();

    for my $file ( $Cpanel::CPDATA{'RS'} ? ("themes/$Cpanel::CPDATA{RS}/$langtag.cdb") : (), "$langtag.cdb" ) {    # PPI NO PARSE - Only include Cpanel() when some other module uses it
        if ( -e "$db_root/$file" ) {
            $cdb_file = "$db_root/$file";
            last;
        }
    }

    if ( !$cdb_file ) {
        if ( -e Cpanel::Locale::Utils::Paths::get_locale_yaml_root() . "/$langtag.yaml" && !$Cpanel::Locale::Utils::i_am_the_compiler ) {
            _logger()->info(qq{Locale needs to be compiled by root (/usr/local/cpanel/bin/build_locale_databases --locale=$langtag)});
        }
        return;
    }


    my $cdb_tie = get_readonly_tie( $cdb_file, $hr );

    if ( exists $hr->{'__VERSION'} && ref $version_sr ) {
        ${$version_sr} = $hr->{'__VERSION'};
    }

    if ( ref $encoding_sr ) {

        ${$encoding_sr} ||= 'utf-8';
    }

    return $cdb_file;
}

sub init_package {
    my ($caller) = caller();

    my ($langtag) = reverse( split( /::/, $caller ) );

    no strict 'refs';
    no warnings 'once';

    ${ $caller . '::CDB_File_Path' } ||= init_lexicon( "$langtag", \%{ $caller . '::Lexicon' }, \${ $caller . '::VERSION' }, \${ $caller . '::Encoding' }, );

    return;
}

1;

} # --- END Cpanel/Locale/Utils.pm


{ # --- BEGIN Cpanel/DB/Utils.pm
package Cpanel::DB::Utils;


use strict;

sub username_to_dbowner {
    my ($username) = @_;

    $username =~ tr<_.><>d if defined $username;

    return $username;
}

1;

} # --- END Cpanel/DB/Utils.pm


{ # --- BEGIN Cpanel/Readlink.pm
package Cpanel::Readlink;


use strict;
use warnings;

# use Cpanel::Autodie   ();
# use Cpanel::Exception ();
use Cwd               ();

our $MAX_SYMLINK_DEPTH = 1024;

sub deep {
    my ( $link, $provide_trailing_slash ) = @_;

    die Cpanel::Exception::create( 'MissingParameter', 'Provide a link path.' ) if !length $link;

    if ( length($link) > 1 && substr( $link, -1, 1 ) eq '/' ) {
        $link = substr( $link, 0, length($link) - 1 );
        return deep( $link, 1 );
    }

    if ( !-l $link ) {
        return $provide_trailing_slash ? qq{$link/} : $link;
    }

    my %is_link;
    $is_link{$link} = 1;

    my $depth = 0;

    my $base = _get_base_for($link);

    if ( substr( $link, 0, 1 ) ne '/' ) {
        $base = Cwd::abs_path() . '/' . $base;
    }

    while ( ( $is_link{$link} ||= -l $link ) && ++$depth <= $MAX_SYMLINK_DEPTH ) {
        $link = Cpanel::Autodie::readlink($link);
        if ( substr( $link, 0, 1 ) ne '/' ) {
            $link = $base . '/' . $link;
        }

        $base = _get_base_for($link);
    }

    return $provide_trailing_slash ? qq{$link/} : $link;
}

sub _get_base_for {
    my $basename = shift;
    my @path     = split( '/', $basename );
    pop(@path);
    return join( '/', @path );
}

1;

} # --- END Cpanel/Readlink.pm


{ # --- BEGIN Cpanel/FileUtils/Write.pm
package Cpanel::FileUtils::Write;


use strict;
use warnings;


# use Cpanel::Fcntl::Constants ();
use Cpanel::Autodie ( 'rename', 'syswrite_sigguard', 'seek', 'print', 'truncate' );
# use Cpanel::Exception       ();
# use Cpanel::FileUtils::Open ();
# use Cpanel::Finally         ();
# use Cpanel::Debug           ();

our $Errno_EEXIST = 17;

our $MAX_TMPFILE_CREATE_ATTEMPTS = 1024;
my $DEFAULT_PERMS = 0600;
my $_WRONLY_CREAT_EXCL;


sub write_fh {    ##no critic qw(RequireArgUnpacking)
    my $fh = $_[0];

    Cpanel::Autodie::seek( $fh, 0, 0 );
    Cpanel::Autodie::print( $fh, $_[1] );
    Cpanel::Autodie::truncate( $fh, tell($fh) );

    return 1;
}


sub write {
    return _write_to_tmpfile( @_[ 0 .. 2 ], \&_write_finish );
}


sub overwrite {
    return _write_to_tmpfile( @_[ 0 .. 2 ], \&_overwrite_finish );
}

sub overwrite_no_exceptions {
    my $fh;

    local $@;
    eval {
        $fh = overwrite(@_);
        1;
    } or Cpanel::Debug::log_warn("overwrite exception: $@");

    return !!$fh;
}

sub _write_to_tmpfile {    ##no critic qw(RequireArgUnpacking)
    my ( $filename, $perms_or_hr, $finish_cr ) = ( $_[0], $_[2], $_[3] );

    if ( !defined $filename ) {
        exists $INC{'Carp.pm'} ? Carp::confess("write() called with undefined filename") : die("write() called with undefined filename");
    }

    if ( ref $filename ) {
        die "Use write_fh to write to a file handle. ($filename is a filehandle, right?)";
    }

    my ( $fh, $tmpfile_is_renamed );

    if ( -l $filename ) {
        require Cpanel::Readlink;
        $filename = Cpanel::Readlink::deep($filename);
    }


    my ( $callback_cr, $tmp_perms );

    if ( 'HASH' eq ref $perms_or_hr ) {
        $callback_cr = $perms_or_hr->{'before_installation'};
    }
    else {
        $tmp_perms = $perms_or_hr;
    }

    $tmp_perms //= $DEFAULT_PERMS;

    my ( $tmpfile, $attempts ) = ( '', 0 );

    while (1) {
        local $!;
        my $rand = rand(99999999);
        $rand = sprintf( '%x', substr( $rand, 2 ) );

        my $last_slash_idx = rindex( $filename, '/' );
        $tmpfile = $filename;
        substr( $tmpfile, 1 + $last_slash_idx, 0 ) = ".tmp.$rand.";

        last if Cpanel::FileUtils::Open::sysopen_with_real_perms(
            $fh,
            $tmpfile,
            ( $_WRONLY_CREAT_EXCL ||= ( $Cpanel::Fcntl::Constants::O_CREAT | $Cpanel::Fcntl::Constants::O_EXCL | $Cpanel::Fcntl::Constants::O_WRONLY ) ),
            $tmp_perms,
        );

        if ( $! != $Errno_EEXIST ) {
            die Cpanel::Exception::create( 'IO::FileCreateError', [ error => $!, path => $tmpfile, permissions => $tmp_perms ] );
        }

        ++$attempts;
        if ( $attempts >= $MAX_TMPFILE_CREATE_ATTEMPTS ) {
            die Cpanel::Exception::create_raw( 'IO::FileCreateError', "Too many ($MAX_TMPFILE_CREATE_ATTEMPTS) failed attempts to create a temp file as EUID $> and GID $) based on “$filename”! The last tried file was “$tmpfile”, and the last error was: $!" );
        }
    }

    my $finally = Cpanel::Finally->new(
        sub {
            if ( !$tmpfile_is_renamed ) {
                Cpanel::Autodie::unlink_if_exists($tmpfile);

            }
            return;
        }
    );

    if ( my $ref = ref $_[1] ) {
        if ( $ref eq 'SCALAR' ) {
            _write_fh( $fh, ${ $_[1] } );
        }
        else {
            die Cpanel::Exception::create( 'InvalidParameter', 'Invalid content type “[_1]”, expect a scalar.', [$ref] );
        }
    }
    else {
        _write_fh( $fh, $_[1] );
    }

    $callback_cr->($fh) if $callback_cr;

    $tmpfile_is_renamed = $finish_cr->( $tmpfile, $filename );

    if ( !$tmpfile_is_renamed ) {
        Cpanel::Autodie::unlink_if_exists($tmpfile);
    }

    $finally->skip();

    return $fh;
}

*_syswrite = *Cpanel::Autodie::syswrite_sigguard;

our $DEBUG_WRITE;

sub _write_fh {
    if ( length $_[1] ) {
        my $pos = 0;

        do {

            local $SIG{'XFSZ'} = 'IGNORE' if $pos;

            $pos += _syswrite( $_[0], $_[1], length( $_[1] ), $pos ) || do {

                die "Zero bytes written, non-error!";
            };
        } while $pos < length( $_[1] );
    }

    return;
}

sub _write_finish {

    Cpanel::Autodie::link(@_);
    return 0;
}

*_overwrite_finish = *Cpanel::Autodie::rename;

1;

} # --- END Cpanel/FileUtils/Write.pm


{ # --- BEGIN Cpanel/FileUtils/Write/JSON/Lazy.pm
package Cpanel::FileUtils::Write::JSON::Lazy;


use strict;
use warnings;


sub write_file {
    my ( $file_or_fh, $data, $perms ) = @_;

    if ( exists $INC{'Cpanel/JSON.pm'} && exists $INC{'JSON/XS.pm'} && ( my $Dump = 'Cpanel::JSON'->can('Dump') ) ) {    # PPI NO PARSE -- check earlier - must be quoted or it ends up in the stash
        require Cpanel::FileUtils::Write if !$INC{'Cpanel/FileUtils/Write.pm'};
        require Cpanel::FHUtils::Tiny    if !$INC{'Cpanel/FHUtils/Tiny.pm'};
        my $func = Cpanel::FHUtils::Tiny::is_a($file_or_fh) ? 'write_fh' : 'overwrite';

        if ( $func eq 'write_fh' ) {
            if ( !defined $perms ) {
                $perms = 0600;
            }

            chmod( $perms, $file_or_fh ) or die "Failed to set permissions on the file handle passed to Cpanel::FileUtils::Write::JSON::Lazy::write_file because of an error: $!";
        }

        return Cpanel::FileUtils::Write->can($func)->(
            $file_or_fh,
            $Dump->($data),
            $perms
        );
    }
    return 0;
}


sub write_file_pretty {
    my ( $file_or_fh, $data, $perms ) = @_;

    if ( exists $INC{'Cpanel/JSON.pm'} && exists $INC{'JSON/XS.pm'} && ( my $Dump = 'Cpanel::JSON'->can('pretty_dump') ) ) {    # PPI NO PARSE -- check earlier - must be quoted or it ends up in the stash
        require Cpanel::FileUtils::Write if !$INC{'Cpanel/FileUtils/Write.pm'};
        require Cpanel::FHUtils::Tiny    if !$INC{'Cpanel/FHUtils/Tiny.pm'};
        my $func = Cpanel::FHUtils::Tiny::is_a($file_or_fh) ? 'write_fh' : 'overwrite';

        if ( $func eq 'write_fh' ) {
            if ( !defined $perms ) {
                $perms = 0600;
            }

            chmod( $perms, $file_or_fh ) or die "Failed to set permissions on the file handle passed to Cpanel::FileUtils::Write::JSON::Lazy::write_file because of an error: $!";
        }

        return Cpanel::FileUtils::Write->can($func)->(
            $file_or_fh,
            $Dump->($data),
            $perms
        );
    }
    return 0;
}

1;

} # --- END Cpanel/FileUtils/Write/JSON/Lazy.pm


{ # --- BEGIN Cpanel/JSON/Unicode.pm
package Cpanel::JSON::Unicode;


use strict;
use warnings;



use constant {

    _LEAD_SURROGATE_MIN => 0xd800,
    _TAIL_SURROGATE_MIN => 0xdc00,

    _SURROGATE_MASK => 0xfc00,

    _BACKSLASH_ORD    => 0x5c,
    _DOUBLE_QUOTE_ORD => 0x22,
};

my $UNICODE_ESCAPE_REGEXP = qr/

    (?<!\x5c)

    (

        (?:\x5c\x5c)*

        \x5c u ([0-9a-fA-F]{4})
    )
/x;



sub replace_unicode_escapes_with_utf8 {
    my ($json_sr) = @_;

    my $lead_surrogate;

    my $ret = $$json_sr =~ s<$UNICODE_ESCAPE_REGEXP><
        _replacement(\$lead_surrogate, $json_sr, $+[0], @{^CAPTURE})
    >ge;

    if ($lead_surrogate) {
        die sprintf "Incomplete surrogate pair (0x%04x)", $lead_surrogate;
    }

    return $ret;
}

sub _replacement {
    my ( $lead_surrogate_sr, $json_sr, $match_end, @captures ) = @_;

    my $num = hex $captures[1];

    if ( ( $num & _SURROGATE_MASK ) == _TAIL_SURROGATE_MIN ) {
        if ($$lead_surrogate_sr) {
            my $utf8 = _decode_surrogates( $$lead_surrogate_sr, $num );
            $$lead_surrogate_sr = undef;
            return $utf8;
        }

        die sprintf "Unpaired trailing surrogate (0x%04x)", $num;
    }
    elsif ( ( $num & _SURROGATE_MASK ) == _LEAD_SURROGATE_MIN ) {
        my $next2 = substr( $$json_sr, $match_end, 2 );
        if ( !$next2 || $next2 ne '\\u' ) {
            die sprintf "Unpaired leading surrogate (0x%04x)", $num;
        }

        $$lead_surrogate_sr = $num;
        return q<>;
    }
    elsif ( $num < 0x20 || $num == _BACKSLASH_ORD || $num == _DOUBLE_QUOTE_ORD ) {
        return $captures[0];
    }

    my $utf8 = chr $num;
    utf8::encode($utf8);
    return $utf8;
}

sub _decode_surrogates {
    my ( $lead, $tail ) = @_;

    my $uni = 0x10000 + ( ( $lead - 0xd800 ) << 10 ) + ( $tail - 0xdc00 );

    my $un = chr $uni;
    utf8::encode($un);

    return $un;
}

1;

} # --- END Cpanel/JSON/Unicode.pm


{ # --- BEGIN Cpanel/LoadFile/ReadFast.pm
package Cpanel::LoadFile::ReadFast;


use strict;
use warnings;


use constant READ_CHUNK => 1 << 18;    # 262144

use constant _EINTR => 4;


sub read_fast {
    $_[1] //= q<>;

    return ( @_ > 3 ? sysread( $_[0], $_[1], $_[2], $_[3] ) : sysread( $_[0], $_[1], $_[2] ) ) // do {
        goto \&read_fast if $! == _EINTR;
        die "Failed to read data: $!";
    };
}


my $_ret;

sub read_all_fast {
    $_[1] //= q<>;

    $_ret = 1;
    while ($_ret) {
        $_ret = sysread( $_[0], $_[1], READ_CHUNK, length $_[1] ) // do {
            redo if $! == _EINTR;
            die "Failed to read data: $!";
        }
    }
    return;
}

1;

} # --- END Cpanel/LoadFile/ReadFast.pm


{ # --- BEGIN Cpanel/Encoder/ASCII.pm
package Cpanel::Encoder::ASCII;


use strict;
use warnings;

sub to_hex {
    my ($readable) = @_;

    $readable =~ s<\\><\\\\>g;
    $readable =~ s<([\0-\x{1f}\x{7f}-\x{ff}])><sprintf '\x{%02x}', ord $1>eg;

    return $readable;
}

1;

} # --- END Cpanel/Encoder/ASCII.pm


{ # --- BEGIN Cpanel/UTF8/Strict.pm
package Cpanel::UTF8::Strict;


use strict;
use warnings;


sub decode {

    utf8::decode( $_[0] ) or do {
        local ( $@, $! );
        require Cpanel::Encoder::ASCII;
        die sprintf "Invalid UTF-8 in string: “%s”", Cpanel::Encoder::ASCII::to_hex( $_[0] );
    };

    return $_[0];
}

1;

} # --- END Cpanel/UTF8/Strict.pm


{ # --- BEGIN Cpanel/JSON.pm
package Cpanel::JSON;


use strict;

# use Cpanel::Fcntl::Constants   ();
# use Cpanel::FHUtils::Tiny      ();
# use Cpanel::JSON::Unicode      ();
# use Cpanel::LoadFile::ReadFast ();
use JSON::XS                   ();
# use Cpanel::UTF8::Strict       ();

our $NO_DECODE_UTF8 = 0;
our $DECODE_UTF8    = 1;

our $LOAD_STRICT  = 0;
our $LOAD_RELAXED = 1;

our $MAX_LOAD_LENGTH_UNLIMITED = 0;
our $MAX_LOAD_LENGTH           = 65535;

our $MAX_PRIV_LOAD_LENGTH = 4194304;    # four megs

our $XS_ConvertBlessed_obj;
our $XS_RelaxedConvertBlessed_obj;
our $XS_NoSetUTF8RelaxedConvertBlessed_obj;
our $XS_NoSetUTF8ConvertBlessed_obj;

our $VERSION = '2.5';

my $copied_boolean = 0;

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

    if ( Cpanel::FHUtils::Tiny::is_a($file) ) {
        print {$file} Dump($data) || return 0;
    }
    else {
        if ( open( my $fh, '>', $file ) ) {
            print {$fh} Dump($data);
            close($fh);
        }
        else {
            return 0;
        }
    }
    return 1;
}

sub copy_boolean {

    if ( !$copied_boolean ) {
        *Types::Serialiser::Boolean:: = *JSON::PP::Boolean::;
        $copied_boolean               = 1;
    }
    return;
}

sub _create_new_json_object {
    copy_boolean() if !$copied_boolean;
    return JSON::XS->new()->shrink(1)->allow_nonref(1)->convert_blessed(1);
}

sub true {
    copy_boolean() if !$copied_boolean;
    my $x = 1;
    return bless \$x, 'Types::Serialiser::Boolean';
}

sub false {
    copy_boolean() if !$copied_boolean;
    my $x = 0;
    return bless \$x, 'Types::Serialiser::Boolean';
}

sub pretty_dump {
    return _create_new_json_object()->pretty(1)->encode( $_[0] );
}

my $XS_Canonical_obj;

sub canonical_dump {
    return ( $XS_Canonical_obj ||= _create_new_json_object()->canonical(1) )->encode( $_[0] );
}

sub pretty_canonical_dump {
    return _create_new_json_object()->canonical(1)->indent->space_before->space_after->encode( $_[0] );
}

sub Dump {
    return ( $XS_ConvertBlessed_obj ||= _create_new_json_object() )->encode( $_[0] );
}

sub Load {
    local $@;

    _replace_unicode_escapes_if_needed( \$_[0] );

    return eval { ( $XS_ConvertBlessed_obj ||= _create_new_json_object() )->decode( $_[0] ); } // ( ( $@ && _throw_json_error( $@, $_[1], \$_[0] ) ) || undef );
}

sub LoadRelaxed {
    local $@;

    _replace_unicode_escapes_if_needed( \$_[0] );

    return eval { ( $XS_RelaxedConvertBlessed_obj ||= _create_new_json_object()->relaxed(1) )->decode( $_[0] ); } // ( ( $@ && _throw_json_error( $@, $_[1], \$_[0] ) ) || undef );
}

sub _throw_json_error {
    my ( $exception, $path, $dataref ) = @_;

    local $@;
    require Cpanel::Exception;
    die $exception if $@;
    die 'Cpanel::Exception'->can('create')->( 'JSONParseError', { 'error' => $exception, 'path' => $path, 'dataref' => $dataref } );
}

sub LoadNoSetUTF8 {
    local $@;

    _replace_unicode_escapes_if_needed( \$_[0] );

    return eval { ( $XS_NoSetUTF8ConvertBlessed_obj ||= _create_new_no_set_utf8_json_object() )->decode( $_[0] ); } // ( ( $@ && _throw_json_error( $@, $_[1], \$_[0] ) ) || undef );
}

sub LoadNoSetUTF8Relaxed {
    local $@;

    _replace_unicode_escapes_if_needed( \$_[0] );

    return eval { ( $XS_NoSetUTF8RelaxedConvertBlessed_obj ||= _create_new_no_set_utf8_json_object()->relaxed(1) )->decode( $_[0] ); } // ( ( $@ && _throw_json_error( $@, $_[1], \$_[0] ) ) || undef );
}

sub _create_new_no_set_utf8_json_object {
    my $obj = _create_new_json_object();
    if ( $obj->can('no_set_utf8') ) {
        $obj->no_set_utf8(1);
    }
    else {
        warn "JSON::XS is missing the no_set_utf8 flag";
    }
    return $obj;
}

sub _replace_unicode_escapes_if_needed {
    my $json_r = shift;

    if ( -1 != index( $$json_r, '\\u' ) ) {
        Cpanel::JSON::Unicode::replace_unicode_escapes_with_utf8($json_r);
    }

    return;
}


sub SafeLoadFile {    # only allow a small bit of data to be loaded
    return _LoadFile( $_[0], $MAX_LOAD_LENGTH, $_[2] || $NO_DECODE_UTF8, $_[1], $LOAD_STRICT );
}

sub LoadFile {
    return _LoadFile( $_[0], $MAX_LOAD_LENGTH_UNLIMITED, $_[2] || $NO_DECODE_UTF8, $_[1], $LOAD_STRICT );
}

sub LoadFileRelaxed {
    return _LoadFile( $_[0], $MAX_LOAD_LENGTH_UNLIMITED, $_[2] || $NO_DECODE_UTF8, $_[1], $LOAD_RELAXED );
}

sub LoadFileNoSetUTF8 {
    return _LoadFile( $_[0], $_[1] || $MAX_LOAD_LENGTH_UNLIMITED, $DECODE_UTF8, $_[2], $LOAD_STRICT );
}

sub _LoadFile {
    my ( $file, $max, $decode_utf8, $path, $relaxed ) = @_;

    my $data;
    if ( Cpanel::FHUtils::Tiny::is_a($file) ) {
        if ($max) {
            my $togo = $max;
            $data = '';
            my $bytes_read;
            while ( $bytes_read = read( $file, $data, $togo, length $data ) && length $data < $max ) {
                $togo -= $bytes_read;
            }
        }
        else {
            Cpanel::LoadFile::ReadFast::read_all_fast( $file, $data );
        }
    }
    else {
        local $!;
        open( my $fh, '<:stdio', $file ) or do {
            my $err = $!;

            require Cpanel::Carp;
            die Cpanel::Carp::safe_longmess("Cannot open “$file”: $err");
        };
        Cpanel::LoadFile::ReadFast::read_all_fast( $fh, $data );
        if ( !length $data ) {
            require Cpanel::Carp;
            die Cpanel::Carp::safe_longmess("“$file” is empty.");
        }
        close $fh or warn "close($file) failed: $!";
    }

    if ( $decode_utf8 && $decode_utf8 == $DECODE_UTF8 ) {

        Cpanel::UTF8::Strict::decode($data);

        return $relaxed ? LoadNoSetUTF8Relaxed( $data, $path || $file ) : LoadNoSetUTF8( $data, $path || $file );
    }

    return $relaxed ? LoadRelaxed( $data, $path || $file ) : Load( $data, $path || $file );
}

sub SafeDump {
    my $raw_json = ( $XS_ConvertBlessed_obj ||= _create_new_json_object() )->encode( $_[0] );
    $raw_json =~ s{\/}{\\/}g if $raw_json =~ tr{/}{};
    return $raw_json;
}

sub _fh_looks_like_json {
    my ($fh) = @_;

    my $bytes_read = 0;

    my $buffer = q{};

    local $!;

    while ( $buffer !~ tr{ \t\r\n\f}{}c && !eof $fh ) {
        $bytes_read += ( read( $fh, $buffer, 1, length $buffer ) // die "read() failed: $!" );
    }

    return (
        _string_looks_like_json($buffer),
        \$buffer,
    );
}

sub _string_looks_like_json {    ##no critic qw(RequireArgUnpacking)
    return $_[0] =~ m/\A\s*[\[\{"0-9]/ ? 1 : 0;
}

sub looks_like_json {    ##no critic qw(RequireArgUnpacking)
    if ( Cpanel::FHUtils::Tiny::is_a( $_[0] ) ) {
        my $fh = $_[0];

        my ( $looks_like_json, $fragment_ref ) = _fh_looks_like_json($fh);
        my $bytes_read = length $$fragment_ref;

        if ($bytes_read) {
            seek( $fh, -$bytes_read, $Cpanel::Fcntl::Constants::SEEK_CUR ) or die "seek() failed: $!";
        }

        return $looks_like_json;
    }

    return _string_looks_like_json( $_[0] );
}

1;

} # --- END Cpanel/JSON.pm


{ # --- BEGIN Cpanel/AdminBin/Serializer.pm
package Cpanel::AdminBin::Serializer;


use strict;
use warnings;



# use Cpanel::JSON ();


our $VERSION = '2.4';

our $MAX_LOAD_LENGTH;
our $MAX_PRIV_LOAD_LENGTH;

BEGIN {
    *MAX_LOAD_LENGTH      = \$Cpanel::JSON::MAX_LOAD_LENGTH;
    *MAX_PRIV_LOAD_LENGTH = \$Cpanel::JSON::MAX_PRIV_LOAD_LENGTH;
    *DumpFile             = *Cpanel::JSON::DumpFile;
}


BEGIN {
    *Dump = *Cpanel::JSON::Dump;

    *SafeDump = *Cpanel::JSON::SafeDump;

    *LoadFile = *Cpanel::JSON::LoadFileNoSetUTF8;

    *Load = *Cpanel::JSON::Load;

    *looks_like_serialized_data = *Cpanel::JSON::looks_like_json;
}



sub SafeLoadFile {
    return Cpanel::JSON::_LoadFile( $_[0], $Cpanel::JSON::MAX_LOAD_LENGTH, $Cpanel::JSON::DECODE_UTF8, $_[1], $Cpanel::JSON::LOAD_STRICT );
}



sub SafeLoad {
    utf8::decode( $_[0] );
    return Cpanel::JSON::LoadNoSetUTF8(@_);
}



sub clone {
    return Cpanel::JSON::LoadNoSetUTF8( Cpanel::JSON::Dump( $_[0] ) );
}

1;

} # --- END Cpanel/AdminBin/Serializer.pm


{ # --- BEGIN Cpanel/AdminBin/Serializer/FailOK.pm
package Cpanel::AdminBin::Serializer::FailOK;


use strict;
use warnings;

sub LoadModule {
    local $@;

    return 1 if $INC{'Cpanel/AdminBin/Serializer.pm'};

    my $load_ok = eval {
        local $SIG{'__DIE__'};     # Suppress spewage as we may be reading an invalid cache
        local $SIG{'__WARN__'};    # and since failure is ok to throw it away
        require Cpanel::AdminBin::Serializer;
        1;
    };

    if ( !$load_ok && !$ENV{'CPANEL_BASE_INSTALL'} && index( $^X, '/usr/local/cpanel' ) == 0 ) {
        warn $@;
    }

    return $load_ok ? 1 : 0;
}

sub LoadFile {
    my ( $file_or_fh, $path ) = @_;

    return undef if !$INC{'Cpanel/AdminBin/Serializer.pm'};

    return eval {
        local $SIG{'__DIE__'};     # Suppress spewage as we may be reading an invalid cache
        local $SIG{'__WARN__'};    # and since failure is ok to throw it away
        Cpanel::AdminBin::Serializer::LoadFile( $file_or_fh, undef, $path );
    };
}
1;

} # --- END Cpanel/AdminBin/Serializer/FailOK.pm


{ # --- BEGIN Cpanel/Config/Constants.pm
package Cpanel::Config::Constants;


use strict;
use warnings;

our $DEFAULT_CPANEL_THEME = 'jupiter';

our $DEFAULT_CPANEL_MAILONLY_THEME = 'jupiter';

our $DEFAULT_WEBMAIL_THEME = 'jupiter';

our $DEFAULT_WEBMAIL_MAILONLY_THEME = 'jupiter';

our @DORMANT_SERVICES_LIST = qw(cpanalyticsd cpdavd cphulkd cpsrvd dnsadmin spamd);

our $MAX_HOMEDIR_STREAM_TIME = ( 86400 * 2 );

1;

} # --- END Cpanel/Config/Constants.pm


{ # --- BEGIN Cpanel/Imports.pm
package Cpanel::Imports;


use strict;

$Cpanel::Imports::VERSION = '0.02';

sub import {
    my $caller = caller;
    no strict 'refs';    ## no critic(ProhibitNoStrict)

    *{ $caller . '::logger' } = \&__logger;
    *{ $caller . '::locale' } = \&__locale;

    return;
}

my ( $logger, $locale );

sub _reset_lazy_facade {    # usually for testing
    $logger = undef;
    $locale = undef;
    return;
}

sub __logger {
    require Cpanel::Logger if !$INC{'Cpanel/Logger.pm'};
    if ( !$logger ) {    # return $var ||= XYZ->new; works but, we keep it super vanilla to make it more likley to perlcc OK
        $logger = Cpanel::Logger->new;
    }
    return $logger;
}

sub __locale {
    require Cpanel::Locale if !$INC{'Cpanel/Locale.pm'};
    if ( !$locale ) {    # return $var ||= XYZ->new; works but, we keep it super vanilla to make it more likley to perlcc OK
        $locale = Cpanel::Locale->get_handle;
    }
    return $locale;
}

1;


} # --- END Cpanel/Imports.pm


{ # --- BEGIN Cpanel/SSL/KeyTypeLabel.pm
package Cpanel::SSL::KeyTypeLabel;


use cPstrict;



use Cpanel::Imports;



my %_ECDSA_DETAIL = (
    prime256v1 => 'P-256 (prime256v1)',
    secp384r1  => 'P-384 (secp384r1)',
);

sub to_label ($the_type) {
    my ( $type, $detail ) = split m<->, $the_type;

    die _invalid_type_msg($the_type) if !defined $detail;

    $type =~ tr<a-z><A-Z>;

    if ( $type eq 'RSA' ) {
        $detail = locale()->maketext( '[numf,_1]-bit', $detail );
    }
    elsif ( $type eq 'ECDSA' ) {
        $detail = $_ECDSA_DETAIL{$detail} or die _invalid_type_msg($the_type);
    }
    else {
        die "need update? ($the_type)";
    }

    return "$type, $detail";
}

sub _invalid_type_msg ($the_type) {
    return "Invalid key type: “$the_type”";
}

1;

} # --- END Cpanel/SSL/KeyTypeLabel.pm


{ # --- BEGIN Cpanel/SSL/DefaultKey/Constants.pm
package Cpanel::SSL::DefaultKey::Constants;


use cPstrict;



# use Cpanel::SSL::KeyTypeLabel ();



use constant OPTIONS => (
    'rsa-2048',
    'ecdsa-secp384r1',
    'ecdsa-prime256v1',
    'rsa-4096',
);


sub OPTIONS_AND_LABELS() {
    local ( $@, $! );
    require Cpanel::Locale;

    my $lh = Cpanel::Locale->get_handle();

    return map { ( $_ => Cpanel::SSL::KeyTypeLabel::to_label($_) ) } OPTIONS;
}


sub KEY_DESCRIPTIONS() {
    require Cpanel::Locale;

    my $lh = Cpanel::Locale->get_handle();

    return {
        "rsa-2048"         => $lh->maketext("[asis,RSA] is more compatible with older clients (for example, browsers older than [asis,Internet Explorer] 11) than [asis,ECDSA]. New installations of [asis,cPanel amp() WHM] ship with this setting."),
        "rsa-4096"         => $lh->maketext( "[asis,RSA] is more compatible with older clients (for example, browsers older than [asis,Internet Explorer] 11) than [asis,ECDSA]. This is more secure than [_1]-bit, but will perform slower than [_1]-bit keys.", 'RSA, 2,048' ),
        "ecdsa-prime256v1" => $lh->maketext("[asis,ECDSA] allows websites to support [asis,Internet Explorer] 11 and retain compliance with [output,acronym,PCI,Payment Card Industry] standards."),
        "ecdsa-secp384r1"  => $lh->maketext("[asis,ECDSA] allows websites to support [asis,Internet Explorer] 11 and retain compliance with [output,acronym,PCI,Payment Card Industry] standards. [asis,secp384r1] is more secure than [asis,prime256v1], but may perform slower."),
    };
}

use constant USER_SYSTEM => 'system';

1;

} # --- END Cpanel/SSL/DefaultKey/Constants.pm


{ # --- BEGIN Cpanel/Config/CpUser/Defaults.pm
package Cpanel::Config::CpUser::Defaults;


use strict;
use warnings;



# use Cpanel::SSL::DefaultKey::Constants ();


our @DEFAULTS_KV = (
    'BWLIMIT'              => 'unlimited',
    'CHILD_WORKLOADS'      => q<>,
    'DEADDOMAINS'          => undef,
    'DEMO'                 => 0,
    'DOMAIN'               => '',
    'DOMAINS'              => undef,
    'FEATURELIST'          => 'default',
    'HASCGI'               => 0,
    'HASDKIM'              => 0,
    'HASSPF'               => 0,
    'IP'                   => '127.0.0.1',
    'MAILBOX_FORMAT'       => 'maildir',                                         #keep in sync with cpconf
    'MAX_EMAILACCT_QUOTA'  => 'unlimited',
    'MAXADDON'             => 0,
    'MAXFTP'               => 'unlimited',
    'MAXLST'               => 'unlimited',
    'MAXPARK'              => 0,
    'MAXPOP'               => 'unlimited',
    'MAXSQL'               => 'unlimited',
    'MAXSUB'               => 'unlimited',
    'OWNER'                => 'root',
    'PLAN'                 => 'undefined',
    'RS'                   => '',
    'STARTDATE'            => '0000000000',
    'MAXPASSENGERAPPS'     => 4,
    'SSL_DEFAULT_KEY_TYPE' => Cpanel::SSL::DefaultKey::Constants::USER_SYSTEM,
);

1;

} # --- END Cpanel/Config/CpUser/Defaults.pm


{ # --- BEGIN Cpanel/Hash/JSONable.pm
package Cpanel::Hash::JSONable;


use cPstrict;




sub TO_JSON ($self) {
    return {%$self};
}

1;

} # --- END Cpanel/Hash/JSONable.pm


{ # --- BEGIN Cpanel/Config/CpUser/Object.pm
package Cpanel::Config::CpUser::Object;


use cPstrict;



# use Cpanel::Hash::JSONable();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Hash::JSONable); }

use Class::XSAccessor (
    getters => {
        username => 'USER',
    },
);



sub adopt ( $class, $ref ) {
    return bless $ref, $class;
}



sub domains_ar ($self) {
    return [ $self->{'DOMAIN'}, @{ $self->{'DOMAINS'} } ];
}



sub contact_emails_ar ($self) {
    return [ grep { length } @{$self}{ 'CONTACTEMAIL', 'CONTACTEMAIL2' } ];
}



sub child_workloads ($self) {

    if (wantarray) {
        return if !$self->{'CHILD_WORKLOADS'};
        return split( m<,>, $self->{'CHILD_WORKLOADS'}, -1 );
    }

    return 0 if !$self->{'CHILD_WORKLOADS'};

    return 1 + ( $self->{'CHILD_WORKLOADS'} =~ tr<,><> );
}

1;

} # --- END Cpanel/Config/CpUser/Object.pm


{ # --- BEGIN Cpanel/ConfigFiles.pm
package Cpanel::ConfigFiles;


use strict;


our $VERSION = '1.4';

our $cpanel_users       = '/var/cpanel/users';
our $cpanel_users_cache = '/var/cpanel/users.cache';

our $backup_config_touchfile     = '/var/cpanel/config/backups/metadata_disabled';
our $backup_config_touchfile_dir = '/var/cpanel/config/backups/';
our $backup_config               = '/var/cpanel/backups/config';

our $cpanel_config_file          = '/var/cpanel/cpanel.config';
our $cpanel_config_cache_file    = '/var/cpanel/cpanel.config.cache';
our $cpanel_config_defaults_file = '/usr/local/cpanel/etc/cpanel.config';
our $features_cache_dir          = "/var/cpanel/features.cache";

our $BASE_INSTALL_IN_PROGRESS_FILE = '/root/installer.lock';

our $CPSRVD_CHECK_CPLISC_FILE = q{/var/cpanel/cpsrvd_check_license};

our $ROOT_CPANEL_HOMEDIR = '/var/cpanel/userhomes/cpanel';

our $RESELLERS_FILE             = '/var/cpanel/resellers';
our $RESELLERS_NAMESERVERS_FILE = '/var/cpanel/resellers-nameservers';
our $ACCOUNTING_LOG_FILE        = '/var/cpanel/accounting.log';
our $FEATURES_DIR               = '/var/cpanel/features';
our $BANDWIDTH_LIMIT_DIR        = '/var/cpanel/bwlimited';
our $CUSTOM_PERL_MODULES_DIR    = '/var/cpanel/perl';
our $PACKAGES_DIR;    #defined below

our $DEDICATED_IPS_FILE       = '/etc/domainips';
our $DELEGATED_IPS_DIR        = '/var/cpanel/dips';
our $MAIN_IPS_DIR             = '/var/cpanel/mainips';
our $RESERVED_IPS_FILE        = '/etc/reservedips';
our $RESERVED_IP_REASONS_FILE = '/etc/reservedipreasons';
our $IP_ADDRESS_POOL_FILE     = '/etc/ipaddrpool';
our $ACL_LISTS_DIR            = '/var/cpanel/acllists';

our $OUTGOING_MAIL_SUSPENDED_USERS_FILE    = '/etc/outgoing_mail_suspended_users';
our $OUTGOING_MAIL_HOLD_USERS_FILE         = '/etc/outgoing_mail_hold_users';
our $TRUEUSEROWNERS_FILE                   = '/etc/trueuserowners';
our $TRUEUSERDOMAINS_FILE                  = '/etc/trueuserdomains';
our $USERDOMAINS_FILE                      = '/etc/userdomains';
our $DBOWNERS_FILE                         = '/etc/dbowners';
our $DOMAINUSERS_FILE                      = '/etc/domainusers';
our $LOCALDOMAINS_FILE                     = '/etc/localdomains';
our $REMOTEDOMAINS_FILE                    = '/etc/remotedomains';
our $SECONDARYMX_FILE                      = '/etc/secondarymx';
our $MANUALMX_FILE                         = '/etc/manualmx';
our $USERBWLIMITS_FILE                     = '/etc/userbwlimits';
our $MAILIPS_FILE                          = '/etc/mailips';
our $MAILHELO_FILE                         = '/etc/mailhelo';
our $NEIGHBOR_NETBLOCKS_FILE               = '/etc/neighbor_netblocks';
our $CPANEL_MAIL_NETBLOCKS_FILE            = '/etc/cpanel_mail_netblocks';
our $GREYLIST_TRUSTED_NETBLOCKS_FILE       = '/etc/greylist_trusted_netblocks';
our $GREYLIST_COMMON_MAIL_PROVIDERS_FILE   = '/etc/greylist_common_mail_providers';
our $RECENT_RECIPIENT_MAIL_SERVER_IPS_FILE = '/etc/recent_recipient_mail_server_ips';
our $DEMOUSERS_FILE                        = '/etc/demousers';

our $APACHE_CONFIG_DIR          = '/var/cpanel/conf/apache';
our $APACHE_PRIMARY_VHOSTS_FILE = '/var/cpanel/conf/apache/primary_virtual_hosts.conf';

our $MYSQL_CNF = '/etc/my.cnf';

our $SERVICEAUTH_DIR      = '/var/cpanel/serviceauth';
our $DORMANT_SERVICES_DIR = '/var/cpanel/dormant_services';

our $DOMAIN_KEYS_ROOT = '/var/cpanel/domain_keys';

our $USER_NOTIFICATIONS_DIR = '/var/cpanel/user_notifications';

our $DATABASES_INFO_DIR = '/var/cpanel/databases';

our $CPANEL_ROOT  = '/usr/local/cpanel';
our $MAILMAN_ROOT = "$CPANEL_ROOT/3rdparty/mailman";

our $FPM_CONFIG_ROOT = "/var/cpanel/php-fpm.d";
our $FPM_ROOT        = "/var/cpanel/php-fpm";

our $MAILMAN_LISTS_DIR = "$MAILMAN_ROOT/lists";

our $MAILMAN_USER = 'mailman';

our $FTP_PASSWD_DIR     = '/etc/proftpd';
our $FTP_SYMLINKS_DIR   = '/etc/pure-ftpd';
our $VALIASES_DIR       = '/etc/valiases';
our $VDOMAINALIASES_DIR = '/etc/vdomainaliases';
our $VFILTERS_DIR       = '/etc/vfilters';

our $JAILSHELL_PATH = '/usr/local/cpanel/bin/jailshell';

our @COMMONDOMAINS_FILES = qw{/usr/local/cpanel/etc/commondomains /var/cpanel/commondomains};

our $BANDWIDTH_DIRECTORY             = '/var/cpanel/bandwidth';
our $BANDWIDTH_CACHE_DIRECTORY       = '/var/cpanel/bandwidth.cache';
our $BANDWIDTH_USAGE_CACHE_DIRECTORY = '/var/cpanel/bwusagecache';

our $TEMPLATE_COMPILE_DIR = '/var/cpanel/template_compiles';

our $DOVECOT_SNI_CONF = '/etc/dovecot/sni.conf';

our $DOVECOT_SSL_CONF = '/etc/dovecot/ssl.conf';
our $DOVECOT_SSL_KEY  = '/etc/dovecot/ssl/dovecot.key';
our $DOVECOT_SSL_CRT  = '/etc/dovecot/ssl/dovecot.crt';

our $GOOGLE_AUTH_TEMPFILE_PREFIX = '/var/cpanel/backups/google_oauth_tempfile_';

our $APACHE_LOGFILE_CLEANUP_QUEUE = '/var/cpanel/apache_logfile_cleanup.json';

our $SKIP_REPO_SETUP_FLAG = '/var/cpanel/skip-repo-setup';

our $ACCOUNT_ENHANCEMENTS_DIR          = '/var/cpanel/account_enhancements';
our $ACCOUNT_ENHANCEMENTS_CONFIG_DIR   = $Cpanel::ConfigFiles::ACCOUNT_ENHANCEMENTS_DIR . '/config';
our $ACCOUNT_ENHANCEMENTS_INSTALL_FILE = $Cpanel::ConfigFiles::ACCOUNT_ENHANCEMENTS_CONFIG_DIR . '/installed.json';

BEGIN {
    $PACKAGES_DIR = '/var/cpanel/packages';
}


1;

} # --- END Cpanel/ConfigFiles.pm


{ # --- BEGIN Cpanel/SV.pm
package Cpanel::SV;


use strict;
use warnings;


sub untaint {
    return $_[0] unless ${^TAINT};
    require    # Cpanel::Static OK - we should not untaint variables as part of updatenow.static
      Taint::Util;
    Taint::Util::untaint( $_[0] );
    return $_[0];
}

1;

} # --- END Cpanel/SV.pm


{ # --- BEGIN Cpanel/Struct/Common/Time.pm
package Cpanel::Struct::Common::Time;


use strict;
use warnings;


use constant PACK_TEMPLATE => 'L!L!';

my %CLASS_PRECISION;



sub float_to_binary {
    return pack(
        PACK_TEMPLATE(),

        int( $_[1] ),

        int( 0.5 + ( $_[0]->_PRECISION() * $_[1] ) - ( $_[0]->_PRECISION() * int( $_[1] ) ) ),
    );
}



sub binary_to_float {
    return $_[0]->_binary_to_float( PACK_TEMPLATE(), $_[1] )->[0];
}



sub binaries_to_floats_at {
    return $_[0]->_binary_to_float(
        "\@$_[3] " . ( PACK_TEMPLATE() x $_[2] ),
        $_[1],
    );
}


my ( $i, $precision, @sec_psec_pairs );

sub _binary_to_float {    ## no critic qw(RequireArgUnpacking)
    @sec_psec_pairs = unpack( $_[1], $_[2] );

    $i = 0;

    my @floats;

    $precision = $CLASS_PRECISION{ $_[0] } ||= $_[0]->_PRECISION();

    while ( $i < @sec_psec_pairs ) {


        push @floats, 0 + ( q<> . ( $sec_psec_pairs[$i] + ( $sec_psec_pairs[ $i + 1 ] / $precision ) ) );
        $i += 2;
    }

    return \@floats;
}

1;

} # --- END Cpanel/Struct/Common/Time.pm


{ # --- BEGIN Cpanel/Struct/timespec.pm
package Cpanel::Struct::timespec;


use strict;
use warnings;


# use Cpanel::Struct::Common::Time();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Struct::Common::Time); }

use constant {
    _PRECISION => 1_000_000_000,    # nanoseconds
};

1;

} # --- END Cpanel/Struct/timespec.pm


{ # --- BEGIN Cpanel/NanoStat.pm
package Cpanel::NanoStat;


use strict;
use warnings;


# use Cpanel::Struct::timespec ();

use constant {
    _NR_stat  => 4,
    _NR_fstat => 5,
    _NR_lstat => 6,
};

use constant _PACK_TEMPLATE => q<
    Q       # st_dev
    Q       # st_ino

    @24 L   # st_mode
    @16 Q   # st_nlink

    @28
    L       # st_uid
    L       # st_gid

    x![Q]
    Q       # st_rdev
    Q       # st_size
    Q       # st_blksize
    Q       # st_blocks
>;

my $pre_times_pack_len = length pack _PACK_TEMPLATE();

my $buf = ( "\0" x 144 );



sub stat {
    return _syscall( _NR_stat(), $_[0] );
}


sub lstat {
    return _syscall( _NR_lstat(), $_[0] );
}


sub fstat {
    return _syscall( _NR_fstat(), 0 + ( ref( $_[0] ) ? fileno( $_[0] ) : $_[0] ) );
}


sub _syscall {    ## no critic qw(RequireArgUnpacking)
    my $arg_dupe = $_[1];
    return undef if -1 == syscall( $_[0], $arg_dupe, $buf );
    my @vals = unpack _PACK_TEMPLATE(), $buf;
    splice(
        @vals, 8, 0,
        @{ Cpanel::Struct::timespec->binaries_to_floats_at( $buf, 3, $pre_times_pack_len ) },
    );

    return @vals;
}

1;

} # --- END Cpanel/NanoStat.pm


{ # --- BEGIN Cpanel/NanoUtime.pm
package Cpanel::NanoUtime;


use strict;
use warnings;



# use Cpanel::Struct::timespec ();

use constant {
    _NR_utimensat => 280,

    _AT_FDCWD            => -100,
    _AT_SYMLINK_NOFOLLOW => 0x100,
};



sub utime {
    return _syscall( 0 + _AT_FDCWD(), $_[2], @_[ 0, 1 ], 0 );
}


sub futime {
    return _syscall(
        0 + ( ref( $_[2] ) ? fileno( $_[2] ) : $_[2] ),
        undef,
        @_[ 0, 1 ],
        0,
    );
}


sub lutime {
    return _syscall( 0 + _AT_FDCWD(), $_[2], @_[ 0, 1 ], 0 + _AT_SYMLINK_NOFOLLOW() );
}

my ( $path, $buf ) = @_;

sub _syscall {

    if ( defined $_[-3] ) {
        if ( defined $_[-2] ) {
            $buf = Cpanel::Struct::timespec->float_to_binary( $_[-3] ) . Cpanel::Struct::timespec->float_to_binary( $_[-2] );
        }
        else {
            die "atime is “$_[-3]”, but mtime is undef!";
        }
    }
    elsif ( defined $_[-2] ) {
        die "atime is undef, but mtime is “$_[-2]”!";
    }
    else {
        $buf = undef;
    }

    $path = $_[1];

    return undef if -1 == syscall( 0 + _NR_utimensat(), $_[0], $path // undef, $buf // undef, $_[-1] );

    return 1;
}

1;

} # --- END Cpanel/NanoUtime.pm


{ # --- BEGIN Cpanel/HiRes.pm
package Cpanel::HiRes;


use strict;
use warnings;


my %_routes = (


    'fstat' => [ 'NanoStat', 'fstat', 'stat',  1 ],
    'lstat' => [ 'NanoStat', 'lstat', 'lstat', 1 ],
    'stat'  => [ 'NanoStat', 'stat',  'stat',  1 ],

    'time' => [ 'TimeHiRes', 'time', 'time' ],

    'utime'  => [ 'NanoUtime', 'utime',  'utime' ],
    'futime' => [ 'NanoUtime', 'futime', 'utime' ],

    'lutime' => [ 'NanoUtime', 'lutime', undef ],
);

my $preloaded;


sub import {
    my ( $class, %opts ) = @_;

    if ( my $preload = $opts{'preload'} ) {
        if ( $preload eq 'xs' ) {
            require Time::HiRes;
        }
        elsif ( $preload eq 'perl' ) {
            if ( !$preloaded ) {
                require Cpanel::TimeHiRes;    # PPI USE OK - preload
                require Cpanel::NanoStat;     # PPI USE OK - preload
                require Cpanel::NanoUtime;    # PPI USE OK - preload
            }
        }
        else {
            die "Unknown “preload”: “$preload”";
        }

        $preloaded = $preload;
    }

    return;
}

our $AUTOLOAD;


sub AUTOLOAD {    ## no critic qw(Subroutines::RequireArgUnpacking)
    substr( $AUTOLOAD, 0, 1 + rindex( $AUTOLOAD, ':' ) ) = q<>;

    if ( !$AUTOLOAD || !$_routes{$AUTOLOAD} ) {
        die "Unknown function in Cpanel::HiRes::$_[0]";
    }

    my $function = $AUTOLOAD;

    undef $AUTOLOAD;

    my ( $pp_module, $pp_function, $xs_function, $xs_needs_closure ) = @{ $_routes{$function} };

    no strict 'refs';

    if ( $INC{'Time/HiRes.pm'} && $xs_function ) {
        *$function = *{"Time::HiRes::$xs_function"};
        return Time::HiRes->can($xs_function)->(@_);
    }
    else {

        _require("Cpanel/${pp_module}.pm") if !$INC{"Cpanel/${pp_module}.pm"};

        my $pp_cr = "Cpanel::${pp_module}"->can($pp_function);

        if ($xs_function) {
            *$function = sub {

                if ( $INC{'Time/HiRes.pm'} ) {
                    *$function = *{"Time::HiRes::$xs_function"};
                    return Time::HiRes->can($xs_function)->(@_);
                }

                goto &$pp_cr;
            };
        }
        else {
            *$function = $pp_cr;
        }
    }

    goto &$function;
}

sub _require {
    local ( $!, $^E, $@ );

    require $_[0];
    return;
}

1;

} # --- END Cpanel/HiRes.pm


{ # --- BEGIN Cpanel/Path/Normalize.pm
package Cpanel::Path::Normalize;


use strict;
use warnings;


sub normalize {
    my $uncleanpath = shift || return;

    my $is_abspath = ( 0 == index( $uncleanpath, '/' ) );

    my @pathdirs = split( m[/], $uncleanpath );

    my @cleanpathdirs;
    my $leading_dot_dots = 0;

    foreach my $dir (@pathdirs) {
        next if !length $dir;    #Remove extraneous "//" and leading "/"

        next if $dir eq '.';

        if ( $dir eq '..' ) {
            if (@cleanpathdirs) {
                pop(@cleanpathdirs);
            }
            else {
                $leading_dot_dots++;
            }
        }
        else {
            push( @cleanpathdirs, $dir );
        }
    }

    if ($is_abspath) {
        return ( '/' . join( '/', @cleanpathdirs ) );
    }

    unshift @cleanpathdirs, ('..') x $leading_dot_dots;

    return join( '/', @cleanpathdirs );
}


1;

} # --- END Cpanel/Path/Normalize.pm


{ # --- BEGIN Cpanel/JSON/FailOK.pm
package Cpanel::JSON::FailOK;


use strict;
use warnings;

sub LoadJSONModule {
    local $@;

    my $load_ok = eval {
        local $SIG{'__DIE__'};     # Suppress spewage as we may be reading an invalid cache
        local $SIG{'__WARN__'};    # and since failure is ok to throw it away
        require Cpanel::JSON;      # PPI NO PARSE - FailOK
        1;
    };

    if ( !$load_ok && !$ENV{'CPANEL_BASE_INSTALL'} && index( $^X, '/usr/local/cpanel' ) == 0 ) {
        warn $@;
    }

    return $load_ok ? 1 : 0;
}

sub LoadFile {
    return undef if !$INC{'Cpanel/JSON.pm'};

    return eval {
        local $SIG{'__DIE__'};         # Suppress spewage as we may be reading an invalid cache
        local $SIG{'__WARN__'};        # and since failure is ok to throw it away
        Cpanel::JSON::LoadFile(@_);    # PPI NO PARSE - inc check above
    };
}
1;

} # --- END Cpanel/JSON/FailOK.pm


{ # --- BEGIN Cpanel/Hash/Stringify.pm
package Cpanel::Hash::Stringify;


use strict;
use warnings;


sub sorted_hashref_string {
    my ($hashref) = @_;
    return (
        ( scalar keys %$hashref )
        ? join(
            '_____', map { $_, ( ref $hashref->{$_} eq 'HASH' ? sorted_hashref_string( $hashref->{$_} ) : ref $hashref->{$_} eq 'ARRAY' ? join( '_____', @{ $hashref->{$_} } ) : defined $hashref->{$_} ? $hashref->{$_} : '' ) }
              sort keys %$hashref
          )
        : ''
    );    #sort is important for order;
}

1;

} # --- END Cpanel/Hash/Stringify.pm


{ # --- BEGIN Cpanel/Umask.pm
package Cpanel::Umask;



use strict;

# use Cpanel::Finally();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Finally); }

sub new {
    my ( $class, $new ) = @_;

    my $old = umask();

    umask($new);

    return $class->SUPER::new(
        sub {
            my $cur = umask();

            if ( $cur != $new ) {
                my ( $cur_o, $old_o, $new_o ) = map { '0' . sprintf( '%o', $_ ) } ( $cur, $old, $new );

                warn "I want to umask($old_o). I expected the current umask to be $new_o, but it’s actually $cur_o.";
            }

            umask($old);
        }
    );
}

1;

} # --- END Cpanel/Umask.pm


{ # --- BEGIN Cpanel/Config/LoadConfig.pm
package Cpanel::Config::LoadConfig;


use strict;
use warnings;

# use Cpanel::Hash::Stringify              ();
# use Cpanel::Debug                        ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::AdminBin::Serializer::FailOK ();
# use Cpanel::LoadFile::ReadFast           ();
# use Cpanel::HiRes                        ();
# use Cpanel::SV                           ();

use constant _ENOENT => 2;

my $logger;
our $PRODUCT_CONF_DIR = '/var/cpanel';

our $_DEBUG_SAFEFILE = 0;

my %COMMON_CACHE_NAMES = (
    ':__^\s*[#;]____0__'                                                                           => 'default_colon',
    ':\s+__^\s*[#;]____0__'                                                                        => 'default_colon_any_space',
    ': __^\s*[#;]____0__'                                                                          => 'default_colon_with_one_space',
    '=__^\s*[#;]____0__skip_readable_check_____1'                                                  => 'default_skip_readable',
    '=__^\s*[#;]____0__'                                                                           => 'default',
    '=__^\s*[#;]__(?^:\s+)__0__'                                                                   => 'default_with_preproc_newline',
    '=__^\s*[#;]____1__'                                                                           => 'default_allow_undef',
    '\s*[:]\s*__^\s*[#;]____0__'                                                                   => 'default_colon_before_after_space',
    '\s*=\s*__^\s*[#;]____1__'                                                                     => 'default_equal_before_after_space_allow_undef',
    '\s*[\=]\s*__^\s*[#]____0__use_reverse_____0'                                                  => 'default_equal_before_after_space',
    ': __^\s*[#;]____0__limit_____10000000000_____use_reverse_____0'                               => 'default_with_10000000000_limit',
    '\s*[:]\s*__^\s*[#;]____0__use_hash_of_arr_refs_____0_____use_reverse_____0'                   => 'default_use_hash_of_arr_refs',
    ': __^\s*[#;]____0__limit__________use_reverse_____0'                                          => 'default_colon_single_space_no_limit',
    ': __^\s*[#;]____1__skip_keys_____nobody_____use_hash_of_arr_refs_____0_____use_reverse_____0' => 'default_colon_skip_nobody_no_limit',
    ': __^\s*[#;]____1__use_reverse_____1'                                                         => 'default_reverse_allow_undef',
    '\s+__^\s*[#;]____0__'                                                                         => 'default_space_seperated_config',
    '\s*=\s*__^\s*[#;]__^\s*__0__'                                                                 => 'default_equal_space_seperated_config',           #ea4.conf
);

my $DEFAULT_DELIMITER      = '=';
my $DEFAULT_COMMENT_REGEXP = '^\s*[#;]';                                                                                                                #Keep in sync with tr{} below!!
my @BOOLEAN_OPTIONS        = qw(
  allow_undef_values
  use_hash_of_arr_refs
  use_reverse
);

my $CACHE_DIR_PERMS = 0700;

sub _process_parse_args {
    my (%opts) = @_;

    if ( !defined $opts{'delimiter'} ) {
        $opts{'delimiter'} = $DEFAULT_DELIMITER;
    }

    $opts{'regexp_to_preprune'} ||= q{};

    $opts{'comment'} ||= $DEFAULT_COMMENT_REGEXP;

    $opts{'comment'} = '' if $opts{'comment'} eq '0E0';

    $opts{$_} ||= 0 for @BOOLEAN_OPTIONS;

    return %opts;
}

{
    no warnings 'once';
    *get_homedir_and_cache_dir = *_get_homedir_and_cache_dir;
}

sub _get_homedir_and_cache_dir {
    my ( $homedir, $cache_dir );

    if ( $> == 0 ) {
        $cache_dir = "$PRODUCT_CONF_DIR/configs.cache";
    }
    else {
        {
            no warnings 'once';
            $homedir = $Cpanel::homedir;
        }
        if ( !$homedir ) {
            eval 'local $SIG{__DIE__}; local $SIG{__WARN__}; require Cpanel::PwCache';    ## no critic qw(ProhibitStringyEval) # PPI USE OK - just after
            $homedir = Cpanel::PwCache::gethomedir() if $INC{'Cpanel/PwCache.pm'};
            return unless $homedir;                                                       # undef for homedir and cache_dir avoid issues later when using undef as hash key
        }

        Cpanel::SV::untaint($homedir);

        $homedir =~ tr{/}{}s;

        return ( $homedir, undef ) if $homedir eq '/';
        if ( $ENV{'TEAM_USER'} ) {
            $cache_dir = "$homedir/$ENV{'TEAM_USER'}/.cpanel/caches/config";
        }
        else {
            $cache_dir = "$homedir/.cpanel/caches/config";
        }
    }

    return ( $homedir, $cache_dir );
}

sub loadConfig {    ## no critic qw(Subroutines::ProhibitExcessComplexity Subroutines::ProhibitManyArgs)
    my ( $file, $conf_ref, $delimiter, $comment, $regexp_to_preprune, $allow_undef_values, $arg_ref ) = @_;

    $conf_ref ||= -1;

    my %processed_positional_args = _process_parse_args(
        delimiter          => $delimiter,
        comment            => $comment,
        regexp_to_preprune => $regexp_to_preprune,
        allow_undef_values => $allow_undef_values,
        $arg_ref ? %$arg_ref : (),
    );

    my $empty_is_invalid = ( defined $arg_ref ) ? delete $arg_ref->{'empty_is_invalid'} : undef;

    my ( $use_reverse, $use_hash_of_arr_refs );
    ( $delimiter, $comment, $regexp_to_preprune, $allow_undef_values, $use_reverse, $use_hash_of_arr_refs ) = @processed_positional_args{
        qw(
          delimiter
          comment
          regexp_to_preprune
          allow_undef_values
          use_reverse
          use_hash_of_arr_refs
        )
    };


    if ( !$file || $file =~ tr/\0// ) {
        _do_logger( 'warn', 'loadConfig requires valid filename' );
        if ( $arg_ref->{'keep_locked_open'} ) {
            return ( undef, undef, undef, "loadConfig requires valid filename" );
        }

        return;
    }

    my $filesys_mtime = ( Cpanel::HiRes::stat($file) )[9] or do {
        if ( $arg_ref->{'keep_locked_open'} ) {
            return ( undef, undef, undef, "Unable to stat $file: $!" );
        }
        return;
    };

    my $load_into_conf_ref = ( !ref $conf_ref && $conf_ref == -1 ) ? 0 : 1;

    if ($load_into_conf_ref) {
        $conf_ref = _hashify_ref($conf_ref);
    }

    my ( $homedir, $cache_dir ) = _get_homedir_and_cache_dir();

    my $cache_file;

    Cpanel::AdminBin::Serializer::FailOK::LoadModule() if !$INC{'Cpanel/AdminBin/Serializer.pm'};
    if ( $cache_dir && $INC{'Cpanel/JSON.pm'} && ( !defined $arg_ref || !ref $arg_ref || !exists $arg_ref->{'nocache'} && !$arg_ref->{'keep_locked_open'} ) ) {

        $cache_file = get_cache_file(
            'file'               => $file,
            'cache_dir'          => $cache_dir,
            'delimiter'          => $delimiter,
            'comment'            => $comment,
            'regexp_to_preprune' => $regexp_to_preprune,
            'allow_undef_values' => $allow_undef_values,
            'arg_ref'            => $arg_ref,
        );

        my ( $cache_valid, $ref ) = load_from_cache_if_valid(
            'file'               => $file,
            'cache_file'         => $cache_file,
            'filesys_mtime'      => $filesys_mtime,
            'conf_ref'           => $conf_ref,
            'load_into_conf_ref' => $load_into_conf_ref,
            'empty_is_invalid'   => $empty_is_invalid,
        );

        if ($cache_valid) {
            return $ref;
        }
    }

    $conf_ref = {} if !$load_into_conf_ref;

    my $conf_fh;
    my $conflock;
    my $locked;
    if ( $arg_ref->{'keep_locked_open'} || $arg_ref->{'rw'} ) {
        require Cpanel::SafeFile;
        $locked   = 1;
        $conflock = Cpanel::SafeFile::safeopen( $conf_fh, '+<', $file );
    }
    else {
        $conflock = open( $conf_fh, '<', $file );
    }

    if ( !$conflock ) {
        my $open_err = $! || '(unspecified error)';

        local $_DEBUG_SAFEFILE = 1;

        require Cpanel::Logger;
        my $is_root = ( $> == 0 ? 1 : 0 );

        if ( !$is_root && !$arg_ref->{'skip_readable_check'} ) {
            if ( !-r $file ) {
                my $msg;

                if ( my $err = $! ) {
                    $msg = "$file’s readability check failed: $err";
                }
                else {
                    my $euser = getpwuid $>;
                    $msg = "$file is not readable as $euser.";
                }

                _do_logger( 'warn', $msg );

                if ( $arg_ref->{'keep_locked_open'} ) {
                    return ( undef, undef, undef, $msg );
                }

                return;
            }
        }
        my $verb = ( $locked ? 'lock/' : q<> ) . 'open';
        my $msg  = "Unable to $verb $file as UIDs $</$>: $open_err";

        Cpanel::Logger::cplog( $msg, 'warn', __PACKAGE__ );
        if ( $arg_ref->{'keep_locked_open'} ) {
            return ( undef, undef, undef, $msg );
        }
        return;
    }

    my ( $parse_ok, $parsed ) = _parse_from_filehandle(
        $conf_fh,
        comment              => $comment,
        delimiter            => $delimiter,
        regexp_to_preprune   => $regexp_to_preprune,
        allow_undef_values   => $allow_undef_values,
        use_reverse          => $use_reverse,
        use_hash_of_arr_refs => $use_hash_of_arr_refs,
        $arg_ref ? %$arg_ref : (),
    );

    if ( $locked && !$arg_ref->{'keep_locked_open'} ) {
        require Cpanel::SafeFile;
        Cpanel::SafeFile::safeclose( $conf_fh, $conflock );
    }

    if ( !$parse_ok ) {
        require Cpanel::Logger;
        Cpanel::Logger::cplog( "Unable to parse $file: $parsed", 'warn', __PACKAGE__ );
        if ( $arg_ref->{'keep_locked_open'} ) {
            return ( undef, undef, undef, "Unable to parse $file: $parsed" );
        }
        return;
    }

    @{$conf_ref}{ keys %$parsed } = values %$parsed;

    if ($cache_file) {
        write_cache(
            'cache_dir'  => $cache_dir,
            'cache_file' => $cache_file,
            'homedir'    => $homedir,
            'is_root'    => ( $> == 0 ? 1 : 0 ),
            'data'       => $parsed,
        );
    }

    if ( $arg_ref->{'keep_locked_open'} ) {
        return $conf_ref, $conf_fh, $conflock, "open success";
    }

    return $conf_ref;
}

sub load_from_cache_if_valid {
    my (%opts) = @_;

    my $cache_file = $opts{'cache_file'} or die "need cache_file!";

    my $file               = $opts{'file'};
    my $conf_ref           = $opts{'conf_ref'};
    my $load_into_conf_ref = $opts{'load_into_conf_ref'};
    my $filesys_mtime      = $opts{'filesys_mtime'} || ( Cpanel::HiRes::stat($file) )[9];

    open( my $cache_fh, '<:stdio', $cache_file ) or do {
        my $err = $!;

        my $msg = "non-fatal error: open($cache_file): $err";

        warn $msg if $! != _ENOENT();

        return ( 0, $msg );
    };

    my ( $cache_filesys_mtime, $now, $cache_conf_ref ) = ( ( Cpanel::HiRes::fstat($cache_fh) )[9], Cpanel::HiRes::time() );    # stat the file after we have it open to avoid a race condition

    if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {
        print STDERR __PACKAGE__ . "::loadConfig file:$file, cache_file:$cache_file, cache_filesys_mtime:$cache_filesys_mtime, filesys_mtime:$filesys_mtime, now:$now\n";
    }

    if ( $filesys_mtime && _greater_with_same_precision( $cache_filesys_mtime, $filesys_mtime ) && _greater_with_same_precision( $now, $cache_filesys_mtime ) ) {
        if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {
            print STDERR __PACKAGE__ . "::loadConfig using cache_file:$cache_file\n";
        }

        Cpanel::AdminBin::Serializer::FailOK::LoadModule() if !$INC{'Cpanel/AdminBin/Serializer.pm'};
        if ( $cache_conf_ref = Cpanel::AdminBin::Serializer::FailOK::LoadFile($cache_fh) ) {    #zero keys is a valid file still it may just be all comments or empty
            close($cache_fh);

            if ( $opts{'empty_is_invalid'} && scalar keys %$cache_conf_ref == 0 ) {
                return ( 0, 'Cache is empty' );
            }

            my $ref_to_return;
            if ($load_into_conf_ref) {
                @{$conf_ref}{ keys %$cache_conf_ref } = values %$cache_conf_ref;
                $ref_to_return = $conf_ref;
            }
            else {
                $ref_to_return = $cache_conf_ref;
            }

            return ( 1, $ref_to_return );
        }
        elsif ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {
            print STDERR __PACKAGE__ . "::loadConfig failed to load cache_file:$cache_file\n";
        }

    }
    else {
        if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {
            print STDERR __PACKAGE__ . "::loadConfig NOT using cache_file:$cache_file\n";
        }
    }

    return ( 0, 'Cache not valid' );
}

sub _greater_with_same_precision {
    my ( $float1, $float2 ) = @_;
    my ( $int1,   $int2 )   = ( int($float1), int($float2) );
    if ( $float1 == $int1 or $float2 == $int2 ) {
        return $int1 > $int2;
    }
    return $float1 > $float2;
}

sub get_cache_file {    ## no critic qw(Subroutines::RequireArgUnpacking) - Args unpacked by _process_parse_args
    my %opts = _process_parse_args(@_);

    die 'need cache_dir!' if !$opts{'cache_dir'};

    my $stringified_args = join(
        '__',
        @opts{qw(delimiter comment regexp_to_preprune allow_undef_values)}, ( scalar keys %{ $opts{'arg_ref'} } ? Cpanel::Hash::Stringify::sorted_hashref_string( $opts{'arg_ref'} ) : '' )
    );
    if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {    # PPI NO PARSE -  ok missing
        print STDERR __PACKAGE__ . "::loadConfig stringified_args[$stringified_args]\n";
    }

    my $safe_filename = $opts{'file'};
    $safe_filename =~ tr{/}{_};

    return $opts{'cache_dir'} . '/' . $safe_filename . '___' . ( $COMMON_CACHE_NAMES{$stringified_args} || _get_fastest_hash($stringified_args) );
}

sub _get_fastest_hash {
    require Cpanel::Hash;
    goto \&Cpanel::Hash::get_fastest_hash;
}

sub write_cache {
    my (%opts)     = @_;
    my $cache_file = $opts{'cache_file'};
    my $cache_dir  = $opts{'cache_dir'};
    my $homedir    = $opts{'homedir'};
    my $is_root    = $opts{'is_root'};
    my $parsed     = $opts{'data'};

    my @dirs = ($cache_dir);
    if ( !$is_root ) {
        if ( $ENV{'TEAM_USER'} ) {
            unshift @dirs, "$homedir/$ENV{'TEAM_USER'}", "$homedir/$ENV{'TEAM_USER'}/.cpanel", "$homedir/$ENV{'TEAM_USER'}/.cpanel/caches";
        }
        else {
            unshift @dirs, "$homedir/.cpanel", "$homedir/.cpanel/caches";
        }
    }

    foreach my $dir (@dirs) {
        Cpanel::SV::untaint($dir);

        chmod( $CACHE_DIR_PERMS, $dir ) or do {
            if ( $! == _ENOENT() ) {

                require Cpanel::Umask;
                my $umask = Cpanel::Umask->new(0);

                mkdir( $dir, $CACHE_DIR_PERMS ) or do {
                    _do_logger( 'warn', "Failed to create dir “$dir”: $!" );
                };
            }
            else {
                _do_logger( 'warn', "chmod($dir): $!" );
            }
        };

    }

    my $wrote_ok = eval { Cpanel::FileUtils::Write::JSON::Lazy::write_file( $cache_file, $parsed, 0600 ) };
    my $error    = $@;

    $error ||= "Unknown error" if !defined $wrote_ok;
    if ($error) {
        _do_logger( 'warn', "Could not create cache file “$cache_file”: $error" );
        unlink $cache_file;    #outdated
    }
    if ( ( $Cpanel::Debug::level || 0 ) > 4 ) {    # PPI NO PARSE -  ok missing
        print STDERR __PACKAGE__ . "::loadConfig [lazy write cache file] [$cache_file] wrote_ok:[$wrote_ok]\n";
    }
    return 1;
}

sub _do_logger {
    my ( $action, $msg ) = @_;

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

    return $logger->$action($msg);
}

sub parse_from_filehandle {
    my ( $conf_fh, %opts ) = @_;
    return _parse_from_filehandle( $conf_fh, _process_parse_args(%opts) );
}

sub _parse_from_filehandle {
    my ( $conf_fh, %opts ) = @_;


    my ( $comment, $limit, $regexp_to_preprune, $delimiter, $allow_undef_values, $use_hash_of_arr_refs, $skip_keys, $use_reverse ) = @opts{
        qw(
          comment
          limit
          regexp_to_preprune
          delimiter
          allow_undef_values
          use_hash_of_arr_refs
          skip_keys
          use_reverse
        )
    };

    my $conf_ref = {};

    my $parser_code;
    my ( $k, $v );    ## no critic qw(Variables::ProhibitUnusedVariables)
    my $keys           = 0;
    my $key_value_text = $use_reverse ? '1,0' : '0,1';
    my $cfg_txt        = '';
    Cpanel::LoadFile::ReadFast::read_all_fast( $conf_fh, $cfg_txt );
    my $has_cr = index( $cfg_txt, "\r" ) > -1 ? 1 : 0;
    _remove_comments_from_text( \$cfg_txt, $comment, \$has_cr ) if $cfg_txt && $comment;

    my $split_on = $has_cr ? '\r?\n' : '\n';

    if ( !$limit && !$regexp_to_preprune && !$use_hash_of_arr_refs && length $delimiter ) {
        if ($allow_undef_values) {
            $parser_code = qq<
                  \$conf_ref = {
                      map {
                          (split(m/> . $delimiter . qq</, \$_, 2))[$key_value_text]
                      } split(/> . $split_on . qq</, \$cfg_txt)
                  };
              >;
        }
        else {
            $parser_code = ' $conf_ref = {  map { ' . '($k,$v) = (split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . ']; ' . 'defined($v) ? ($k,$v) : () ' . '} split(/' . $split_on . '/, $cfg_txt ) }';
        }
    }
    else {
        if ( ( $Cpanel::Debug::level || 0 ) > 4 ) {    # PPI NO PARSE - ok if not there
            $limit ||= 0;
            print STDERR __PACKAGE__ . "::parse_from_filehandle [slow LoadConfig parser used] LIMIT:[!$limit] REGEXP_TO_DELETE[!$regexp_to_preprune] USE_HASH_OF_ARR_REFS[$use_hash_of_arr_refs)]\n";
        }
        $parser_code = 'foreach (split(m/' . $split_on . '/, $cfg_txt)) {' . "\n"                                                                            #
          . q{next if !length;} . "\n"                                                                                                                       #
          . ( $limit ? q{last if $keys++ == } . $limit . ';' : '' ) . "\n" . ( $regexp_to_preprune ? q{ s/} . $regexp_to_preprune . q{//g;} : '' ) . "\n"    #
          . (
            length $delimiter ?                                                                                                                              #
              (
                q{( $k, $v ) = (split( /} . $delimiter . q{/, $_, 2 ))[} . $key_value_text . q{];} . "\n" .                                                  #
                  ( !$allow_undef_values  ? q{ next if !defined($v); }          : '' ) . "\n" .                                                              #
                  ( $use_hash_of_arr_refs ? q{ push @{ $conf_ref->{$k} }, $v; } : q{ $conf_ref->{$k} = $v; } ) . "\n"                                        #
              )
            : q{$conf_ref->{$_} = 1; } . "\n"
          ) . '};';
    }

    $parser_code .= "; 1";
    $parser_code =~ tr{\n}{\r};    ## no critic qw(Cpanel::TransliterationUsage)
    eval($parser_code) or do {     ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        $parser_code =~ tr{\r}{\n};    ## no critic qw(Cpanel::TransliterationUsage)
        _do_logger( 'panic', "Failed to parse :: $parser_code: $@" );
        return ( 0, "$@\n$parser_code" );
    };

    delete $conf_ref->{''} if !defined( $conf_ref->{''} );

    if ($skip_keys) {
        my $skip_keys_ar;
        if ( ref $skip_keys eq 'ARRAY' ) {
            $skip_keys_ar = $skip_keys;
        }
        elsif ( ref $skip_keys eq 'HASH' ) {
            $skip_keys_ar = [ keys %$skip_keys ];
        }
        else {
            return ( 0, 'skip_keys must be an ARRAY or HASH reference' );
        }
        delete @{$conf_ref}{@$skip_keys_ar};
    }

    return ( 1, $conf_ref );
}

sub _hashify_ref {
    my $conf_ref = shift;

    if ( !defined($conf_ref) ) {
        $conf_ref = {};
        return $conf_ref;
    }

    unless ( ref $conf_ref eq 'HASH' ) {
        if ( ref $conf_ref ) {
            require Cpanel::Logger;
            Cpanel::Logger::cplog( 'hashifying non-HASH reference', 'warn', __PACKAGE__ );

            ${$conf_ref} = {};
            $conf_ref = ${$conf_ref};
        }
        else {
            require Cpanel::Logger;
            Cpanel::Logger::cplog( 'defined value encountered where reference expected', 'die', __PACKAGE__ );
        }
    }
    return $conf_ref;
}

sub default_product_dir {
    $PRODUCT_CONF_DIR = shift if @_;
    return $PRODUCT_CONF_DIR;
}

sub _remove_comments_from_text {
    my ( $cfg_txt_sr, $comment, $has_cr_sr ) = @_;
    if ($$has_cr_sr) {
        $$cfg_txt_sr = join( "\n", grep ( !m/$comment/, split( m{\r?\n}, $$cfg_txt_sr ) ) );
        $$has_cr_sr  = 0;
    }
    elsif ( $comment eq $DEFAULT_COMMENT_REGEXP ) {

        if ( rindex( $$cfg_txt_sr, '#', 0 ) == 0 && index( $$cfg_txt_sr, "\n" ) > -1 ) {
            substr( $$cfg_txt_sr, 0, index( $$cfg_txt_sr, "\n" ) + 1, '' );
        }
        $$cfg_txt_sr =~ s{$DEFAULT_COMMENT_REGEXP.*}{}omg if $$cfg_txt_sr =~ tr{#;}{};
    }
    else {
        $$cfg_txt_sr =~ s{$comment.*}{}mg;
    }
    return 1;
}

1;

} # --- END Cpanel/Config/LoadConfig.pm


{ # --- BEGIN Cpanel/Config/LoadWwwAcctConf.pm
package Cpanel::Config::LoadWwwAcctConf;


use strict;
use warnings;

# use Cpanel::HiRes ();

# use Cpanel::Path::Normalize ();
# use Cpanel::Debug           ();
# use Cpanel::JSON::FailOK    ();

my $SYSTEM_CONF_DIR = '/etc';
my $wwwconf_cache;
my $wwwconf_mtime = 0;

my $has_serializer;

our $wwwacctconf       = "$SYSTEM_CONF_DIR/wwwacct.conf";
our $wwwacctconfshadow = "$SYSTEM_CONF_DIR/wwwacct.conf.shadow";

sub import {
    my $this = shift;
    if ( !exists $INC{'Cpanel/JSON.pm'} ) {
        Cpanel::JSON::FailOK::LoadJSONModule();
    }
    if ( $INC{'Cpanel/JSON.pm'} ) {
        $has_serializer = 1;
    }
    return Exporter::import( $this, @_ );
}

sub loadwwwacctconf {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    if ( $INC{'Cpanel/JSON.pm'} ) { $has_serializer = 1; }    #something else loaded it

    my $filesys_mtime = ( Cpanel::HiRes::stat($wwwacctconf) )[9];

    return if !$filesys_mtime;

    if ( $filesys_mtime == $wwwconf_mtime && $wwwconf_cache ) {
        return wantarray ? %{$wwwconf_cache} : $wwwconf_cache;
    }

    my $wwwacctconf_cache       = "$wwwacctconf.cache";
    my $wwwacctconfshadow_cache = "$wwwacctconfshadow.cache";
    my $is_root                 = $> ? 0 : 1;

    if ($has_serializer) {
        my $cache_file;
        my $cache_filesys_mtime;
        my $have_valid_cache = 1;

        if ( $is_root && -e $wwwacctconfshadow_cache ) {
            $cache_filesys_mtime = ( Cpanel::HiRes::stat($wwwacctconfshadow_cache) )[9];    #shadow cache's mtime

            my $shadow_file_mtime = ( Cpanel::HiRes::stat $wwwacctconfshadow )[9] || 0;
            if ( $shadow_file_mtime < $cache_filesys_mtime ) {
                $cache_file = $wwwacctconfshadow_cache;
            }
            else {    #don't use shadow cache if shadow file is newer
                $have_valid_cache = undef;
            }
        }

        elsif ( -e $wwwacctconf_cache && !( $is_root && -r $wwwacctconfshadow ) ) {
            $cache_filesys_mtime = ( Cpanel::HiRes::stat $wwwacctconf_cache )[9];    #regular cache's mtime
            $cache_file          = $wwwacctconf_cache;
        }
        else {
            $have_valid_cache = undef;
        }
        my $now = Cpanel::HiRes::time();

        if ( $Cpanel::Debug::level >= 5 ) {
            print STDERR __PACKAGE__ . "::loadwwwacctconf cache_filesys_mtime = $cache_filesys_mtime , filesys_mtime: $filesys_mtime , now : $now\n";
        }

        if ( $have_valid_cache && $cache_filesys_mtime > $filesys_mtime && $cache_filesys_mtime < $now ) {
            my $wwwconf_ref;
            if ( open( my $conf_fh, '<', $cache_file ) ) {
                $wwwconf_ref = Cpanel::JSON::FailOK::LoadFile($conf_fh);
                close($conf_fh);
            }

            if ( $wwwconf_ref && ( scalar keys %{$wwwconf_ref} ) > 0 ) {
                if ( $Cpanel::Debug::level >= 5 ) { print STDERR __PACKAGE__ . "::loadwwwconf file system cache hit\n"; }
                $wwwconf_cache = $wwwconf_ref;
                $wwwconf_mtime = $filesys_mtime;
                return wantarray ? %{$wwwconf_ref} : $wwwconf_ref;
            }
        }
    }

    my @configfiles;
    push @configfiles, $wwwacctconf;

    if ($is_root) { push @configfiles, $wwwacctconfshadow; }    #shadow file must be last as the cache gets written for each file with all the files before it in it

    my $can_write_cache;
    if ( $is_root && $has_serializer ) {
        $can_write_cache = 1;
    }

    my %CONF = (
        'ADDR'         => undef,
        'CONTACTEMAIL' => undef,
        'DEFMOD'       => undef,
        'ETHDEV'       => undef,
        'HOST'         => undef,
        'NS'           => undef,
        'NS2'          => undef,
    );
    require Cpanel::Config::LoadConfig;
    foreach my $configfile (@configfiles) {
        Cpanel::Config::LoadConfig::loadConfig( $configfile, \%CONF, '\s+', undef, undef, undef, { 'nocache' => 1 } );

        foreach ( keys %CONF ) {

            $CONF{$_} =~ s{\s+$}{} if defined $CONF{$_};
        }

        $CONF{'HOMEMATCH'} =~ s{/+$}{} if defined $CONF{'HOMEMATCH'};    # Remove trailing slashes

        $CONF{'HOMEDIR'} = Cpanel::Path::Normalize::normalize( $CONF{'HOMEDIR'} ) if defined $CONF{'HOMEDIR'};

        if ($can_write_cache) {
            my $cache_file = $configfile . '.cache';
            require Cpanel::FileUtils::Write::JSON::Lazy;
            Cpanel::FileUtils::Write::JSON::Lazy::write_file( $cache_file, \%CONF, ( $configfile eq $wwwacctconfshadow ) ? 0600 : 0644 );
        }
    }

    $wwwconf_mtime = $filesys_mtime;
    $wwwconf_cache = \%CONF;

    return wantarray ? %CONF : \%CONF;
}

sub reset_mem_cache {
    ( $wwwconf_mtime, $wwwconf_cache ) = ( 0, undef );
}

sub reset_has_serializer {
    $has_serializer = 0;
}

sub default_conf_dir {
    $SYSTEM_CONF_DIR = shift if @_;

    $wwwacctconf       = "$SYSTEM_CONF_DIR/wwwacct.conf";
    $wwwacctconfshadow = "$SYSTEM_CONF_DIR/wwwacct.conf.shadow";

    return $SYSTEM_CONF_DIR;
}

sub reset_caches {
    my @cache_files = map { "$_.cache" } ( $wwwacctconf, $wwwacctconfshadow );

    for my $cache_file (@cache_files) {
        unlink $cache_file if -e $cache_file;
    }

    reset_mem_cache();

    return;
}

1;

} # --- END Cpanel/Config/LoadWwwAcctConf.pm


{ # --- BEGIN Cpanel/Conf.pm
package Cpanel::Conf;


# use Cpanel::Config::Constants ();
my $cpanel_theme;
my $webmail_theme;

sub new {
    my ( $class, %opts ) = @_;
    my $self = {};
    bless $self, $class;
    if ( exists $opts{'wwwacct'} && ref $opts{'wwwacct'} eq 'HASH' ) {
        $self->{'wwwacct'} = $opts{'wwwacct'};
    }

    undef $cpanel_theme;
    undef $webmail_theme;

    return $self;
}

sub system_config_dir {
    my ($self) = @_;
    return '/etc';
}

sub product_config_dir {
    my ($self) = @_;
    return '/var/cpanel';
}

sub product_base_dir {
    my ($self) = @_;
    return '/usr/local/cpanel';
}

sub whm_base_dir {
    my ($self) = @_;
    return $self->product_base_dir . '/whostmgr';
}

sub cpanel_theme_dir {
    my ($self) = @_;
    return $self->product_base_dir . '/base/frontend';
}

sub whm_theme_dir {
    my ($self) = @_;
    return $self->whm_base_dir . '/docroot/themes';
}

sub whm_theme {
    my ($self) = @_;
    return 'x';
}

sub account_creation_defaults {
    my ($self) = @_;
    if ( exists $self->{'wwwacct'} ) {
        my %wwwacct = %{ $self->{'wwwacct'} };
        return \%wwwacct;
    }
    require Cpanel::Config::LoadWwwAcctConf;
    return Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
}

sub cpanel_theme {
    my ($self) = @_;
    return $cpanel_theme if defined $cpanel_theme;

    $cpanel_theme = $Cpanel::Config::Constants::DEFAULT_CPANEL_THEME;

    my $defaults = {};
    $defaults = $self->account_creation_defaults();
    if ( ref $defaults eq 'HASH' && $defaults->{'DEFMOD'} ) {
        $cpanel_theme = $defaults->{'DEFMOD'};
    }
    return $cpanel_theme;
}

sub default_webmail_theme {
    my ($self) = @_;
    return $webmail_theme if defined $webmail_theme;

    $webmail_theme = $Cpanel::Config::Constants::DEFAULT_WEBMAIL_THEME;

    my $defaults = {};
    $defaults = $self->account_creation_defaults();
    if ( ref $defaults eq 'HASH' && $defaults->{'DEFMOD'} ) {
        $webmail_theme = $defaults->{'DEFMOD'};
    }
    return $webmail_theme;
}

1;

} # --- END Cpanel/Conf.pm


{ # --- BEGIN Cpanel/Config/LoadCpUserFile.pm
package Cpanel::Config::LoadCpUserFile;


use strict;
use warnings;


use Try::Tiny;

# use Cpanel::DB::Utils                    ();
# use Cpanel::Exception                    ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::AdminBin::Serializer::FailOK ();
# use Cpanel::Config::Constants            ();
# use Cpanel::Config::CpUser::Defaults     ();
# use Cpanel::Config::CpUser::Object       ();
# use Cpanel::ConfigFiles                  ();
# use Cpanel::LoadFile::ReadFast           ();
# use Cpanel::SV                           ();

our $VERSION = '0.82';    # DO NOT CHANGE THIS FROM A DECIMAL

sub _cpuser_defaults {
    return @Cpanel::Config::CpUser::Defaults::DEFAULTS_KV;
}

my %should_never_be_on_disk = map { $_ => undef } qw(
  DBOWNER
  DOMAIN
  DOMAINS
  DEADDOMAINS
  HOMEDIRLINKS
);

my $logger;



sub load_or_die {
    return ( _load( $_[0], undef, if_missing => 'die' ) )[2];
}

sub load_if_exists {
    return ( _load( $_[0], undef, if_missing => 'return' ) )[2] // undef;
}

sub load_file {
    my ($file) = @_;


    return parse_cpuser_file( _open_cpuser_file( '<', $file ) );
}

sub _open_cpuser_file_locked {
    my ( $mode, $file ) = @_;

    local $!;

    my $cpuser_fh;

    require Cpanel::SafeFile;
    my $lock_obj = Cpanel::SafeFile::safeopen( $cpuser_fh, $mode, $file ) or do {
        die Cpanel::Exception::create( 'IO::FileOpenError', [ path => $file, error => $!, mode => $mode ] );
    };

    return ( $lock_obj, $cpuser_fh );
}

sub _open_cpuser_file {
    my ( $mode, $file ) = @_;

    local $!;

    my $cpuser_fh;

    open( $cpuser_fh, $mode, $file ) or do {
        die Cpanel::Exception::create( 'IO::FileOpenError', [ path => $file, error => $!, mode => $mode ] );
    };
    return $cpuser_fh;
}

sub parse_cpuser_file {
    my ($cpuser_fh) = @_;

    my $buffer = '';
    Cpanel::LoadFile::ReadFast::read_all_fast( $cpuser_fh, $buffer );

    return parse_cpuser_file_buffer($buffer);
}


sub parse_cpuser_file_buffer {
    my ($buffer) = @_;

    my %cpuser = _cpuser_defaults();

    my %DOMAIN_MAP;
    my %DEAD_DOMAIN_MAP;
    my %HOMEDIRLINKS_MAP;

    local ( $!, $_ );

    foreach ( split( m{\n}, $buffer ) ) {
        next if index( $_, '#' ) > -1 && m/^\s*#/;

        my ( $key, $value ) = split( /\s*=/, $_, 2 );

        if ( !defined $value || exists $should_never_be_on_disk{$key} ) {
            next;

        }
        elsif ( $key eq 'DNS' ) {
            $cpuser{'DOMAIN'} = lc $value;
        }

        elsif ( index( $key, 'DNS' ) == 0 && substr( $key, 3, 1 ) =~ tr{0-9}{} ) {
            $DOMAIN_MAP{ lc $value } = undef;
        }
        elsif ( index( $key, 'XDNS' ) == 0 && substr( $key, 4, 1 ) =~ tr{0-9}{} ) {
            $DEAD_DOMAIN_MAP{ lc $value } = undef;
        }
        elsif ( index( $key, 'HOMEDIRPATHS' ) == 0 && $key =~ m{ \A HOMEDIRPATHS \d* \z }xms ) {
            $HOMEDIRLINKS_MAP{$value} = undef;
        }
        else {
            $cpuser{$key} = $value;
        }
    }

    delete @DEAD_DOMAIN_MAP{ keys %DOMAIN_MAP };
    delete $DOMAIN_MAP{ $cpuser{'DOMAIN'} };

    if ($!) {
        die Cpanel::Exception::create( 'IO::FileReadError', [ error => $! ] );
    }

    if ( exists $cpuser{'USER'} ) {

        $cpuser{'DBOWNER'} = Cpanel::DB::Utils::username_to_dbowner( $cpuser{'USER'} );
    }

    if ( !length $cpuser{'RS'} ) {
        require Cpanel::Conf;
        my $cp_defaults = Cpanel::Conf->new();
        $cpuser{'RS'} = $cp_defaults->cpanel_theme;
    }

    if ( !$cpuser{'LOCALE'} ) {
        $cpuser{'LOCALE'}           = 'en';
        $cpuser{'__LOCALE_MISSING'} = 1;
    }
    $cpuser{'DOMAINS'}      = [ sort keys %DOMAIN_MAP ];         # Sorted here so they can be tested with TM::is_deeply
    $cpuser{'DEADDOMAINS'}  = [ sort keys %DEAD_DOMAIN_MAP ];    # Sorted here so they can be tested with TM::is_deeply
    $cpuser{'HOMEDIRLINKS'} = [ sort keys %HOMEDIRLINKS_MAP ];

    return _wrap_cpuser( \%cpuser );
}

sub _wrap_cpuser {
    return Cpanel::Config::CpUser::Object->adopt(shift);
}

sub _logger {
    return $logger ||= do {
        require Cpanel::Logger;
        Cpanel::Logger->new();
    };
}

sub load {
    my ( $user, $opts ) = @_;

    my $cpuser = ( _load( $user, $opts ) )[2];

    if ( !ref $cpuser ) {
        _logger()->warn( "Failed to load cPanel user file for '" . ( $user || '' ) . "'" ) unless $opts->{'quiet'};
        return wantarray ? () : bless( {}, 'Cpanel::Config::CpUser::Object' );
    }
    return wantarray ? %$cpuser : $cpuser;
}

sub _load_locked {
    my ($user) = @_;

    my ( $fh, $lock_fh, $cpuser ) = _load( $user, { lock => 1 } );

    return unless $fh && $lock_fh && $cpuser;

    return {
        'file' => $fh,
        'lock' => $lock_fh,
        'data' => $cpuser,
    };
}

sub clear_cache {
    my ($user) = @_;

    return unlink "$Cpanel::ConfigFiles::cpanel_users.cache/$user";
}

sub _load {    ## no critic(Subroutines::ProhibitExcessComplexity)  -- Refactoring this function is a project, not a bug fix
    my ( $user, $load_opts_ref, %internal_opts ) = @_;

    if ( !$user || $user =~ tr</\0><> ) {    #no eq '' needed as !$user covers this
        _logger()->warn("Invalid username (falsy or forbidden character) given to loadcpuserfile.");

        if ( $internal_opts{'if_missing'} ) {
            die Cpanel::Exception::create( 'UserNotFound', [ name => '' ] );
        }

        return;
    }

    my ( $now, $has_serializer, $user_file, $user_cache_file ) = (
        time(),                                                                    #now
        ( exists $INC{'Cpanel/JSON.pm'} ? 1 : 0 ),                                 #has_serializer
        $load_opts_ref->{'file'} || "$Cpanel::ConfigFiles::cpanel_users/$user",    # user_file
        "$Cpanel::ConfigFiles::cpanel_users.cache/$user",                          # user_cache_file
    );

    my ( $cpuid, $cpgid, $size, $mtime ) = ( stat($user_file) )[ 4, 5, 7, 9 ];

    if ( not defined($size) and my $if_missing = $internal_opts{'if_missing'} ) {
        if ( $! == _ENOENT() ) {
            if ( $if_missing eq 'return' ) {
                return;
            }

            die Cpanel::Exception::create( 'UserNotFound', [ name => $user ] );
        }
        die Cpanel::Exception->create( 'The system failed to find the file “[_1]” because of an error: [_2]', [ $user_file, $! ] );
    }

    $mtime ||= 0;

    my $lock_fh;
    my $cpuser_fh;

    if ( $load_opts_ref->{'lock'} ) {
        my $mode = $mtime ? '+<' : '+>';
        try {
            ( $lock_fh, $cpuser_fh ) = _open_cpuser_file_locked( $mode, $user_file );
        }
        catch {
            if ( my $if_missing = $internal_opts{'if_missing'} ) {
                die $_ if $if_missing ne 'return';
            }
            else {
                _logger()->warn($_);
            }
        };

        return if !$lock_fh;
    }
    elsif ( !$size ) {
        if ( $user eq 'cpanel' ) {
            my $result = _load_cpanel_user();
            _wrap_cpuser($result);
            return ( $cpuser_fh, $lock_fh, $result );
        }
        else {
            _logger()->warn("User file '$user_file' is empty or non-existent.") unless $load_opts_ref->{'quiet'};
            return;
        }
    }

    if ( $Cpanel::Debug::level && $Cpanel::Debug::level > 3 ) {    # PPI NO PARSE - This doesn't need to be loaded
        _logger()->debug("load cPanel user file [$user]");
    }

    if ($has_serializer) {
        Cpanel::SV::untaint($user_cache_file);                        # case CPANEL-11199
        if ( open( my $cache_fh, '<:stdio', $user_cache_file ) ) {    #ok if the file is not there
            my $cache_mtime = ( stat($cache_fh) )[9];                 # Check the mtime after we have opened the file to prevent a race condition
            if ( $cache_mtime >= $mtime && $cache_mtime <= $now ) {
                my $cpuser_ref = Cpanel::AdminBin::Serializer::FailOK::LoadFile($cache_fh);
                if ( $cpuser_ref && ref $cpuser_ref eq 'HASH' ) {
                    if ( $Cpanel::Debug::level && $Cpanel::Debug::level > 3 ) {    # PPI NO PARSE - This doesn't need to be loaded
                        _logger()->debug("load cache hit user[$user] now[$now] mtime[$mtime] cache_mtime[$cache_mtime]");
                    }
                    $cpuser_ref->{'MTIME'} = $mtime;

                    if ( ( $cpuser_ref->{'__CACHE_DATA_VERSION'} // 0 ) == $VERSION ) {
                        _wrap_cpuser($cpuser_ref);
                        return ( $cpuser_fh, $lock_fh, $cpuser_ref );
                    }
                    else {
                        unlink $user_cache_file;    # force a re-cache of the latest data set
                    }
                }
            }
            else {
                if ( $Cpanel::Debug::level && $Cpanel::Debug::level > 3 ) {    # PPI NO PARSE - This doesn't need to be loaded
                    _logger()->debug("load cache miss user[$user] now[$now] mtime[$mtime] cache_mtime[$cache_mtime]");
                }
            }
            close($cache_fh);
        }
        else {
            if ( $Cpanel::Debug::level && $Cpanel::Debug::level > 3 ) {    # PPI NO PARSE - This doesn't need to be loaded
                _logger()->debug("load cache miss user[$user] now[$now] mtime[$mtime] cache_mtime[0]");
            }
        }
    }

    if ( !$lock_fh ) {
        try {
            $cpuser_fh = _open_cpuser_file( '<', $user_file );
        }
        catch {
            die $_ if $internal_opts{'if_missing'};

            _logger()->warn($_);
        };

        return if !$cpuser_fh;
    }

    my $cpuser_hr;
    try {
        $cpuser_hr = parse_cpuser_file($cpuser_fh);
    }
    catch {
        _logger()->warn("Failed to read “$user_file”: $_");
    };

    return if !$cpuser_hr;

    $cpuser_hr->{'USER'}    = $user;
    $cpuser_hr->{'DBOWNER'} = Cpanel::DB::Utils::username_to_dbowner($user);

    $cpuser_hr->{'__CACHE_DATA_VERSION'} = $VERSION;    # set this before the cache is written so that it will be included in the cache
    if ( $> == 0 ) {
        create_users_cache_dir();
        if ( $has_serializer && Cpanel::FileUtils::Write::JSON::Lazy::write_file( $user_cache_file, $cpuser_hr, 0640 ) ) {
            chown 0, $cpgid, $user_cache_file if $cpgid;    # this is ok if the chown happens after as we fall though to reading the non-cache on a failed open
        }
        else {
            unlink $user_cache_file;                        #outdated
        }
    }

    $cpuser_hr->{'MTIME'} = ( stat($cpuser_fh) )[9];
    if ( $load_opts_ref->{'lock'} ) {
        seek( $cpuser_fh, 0, 0 );
    }
    else {
        if ($lock_fh) {
            require Cpanel::SafeFile;
            Cpanel::SafeFile::safeclose( $cpuser_fh, $lock_fh );
        }
        $cpuser_fh = $lock_fh = undef;
    }

    return ( $cpuser_fh, $lock_fh, $cpuser_hr );
}

sub loadcpuserfile {
    return load( $_[0] );
}

sub _load_cpanel_user {
    my %cpuser = (
        _cpuser_defaults(),
        'DEADDOMAINS'  => [],
        'DOMAIN'       => 'domain.tld',
        'DOMAINS'      => [],
        'HASCGI'       => 1,
        'HOMEDIRLINKS' => [],
        'LOCALE'       => 'en',
        'MAXADDON'     => 'unlimited',
        'MAXPARK'      => 'unlimited',
        'RS'           => $Cpanel::Config::Constants::DEFAULT_CPANEL_THEME,
        'USER'         => 'cpanel',
    );

    return wantarray ? %cpuser : \%cpuser;
}

sub create_users_cache_dir {
    my $uc = "$Cpanel::ConfigFiles::cpanel_users.cache";
    if ( -f $uc || -l $uc ) {
        my $bad = "$uc.bad";
        unlink $bad if -e $bad;
        rename $uc, $bad;
    }
    if ( !-e $uc ) {
        mkdir $uc;
    }
    return;
}

sub _ENOENT { return 2; }

1;

} # --- END Cpanel/Config/LoadCpUserFile.pm


{ # --- BEGIN Cpanel/Config/HasCpUserFile.pm
package Cpanel::Config::HasCpUserFile;


use strict;
use warnings;

# use Cpanel::ConfigFiles ();



sub has_cpuser_file {
    return 0 if !length $_[0] || $_[0] =~ tr{/\0}{};
    return -e "$Cpanel::ConfigFiles::cpanel_users/$_[0]" && -s _;
}


sub has_readable_cpuser_file {
    my ($user) = @_;
    return unless defined $user and $user ne '' and $user !~ tr/\/\0//;

    return -e "$Cpanel::ConfigFiles::cpanel_users/$user" && -s _ && -r _;
}

1;

} # --- END Cpanel/Config/HasCpUserFile.pm


{ # --- BEGIN Cpanel/NSCD/Constants.pm
package Cpanel::NSCD::Constants;


use strict;

our $NSCD_CONFIG_FILE = '/etc/nscd.conf';
our $NSCD_SOCKET      = '/var/run/nscd/socket';

1;

} # --- END Cpanel/NSCD/Constants.pm


{ # --- BEGIN Cpanel/Socket/UNIX/Micro.pm
package Cpanel::Socket::UNIX::Micro;


use strict;

my $MAX_PATH_LENGTH        = 107;
my $LITTLE_ENDIAN_TEMPLATE = 'vZ' . ( 1 + $MAX_PATH_LENGTH );    # x86_64 is always little endian
my $AF_UNIX                = 1;
my $SOCK_STREAM            = 1;

sub connect {
    socket( $_[0], $AF_UNIX, $SOCK_STREAM, 0 ) or warn "socket(AF_UNIX, SOCK_STREAM): $!";
    return connect( $_[0], micro_sockaddr_un( $_[1] ) );
}

sub micro_sockaddr_un {

    if ( length( $_[0] ) > $MAX_PATH_LENGTH ) {
        my $excess = length( $_[0] ) - $MAX_PATH_LENGTH;
        die "“$_[0]” is $excess character(s) too long to be a path to a local socket ($MAX_PATH_LENGTH bytes maximum)!";
    }

    return pack( 'va*', $AF_UNIX, $_[0] ) if 0 == rindex( $_[0], "\0", 0 );

    return pack(
        $LITTLE_ENDIAN_TEMPLATE,    # x86_64 is always little endian
        $AF_UNIX,
        $_[0],
    );
}

sub unpack_sockaddr_un {

    return substr( $_[0], 2 ) if 2 == rindex( $_[0], "\0", 2 );

    return ( unpack $LITTLE_ENDIAN_TEMPLATE, $_[0] )[1];
}

1;

} # --- END Cpanel/Socket/UNIX/Micro.pm


{ # --- BEGIN Cpanel/NSCD/Check.pm
package Cpanel::NSCD::Check;


use strict;

# use Cpanel::NSCD::Constants     ();
# use Cpanel::Socket::UNIX::Micro ();

our $CACHE_TTL = 600;

my $last_check_time = 0;
my $nscd_is_running_cache;

sub nscd_is_running {
    my $now = time();
    if ( $last_check_time && $last_check_time + $CACHE_TTL > $now ) {
        return $nscd_is_running_cache;
    }

    $last_check_time = $now;
    my $socket;
    if ( Cpanel::Socket::UNIX::Micro::connect( $socket, $Cpanel::NSCD::Constants::NSCD_SOCKET ) ) {
        return ( $nscd_is_running_cache = 1 );
    }
    return ( $nscd_is_running_cache = 0 );
}

1;

} # --- END Cpanel/NSCD/Check.pm


{ # --- BEGIN Cpanel/PwCache/Helpers.pm
package Cpanel::PwCache::Helpers;


use strict;
use warnings;

my $skip_uid_cache = 0;

sub no_uid_cache { $skip_uid_cache = 1; return }
sub uid_cache    { $skip_uid_cache = 0; return }

sub skip_uid_cache {
    return $skip_uid_cache;
}

sub init {
    my ( $totie, $skip_uid_cache_value ) = @_;

    tiedto($totie);
    $skip_uid_cache = $skip_uid_cache_value;

    return;
}

{    # debugging helpers
    sub confess { require Carp; return Carp::confess(@_) }
    sub cluck   { require Carp; return Carp::cluck(@_) }
}

{    # tie logic and cache

    my $pwcacheistied = 0;
    my $pwcachetie;

    sub istied { return $pwcacheistied }
    sub deinit { $pwcacheistied = 0; return; }

    sub tiedto {
        my $v = shift;

        if ( !defined $v ) {    # get
            return $pwcacheistied ? $pwcachetie : undef;
        }
        else {                  # set
            $pwcacheistied = 1;
            $pwcachetie    = $v;
        }

        return;
    }

}

{
    my $SYSTEM_CONF_DIR  = '/etc';
    my $PRODUCT_CONF_DIR = '/var/cpanel';

    sub default_conf_dir    { return $SYSTEM_CONF_DIR }
    sub default_product_dir { return $PRODUCT_CONF_DIR; }
}

1;

} # --- END Cpanel/PwCache/Helpers.pm


{ # --- BEGIN Cpanel/PwCache/Cache.pm
package Cpanel::PwCache::Cache;


use strict;
use warnings;

my %_cache;
my %_homedir_cache;
use constant get_cache         => \%_cache;
use constant get_homedir_cache => \%_homedir_cache;

our $pwcache_inited = 0;
my $PWCACHE_IS_SAFE = 1;

sub clear {    # clear all
    %_cache         = ();
    %_homedir_cache = ();
    $pwcache_inited = 0;
    return;
}

sub remove_key {
    my ($pwkey) = @_;
    return delete $_cache{$pwkey};
}

sub replace {
    my $h = shift;
    %_cache = %$h if ref $h eq 'HASH';
    return;
}

sub is_safe {
    $PWCACHE_IS_SAFE = $_[0] if defined $_[0];
    return $PWCACHE_IS_SAFE;
}

sub pwmksafecache {
    return if $PWCACHE_IS_SAFE;
    $_cache{$_}{'contents'}->[1] = 'x' for keys %_cache;
    $PWCACHE_IS_SAFE = 1;
    return;
}

1;

} # --- END Cpanel/PwCache/Cache.pm


{ # --- BEGIN Cpanel/PwCache/Find.pm
package Cpanel::PwCache::Find;


use strict;

# use Cpanel::LoadFile::ReadFast ();

our $PW_CHUNK_SIZE = 1 << 17;

sub field_with_value_in_pw_file {
    my ( $passwd_fh, $field, $value, $lc_flag ) = @_;

    return if ( $value =~ tr{\x{00}-\x{1f}\x{7f}:}{} );

    my $needle = $field == 0 ? "\n${value}:" : ":${value}";
    my $haystack;

    my $match_pos = 0;
    my $line_start;
    my $line_end;
    my $not_eof;
    my $data = "\n";

    while ( ( $not_eof = Cpanel::LoadFile::ReadFast::read_fast( $passwd_fh, $data, $PW_CHUNK_SIZE, length $data ) ) || length($data) > 1 ) {

        $haystack = $not_eof ? substr( $data, 0, rindex( $data, "\n" ), '' ) : $data;

        if ( $lc_flag && $lc_flag == 1 ) {
            $haystack = lc $haystack;
            $needle   = lc $needle;
        }

        while ( -1 < ( $match_pos = index( $haystack, $needle, $match_pos ) ) ) {

            $line_start = ( !$field ? $match_pos : rindex( $haystack, "\n", $match_pos ) ) + 1;
            if (
                !$field || (

                    $field == ( substr( $haystack, $line_start, $match_pos - $line_start + 1 ) =~ tr{:}{} )

                    && ( length($haystack) == $match_pos + length($needle) || substr( $haystack, $match_pos + length($needle), 1 ) =~ tr{:\n}{} )
                )
            ) {
                $line_end = index( $haystack, "\n", $match_pos + length($needle) );
                my $line = substr( $haystack, $line_start, ( $line_end > -1 ? $line_end : length($haystack) ) - $line_start );

                return split( ':', $line );
            }
            $match_pos += length($needle);
        }
        last unless $not_eof;
    }
    return;
}

1;

} # --- END Cpanel/PwCache/Find.pm


{ # --- BEGIN Cpanel/PwCache/Build.pm
package Cpanel::PwCache::Build;


use strict;
use warnings;

# use Cpanel::Debug                        ();
# use Cpanel::JSON::FailOK                 ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::PwCache::Helpers             ();
# use Cpanel::PwCache::Cache               ();
# use Cpanel::LoadFile::ReadFast           ();


my ( $MIN_FIELDS_FOR_VALID_ENTRY, $pwcache_has_uid_cache ) = ( 0, 6 );

sub pwmksafecache {
    return if Cpanel::PwCache::Cache::is_safe();
    my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();

    $pwcache_ref->{$_}{'contents'}->[1] = 'x' for keys %{$pwcache_ref};

    Cpanel::PwCache::Cache::is_safe(1);

    return;
}

sub pwclearcache {    # also known as clear_this_process_cache
    $pwcache_has_uid_cache = undef;

    Cpanel::PwCache::Cache::clear();

    return;
}

sub init_pwcache {
    Cpanel::PwCache::Cache::is_safe(0);
    return _build_pwcache();
}

sub init_passwdless_pwcache {
    return _build_pwcache( 'nopasswd' => 1 );
}

sub fetch_pwcache {
    init_passwdless_pwcache() unless pwcache_is_initted();
    my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();
    if ( scalar keys %$pwcache_ref < 3 ) {
        die "The password cache unexpectedly had less than 3 entries";
    }
    return [ map { $pwcache_ref->{$_}->{'contents'} } grep { substr( $_, 0, 1 ) eq '0' } keys %{$pwcache_ref} ];
}

sub _write_json_cache {
    my ($cache_file) = @_;
    if ( !Cpanel::PwCache::Helpers::istied() && exists $INC{'Cpanel/JSON.pm'} ) {
        my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();
        if ( !ref $pwcache_ref || scalar keys %$pwcache_ref < 3 ) {
            die "The system failed build the password cache";
        }

        Cpanel::FileUtils::Write::JSON::Lazy::write_file( $cache_file, $pwcache_ref, 0600 );
    }
    return;
}

sub _write_tied_cache {
    my ( $crypted_passwd_ref, $passwdmtime, $hpasswdmtime ) = @_;
    my $SYSTEM_CONF_DIR = Cpanel::PwCache::Helpers::default_conf_dir();
    local $!;
    if ( open( my $pwcache_passwd_fh, '<:stdio', "$SYSTEM_CONF_DIR/passwd" ) ) {
        local $/;
        my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();
        my $data        = '';
        Cpanel::LoadFile::ReadFast::read_all_fast( $pwcache_passwd_fh, $data );
        die "The file “$SYSTEM_CONF_DIR/passwd” was unexpectedly empty" if !length $data;
        my @fields;
        my $skip_uid_cache = Cpanel::PwCache::Helpers::skip_uid_cache();

        foreach my $line ( split( /\n/, $data ) ) {
            next unless length $line;
            @fields = split( /:/, $line );
            next if scalar @fields < $MIN_FIELDS_FOR_VALID_ENTRY || $fields[0] =~ tr/[A-Z][a-z][0-9]._-//c;
            $pwcache_ref->{ '0:' . $fields[0] } = {
                'cachetime'  => $passwdmtime,
                'hcachetime' => $hpasswdmtime,
                'contents'   => [ $fields[0], $crypted_passwd_ref->{ $fields[0] } || $fields[1], $fields[2], $fields[3], '', '', $fields[4], $fields[5], $fields[6], -1, -1, $passwdmtime, $hpasswdmtime ]
            };
            next if $skip_uid_cache || !defined $fields[2] || exists $pwcache_ref->{ '2:' . $fields[2] };
            $pwcache_ref->{ '2:' . $fields[2] } = $pwcache_ref->{ '0:' . $fields[0] };
        }
        close($pwcache_passwd_fh);
    }
    else {
        die "The system failed to read $SYSTEM_CONF_DIR/passwd because of an error: $!";
    }
    return;
}

sub _cache_ref_is_valid {
    my ( $cache_ref, $passwdmtime, $hpasswdmtime ) = @_;
    my @keys = qw/0:root 0:cpanel 0:bin/;
    return
         $cache_ref
      && ( scalar keys %{$cache_ref} ) > 2
      && scalar @keys == grep {    #
             $cache_ref->{$_}->{'hcachetime'}
          && $cache_ref->{$_}->{'hcachetime'} == $hpasswdmtime
          && $cache_ref->{$_}->{'cachetime'}
          && $cache_ref->{$_}->{'cachetime'} == $passwdmtime
      } @keys;
}

sub _build_pwcache {
    my %OPTS = @_;

    if ( $INC{'B/C.pm'} ) {
        Cpanel::PwCache::Helpers::confess("Cpanel::PwCache::Build::_build_pwcache cannot be run under B::C (see case 162857)");
    }

    my $SYSTEM_CONF_DIR = Cpanel::PwCache::Helpers::default_conf_dir();

    my ( $cache_file, $passwdmtime, $cache_file_mtime, $crypted_passwd_ref, $crypted_passwd_file, $hpasswdmtime ) = ( "$SYSTEM_CONF_DIR/passwd.cache", ( stat("$SYSTEM_CONF_DIR/passwd") )[9] );

    if ( $OPTS{'nopasswd'} ) {

        $hpasswdmtime = ( stat("$SYSTEM_CONF_DIR/shadow") )[9];
        $cache_file   = "$SYSTEM_CONF_DIR/passwd" . ( Cpanel::PwCache::Helpers::skip_uid_cache() ? '.nouids' : '' ) . '.cache';
    }
    elsif ( -r "$SYSTEM_CONF_DIR/shadow" ) {
        Cpanel::PwCache::Cache::is_safe(0);
        $hpasswdmtime        = ( stat(_) )[9];
        $crypted_passwd_file = "$SYSTEM_CONF_DIR/shadow";
        $cache_file          = "$SYSTEM_CONF_DIR/shadow" . ( Cpanel::PwCache::Helpers::skip_uid_cache() ? '.nouids' : '' ) . '.cache';
    }
    else {
        $hpasswdmtime = 0;
    }

    if ( !Cpanel::PwCache::Helpers::istied() && exists $INC{'Cpanel/JSON.pm'} ) {
        if ( open( my $cache_fh, '<:stdio', $cache_file ) ) {
            my $cache_file_mtime = ( stat($cache_fh) )[9] || 0;
            if ( $cache_file_mtime > $hpasswdmtime && $cache_file_mtime > $passwdmtime ) {
                my $cache_ref = Cpanel::JSON::FailOK::LoadFile($cache_fh);
                Cpanel::Debug::log_debug("[read pwcache from $cache_file]") if ( $Cpanel::Debug::level > 3 );
                if ( _cache_ref_is_valid( $cache_ref, $passwdmtime, $hpasswdmtime ) ) {
                    Cpanel::Debug::log_debug("[validated pwcache from $cache_file]") if ( $Cpanel::Debug::level > 3 );
                    my $memory_pwcache_ref = Cpanel::PwCache::Cache::get_cache();
                    @{$cache_ref}{ keys %$memory_pwcache_ref } = values %$memory_pwcache_ref;
                    Cpanel::PwCache::Cache::replace($cache_ref);
                    $Cpanel::PwCache::Cache::pwcache_inited = ( $OPTS{'nopasswd'} ? 1 : 2 );
                    return;
                }

            }
        }
    }

    if ($crypted_passwd_file) { $crypted_passwd_ref = _load_pws($crypted_passwd_file); }
    $Cpanel::PwCache::Cache::pwcache_inited = ( $OPTS{'nopasswd'}                          ? 1 : 2 );
    $pwcache_has_uid_cache                  = ( Cpanel::PwCache::Helpers::skip_uid_cache() ? 0 : 1 );

    _write_tied_cache( $crypted_passwd_ref, $passwdmtime, $hpasswdmtime );
    _write_json_cache($cache_file) if $> == 0;

    return 1;
}

sub pwcache_is_initted {
    return ( $Cpanel::PwCache::Cache::pwcache_inited ? $Cpanel::PwCache::Cache::pwcache_inited : 0 );
}

sub _load_pws {
    my $lookup_file = shift;

    if ( $INC{'B/C.pm'} ) {
        Cpanel::PwCache::Helpers::confess("Cpanel::PwCache::Build::_load_pws cannot be run under B::C (see case 162857)");
    }

    my %PW;
    if ( open my $lookup_fh, '<:stdio', $lookup_file ) {
        my $data = '';
        Cpanel::LoadFile::ReadFast::read_all_fast( $lookup_fh, $data );
        die "The file “$lookup_file” was unexpectedly empty" if !length $data;
        %PW = map { ( split(/:/) )[ 0, 1 ] } split( /\n/, $data );
        if ( index( $data, '#' ) > -1 ) {
            delete @PW{ '', grep { index( $_, '#' ) == 0 } keys %PW };
        }
        else {
            delete $PW{''};
        }
        close $lookup_fh;
    }
    return \%PW;
}

1;

} # --- END Cpanel/PwCache/Build.pm


{ # --- BEGIN Cpanel/PwCache.pm
package Cpanel::PwCache;




use strict;

# use Cpanel::Debug            ();
# use Cpanel::NSCD::Check      ();
# use Cpanel::PwCache::Helpers ();
# use Cpanel::PwCache::Cache   ();
# use Cpanel::PwCache::Find    ();

use constant DUMMY_PW_RETURNS => ( -1, -1, 0, 0 );
use constant DEBUG            => 0;                  # Must set $ENV{'CPANEL_DEBUG_LEVEL'} = 5 as well

our $VERSION = '4.2';

my %FIXED_KEYS = (
    '0:root'        => 1,
    '0:nobody'      => 1,
    '0:cpanel'      => 1,
    '0:cpanellogin' => 1,
    '0:mail'        => 1,
    '2:0'           => 1,
    '2:99'          => 1
);

our $_WANT_ENCRYPTED_PASSWORD;


sub getpwnam_noshadow {
    $_WANT_ENCRYPTED_PASSWORD = 0;
    goto &_getpwnam;
}

sub getpwuid_noshadow {
    $_WANT_ENCRYPTED_PASSWORD = 0;
    goto &_getpwuid;
}


sub getpwnam {
    $_WANT_ENCRYPTED_PASSWORD = !!wantarray;
    goto &_getpwnam;
}

sub getpwuid {
    $_WANT_ENCRYPTED_PASSWORD = !!wantarray;
    goto &_getpwuid;
}



sub gethomedir {

    my $uid_or_name = $_[0] // $>;

    my $hd = Cpanel::PwCache::Cache::get_homedir_cache();

    unless ( exists $hd->{$uid_or_name} ) {
        $_WANT_ENCRYPTED_PASSWORD = 0;
        if ( $uid_or_name !~ tr{0-9}{}c ) {
            $hd->{$uid_or_name} = ( _getpwuid($uid_or_name) )[7];
        }
        else {
            $hd->{$uid_or_name} = ( _getpwnam($uid_or_name) )[7];
        }
    }

    return $hd->{$uid_or_name};
}


sub getusername {

    my $uid = defined $_[0] ? $_[0] : $>;

    $_WANT_ENCRYPTED_PASSWORD = 0;
    return scalar _getpwuid($uid);
}




sub init_passwdless_pwcache {
    require Cpanel::PwCache::Build;
    *init_passwdless_pwcache = \&Cpanel::PwCache::Build::init_passwdless_pwcache;
    goto &Cpanel::PwCache::Build::init_passwdless_pwcache;
}


sub _getpwuid {    ## no critic qw(Subroutines::RequireArgUnpacking)
    return unless ( length( $_[0] ) && $_[0] !~ tr/0-9//c );

    my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();

    if ( !exists $pwcache_ref->{"2:$_[0]"} && $> != 0 && !Cpanel::PwCache::Helpers::istied() && Cpanel::NSCD::Check::nscd_is_running() ) {
        return CORE::getpwuid( $_[0] ) if !wantarray;

        my @ret = CORE::getpwuid( $_[0] );

        return @ret ? ( @ret, DUMMY_PW_RETURNS() ) : ();
    }

    if ( my $pwref = _pwfunc( $_[0], 2 ) ) {
        return wantarray ? @$pwref : $pwref->[0];
    }
    return;    #important not to return 0
}

sub _getpwnam {    ## no critic qw(Subroutines::RequireArgUnpacking)
    return unless ( length( $_[0] ) && $_[0] !~ tr{\x{00}-\x{20}\x{7f}:/#}{} );

    my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();

    if ( !exists $pwcache_ref->{"0:$_[0]"} && $> != 0 && !Cpanel::PwCache::Helpers::istied() && Cpanel::NSCD::Check::nscd_is_running() ) {
        return CORE::getpwnam( $_[0] ) if !wantarray;

        my @ret = CORE::getpwnam( $_[0] );

        return @ret ? ( @ret, DUMMY_PW_RETURNS() ) : ();
    }

    if ( my $pwref = _pwfunc( $_[0], 0 ) ) {
        return wantarray ? @$pwref : $pwref->[2];
    }
    return;    #important not to return 0
}

sub _pwfunc {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ( $value, $field, $pwkey ) = ( $_[0], ( $_[1] || 0 ), $_[1] . ':' . ( $_[0] || 0 ) );

    if ( Cpanel::PwCache::Helpers::istied() ) {

        Cpanel::Debug::log_debug("cache tie (tied) value[$value] field[$field]") if (DEBUG);
        my $pwcachetie = Cpanel::PwCache::Helpers::tiedto();

        if ( ref $pwcachetie eq 'HASH' ) {
            my $cache = $pwcachetie->{$pwkey};
            if ( ref $cache eq 'HASH' ) {
                return $pwcachetie->{$pwkey}->{'contents'};
            }
        }
        return undef;
    }
    my $SYSTEM_CONF_DIR = Cpanel::PwCache::Helpers::default_conf_dir();

    my $lookup_encrypted_pass = 0;
    if ($_WANT_ENCRYPTED_PASSWORD) {

        $lookup_encrypted_pass = $> == 0 ? 1 : 0;
    }

    my ( $passwdmtime, $hpasswdmtime );

    my $pwcache_ref = Cpanel::PwCache::Cache::get_cache();

    if ( my $cache_entry = $pwcache_ref->{$pwkey} ) {
        Cpanel::Debug::log_debug("exists in cache value[$value] field[$field]") if (DEBUG);
        if (
            ( exists( $cache_entry->{'contents'} ) && $cache_entry->{'contents'}->[1] ne 'x' )    # Has shadow entry
            || !$lookup_encrypted_pass                                                            # Or we do not need it
          ) {                                                                                     # If we are root and missing the password field we could fail authentication
            if ( $FIXED_KEYS{$pwkey} ) {                                                          # We assume root, nobody, and cpanellogin will never change during execution
                Cpanel::Debug::log_debug("cache (never change) hit value[$value] field[$field]") if (DEBUG);
                return $cache_entry->{'contents'};
            }

            $passwdmtime  = ( stat("$SYSTEM_CONF_DIR/passwd") )[9];
            $hpasswdmtime = $lookup_encrypted_pass ? ( stat("$SYSTEM_CONF_DIR/shadow") )[9] : 0;

            if (   ( $lookup_encrypted_pass && $hpasswdmtime && $hpasswdmtime != $cache_entry->{'hcachetime'} )
                || ( $passwdmtime && $passwdmtime != $cache_entry->{'cachetime'} ) ) {    #timewarp safe
                DEBUG && Cpanel::Debug::log_debug( "cache miss value[$value] field[$field] pwkey[$pwkey] " . qq{hpasswdmtime: $hpasswdmtime != $cache_entry->{hcachetime} } . qq{passwdmtime: $passwdmtime != $cache_entry->{cachetime} } );

                if ( defined $cache_entry && defined $cache_entry->{'contents'} ) {

                    Cpanel::PwCache::Cache::clear();    #If the passwd file mtime changes everything is invalid
                }
            }
            else {
                Cpanel::Debug::log_debug("cache hit value[$value] field[$field]") if (DEBUG);
                return $cache_entry->{'contents'};
            }
        }
        elsif (DEBUG) {
            Cpanel::Debug::log_debug( "cache miss pwkey[$pwkey] value[$value] field[$field] passwdmtime[$passwdmtime] pwcacheistied[" . Cpanel::PwCache::Helpers::istied() . "] hpasswdmtime[$hpasswdmtime]" );
        }
    }
    elsif (DEBUG) {
        Cpanel::Debug::log_debug( "cache miss (no entry) pwkey[$pwkey] value[$value] field[$field] pwcacheistied[" . Cpanel::PwCache::Helpers::istied() . "]" );
    }
    my $pwdata = _getpwdata( $value, $field, $passwdmtime, $hpasswdmtime, $lookup_encrypted_pass );

    _cache_pwdata( $pwdata, $pwcache_ref ) if $pwdata && @$pwdata;

    return $pwdata;
}

sub _getpwdata {
    my ( $value, $field, $passwdmtime, $shadowmtime, $lookup_encrypted_pass ) = @_;
    return if ( !defined $value || !defined $field || $value =~ tr/\0// );

    if ($lookup_encrypted_pass) {
        return [ _readshadow( $value, $field, $passwdmtime, $shadowmtime ) ];
    }

    return [ _readpasswd( $value, $field, $passwdmtime, $shadowmtime ) ];
}

sub _readshadow {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $SYSTEM_CONF_DIR = Cpanel::PwCache::Helpers::default_conf_dir();
    my ( $value, $field, $passwdmtime, $shadowmtime ) = ( $_[0], ( $_[1] || 0 ), ( $_[2] || ( stat("$SYSTEM_CONF_DIR/passwd") )[9] ), ( $_[3] || ( stat("$SYSTEM_CONF_DIR/shadow") )[9] ) );
    my @PW = _readpasswd( $value, $field, $passwdmtime, $shadowmtime );
    return if !@PW;

    $value = $PW[0];

    if ( open my $shadow_fh, '<', "$SYSTEM_CONF_DIR/shadow" ) {
        if ( my @SH = Cpanel::PwCache::Find::field_with_value_in_pw_file( $shadow_fh, 0, $value ) ) {

            ( $PW[1], $PW[9], $PW[10], $PW[11], $PW[12] ) = (
                $SH[1],    #encrypted pass
                $SH[5],    #expire time
                $SH[2],    #change time
                $passwdmtime,
                $shadowmtime
            );
            close $shadow_fh;
            Cpanel::PwCache::Cache::is_safe(0);
            return @PW;
        }
    }
    else {
        Cpanel::PwCache::Helpers::cluck("Unable to open $SYSTEM_CONF_DIR/shadow: $!");
    }

    Cpanel::PwCache::Helpers::cluck("Entry for $value missing in $SYSTEM_CONF_DIR/shadow");
    return @PW;
}

sub _readpasswd {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $SYSTEM_CONF_DIR = Cpanel::PwCache::Helpers::default_conf_dir();
    my ( $value, $field, $passwdmtime, $shadowmtime, $block ) = ( $_[0], ( $_[1] || 0 ), ( $_[2] || ( stat("$SYSTEM_CONF_DIR/passwd") )[9] ), $_[3] );

    if ( $INC{'B/C.pm'} ) {
        die("Cpanel::PwCache::_readpasswd cannot be run under B::C (see case 162857)");
    }

    if ( open( my $passwd_fh, '<', "$SYSTEM_CONF_DIR/passwd" ) ) {
        if ( my @PW = Cpanel::PwCache::Find::field_with_value_in_pw_file( $passwd_fh, $field, $value ) ) {

            return ( $PW[0], $PW[1], $PW[2], $PW[3], '', '', $PW[4], $PW[5], $PW[6], -1, -1, $passwdmtime, ( $shadowmtime || $passwdmtime ) );
        }
        close($passwd_fh);
    }
    else {
        Cpanel::PwCache::Helpers::cluck("open($SYSTEM_CONF_DIR/passwd): $!");
    }

    return;
}

sub _cache_pwdata {
    my ( $pwdata, $pwcache_ref ) = @_;

    $pwcache_ref ||= Cpanel::PwCache::Cache::get_cache();

    if ( $pwdata->[2] != 0 || $pwdata->[0] eq 'root' ) {    # special case for multiple uid 0 users
        @{ $pwcache_ref->{ '2' . ':' . $pwdata->[2] } }{ 'cachetime', 'hcachetime', 'contents' } = ( $pwdata->[11], $pwdata->[12], $pwdata );
    }
    @{ $pwcache_ref->{ '0' . ':' . $pwdata->[0] } }{ 'cachetime', 'hcachetime', 'contents' } = ( $pwdata->[11], $pwdata->[12], $pwdata );
    return 1;
}

1;

} # --- END Cpanel/PwCache.pm


{ # --- BEGIN Cpanel/Locale/Utils/User.pm
package Cpanel::Locale::Utils::User;


use strict;
# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::Config::HasCpUserFile  ();
# use Cpanel::PwCache                ();
# use Cpanel::LoadModule             ();

our $DATASTORE_MODULE     = 'Cpanel::DataStore';
our $LOCALE_LEGACY_MODULE = 'Cpanel::Locale::Utils::Legacy';

my $inited_cpdata_user;
my $userlocale = {};
my $logger;

sub _logger {
    require Cpanel::Logger;
    return ( $logger ||= Cpanel::Logger->new() );
}

sub init_cpdata_keys {
    my $user = shift || $Cpanel::user || $ENV{'REMOTE_USER'} || ( $> == 0 ? 'root' : ( Cpanel::PwCache::getpwuid($>) )[0] );

    return if ( defined $inited_cpdata_user && $inited_cpdata_user eq $user );

    if ( !$Cpanel::CPDATA{'LOCALE'} && $user ne 'root' ) {
        require Cpanel::Server::Utils;
        if ( Cpanel::Server::Utils::is_subprocess_of_cpsrvd() && ( $> && $user ne 'cpanel' && $user ne 'cpanellogin' && !-e "/var/cpanel/users/$user" ) ) {
            _logger()->panic("get_handle() called before initcp()");
        }

        if ( $> == 0 || ( $> && $> == Cpanel::PwCache::getpwnam($user) ) ) {
            $Cpanel::CPDATA{'LOCALE'} = get_user_locale($user);
        }
    }

    return ( $inited_cpdata_user = $user );
}

sub clear_user_cache {
    my ($user) = @_;
    return delete $userlocale->{$user};
}

sub get_user_locale {

    my $user       = ( shift || $Cpanel::user || $ENV{'REMOTE_USER'} || ( $> == 0 ? 'root' : ( Cpanel::PwCache::getpwuid($>) )[0] ) );
    my $cpuser_ref = shift;                                                                                                              # not required, just faster if it is passed

    if ( !$user ) {
        require Cpanel::Locale;
        return Cpanel::Locale::get_server_locale() || 'en';
    }

    return $userlocale->{$user} if exists $userlocale->{$user} && !shift;

    if ( $Cpanel::user && $user eq $Cpanel::user && $Cpanel::CPDATA{'LOCALE'} ) {
        return ( $userlocale->{$user} = $Cpanel::CPDATA{'LOCALE'} );
    }

    my $locale;

    if ( $user eq 'root' ) {
        my $root_conf_yaml = ( Cpanel::PwCache::getpwnam('root') )[7] . '/.cpanel_config';
        if ( -e $root_conf_yaml ) {
            Cpanel::LoadModule::load_perl_module($DATASTORE_MODULE);
            my $hr = $DATASTORE_MODULE->can('fetch_ref')->($root_conf_yaml);
            $locale = $hr->{'locale'};
        }
    }
    elsif ( $user eq 'cpanel' ) {
        require Cpanel::Locale;
        $locale = Cpanel::Locale::get_locale_for_user_cpanel();
    }
    else {
        if ( $cpuser_ref || ( Cpanel::Config::HasCpUserFile::has_readable_cpuser_file($user) && ( $cpuser_ref = Cpanel::Config::LoadCpUserFile::loadcpuserfile($user) ) ) ) {
            if ( defined $cpuser_ref->{'LOCALE'} ) {
                $locale = $cpuser_ref->{'LOCALE'};
            }
            elsif ( defined $cpuser_ref->{'LANG'} ) {
                Cpanel::LoadModule::load_perl_module($LOCALE_LEGACY_MODULE);
                $locale = $LOCALE_LEGACY_MODULE->can('map_any_old_style_to_new_style')->( $cpuser_ref->{'LANG'} );
            }
        }
    }

    if ( !$locale ) {
        require Cpanel::Locale;
        return $userlocale->{$user} = Cpanel::Locale::get_server_locale() || 'en';
    }

    $userlocale->{$user} = $locale;

    return $userlocale->{$user};
}

1;

} # --- END Cpanel/Locale/Utils/User.pm


{ # --- BEGIN Cpanel/Cookies.pm
package Cpanel::Cookies;


$Cpanel::Cookies::VERSION = '0.1';

sub get_cookie_hashref_from_string {
    return {} if !defined $_[0];
    return {
        map {
            map {
                s/%([a-fA-F0-9][a-fA-F0-9])/pack('C', hex($1))/eg if -1 != index( $_, '%' );
                $_;
            } split m<=>, $_, 2
        } split( /; /, $_[0] )
    };
}

my $http_cookie_cached;

sub get_cookie_hashref {

    if ( !defined $http_cookie_cached ) {
        $http_cookie_cached = get_cookie_hashref_from_string( $ENV{'HTTP_COOKIE'} );
    }

    return $http_cookie_cached;
}

sub get_cookie_hashref_recache {

    $http_cookie_cached = get_cookie_hashref_from_string( $ENV{'HTTP_COOKIE'} );
    return $http_cookie_cached;
}

1;


} # --- END Cpanel/Cookies.pm


{ # --- BEGIN Cpanel/SafeDir/Read.pm
package Cpanel::SafeDir::Read;


use strict;
use warnings;

sub read_dir {
    my ( $dir, $coderef ) = @_;
    my @contents;
    if ( opendir my $dir_dh, $dir ) {
        @contents = grep { $_ ne '.' && $_ ne '..' } readdir($dir_dh);
        if ($coderef) {
            @contents = grep { $coderef->($_) } @contents;
        }
        closedir $dir_dh;
        return wantarray ? @contents : \@contents;
    }
    return;
}

1;

} # --- END Cpanel/SafeDir/Read.pm


{ # --- BEGIN Cpanel/ArrayFunc/Uniq.pm
package Cpanel::ArrayFunc::Uniq;


use cPstrict;

sub uniq (@list) {

    if ( $INC{'List/Util.pm'} ) {
        no warnings 'redefine';
        *uniq = *List::Util::uniq;
        return List::Util::uniq(@list);
    }
    my %seen;
    return grep { !$seen{$_}++ } @list;
}

1;

} # --- END Cpanel/ArrayFunc/Uniq.pm


{ # --- BEGIN Cpanel/Locale/Utils/Charmap.pm
package Cpanel::Locale::Utils::Charmap;


use cPstrict;

# use Cpanel::ArrayFunc::Uniq ();

sub get_charmap_list ( $root_says_to_make_symlinks = 0, $no_aliases = 0 ) {    ## no critic(Subroutines::ProhibitManyArgs)
    my $args = { 'iconv' => 0, 'unpreferred_aliases' => ( $no_aliases ? 0 : 1 ) };
    if ($root_says_to_make_symlinks) {
        make_symlinks();
    }
    return @{ get_charmaps($args) };
}

sub get_charmaps ( $args = {} ) {
    _validate_args( $args, { map { $_ => 1 } qw( iconv unpreferred_aliases ) } );

    my ( $iconv, $unpreferred_aliases ) = @{$args}{ 'iconv', 'unpreferred_aliases' };
    $iconv //= 1;    # Provide iconv compatibility by default.

    my %charset_aliases   = _get_charset_aliases();
    my %excluded_charmaps = _get_excluded_charmaps( $iconv, $unpreferred_aliases );
    my @raw_charmaps      = ( qw(utf-8 us-ascii), _get_filesystem_charmaps(), ( $unpreferred_aliases ? %charset_aliases : ( values %charset_aliases ) ) );
    my %charmaps;
    for my $cm (@raw_charmaps) {
        $cm =~ tr{A-Z}{a-z};
        my $copy     = $cm;
        my $stripped = ( $copy =~ tr{_.-}{}d );    #prefer "utf-8" over "utf8"
        if ( !exists( $excluded_charmaps{$cm} ) && ( !exists( $charmaps{$copy} ) || $stripped ) ) {
            $charmaps{$copy} = $cm;
        }
    }

    return [ sort ( Cpanel::ArrayFunc::Uniq::uniq( values %charmaps ) ) ];
}

sub make_symlinks {
    return unless $> == 0;
    my %charset_aliases = _get_charset_aliases();
    my $charmapsdir     = _get_charmaps_dir();

    for my $loop ( 1 .. 2 ) {
        for my $key ( keys %charset_aliases ) {
            lstat("$charmapsdir/$key.gz");    # unpreferred
            if ( -e _ ) {
                lstat("$charmapsdir/$charset_aliases{$key}.gz");    # preferred
                if ( !-e _ && !-l _ ) {
                    symlink( "$charmapsdir/$key.gz", "$charmapsdir/$charset_aliases{$key}.gz" );    # unpreferred -> preferred
                }
            }
            elsif ( !-l _ && -e "$charmapsdir/$charset_aliases{$key}.gz" ) {                        # preferred
                symlink( "$charmapsdir/$charset_aliases{$key}.gz", "$charmapsdir/$key.gz" );        # preferred -> unpreferred
            }
        }
    }
    return 1;
}

sub _validate_args ( $args, $possible_args ) {

    if ( my @bad_args = grep { !$possible_args->{$_} } keys %{$args} ) {
        require Cpanel::Exception;
        die Cpanel::Exception::create_raw( 'InvalidParameters', 'The following arguments are invalid: ' . join ', ', @bad_args );
    }
}

sub _get_charmaps_dir {
    state $charmaps_dir = -e '/usr/local/share/i18n/charmaps' ? '/usr/local/share/i18n/charmaps' : '/usr/share/i18n/charmaps';
    return $charmaps_dir;
}

sub _get_charset_aliases {

    return (    # unpreferred => preferred
        'ASCII'             => 'US-ASCII',
        'BIG5-ETEN'         => 'BIG5',
        'CP1251'            => 'WINDOWS-1251',
        'CP1252'            => 'WINDOWS-1252',
        'CP936'             => 'GBK',
        'CP949'             => 'KS_C_5601-1987',    # Note: same preferred as KS_C_5601
        'EUC-CN'            => 'GB2312',
        'KS_C_5601'         => 'KS_C_5601-1987',    # Note: same preferred as CP949
        'SHIFTJIS'          => 'SHIFT_JIS',
        'SHIFTJISX0213'     => 'SHIFT_JISX0213',
        'UNICODE-1-1-UTF-7' => 'UTF-7',             # RFC 1642 (obs.)
        'UTF8'              => 'UTF-8',
        'UTF-8-STRICT'      => 'UTF-8',             # Perl internal use
        'HZ'                => 'HZ-GB-2312',        # RFC 1842
        'GSM0338'           => 'GSM03.38',
    );
}

sub _get_iconv_blacklist {

    return (
        'big5-eten',
        'bs_viewdata',
        'csa_z243.4-1985-gr',
        'gsm03.38',
        'gsm0338',
        'hz',
        'hz-gb-2312',
        'invariant',
        'iso_10646',
        'iso_646.basic',
        'iso_646.irv',
        'iso_6937-2-25',
        'iso_6937-2-add',
        'iso_8859-1,gl',
        'iso_8859-supp',
        'jis_c6220-1969-jp',
        'jis_c6229-1984-a',
        'jis_c6229-1984-b-add',
        'jis_c6229-1984-hand',
        'jis_c6229-1984-hand-add',
        'jis_c6229-1984-kana',
        'jis_x0201',
        'jus_i.b1.003-mac',
        'jus_i.b1.003-serb',
        'ks_c_5601',
        'ks_c_5601-1987',
        'nats-dano-add',
        'nats-sefi-add',
        'nextstep',
        'sami',
        'sami-ws2',
        't.101-g2',
        't.61-7bit',
        'unicode-1-1-utf-7',
        'utf-8-strict',
        'videotex-suppl',
    );
}

sub _get_filesystem_charmaps {
    state @filesystem_charmaps;
    return @filesystem_charmaps if @filesystem_charmaps;

    my $charmapsdir = _get_charmaps_dir();
    if ( opendir my $charmaps_dh, $charmapsdir ) {
        @filesystem_charmaps = map { m{\A([^.].*)[.]gz\z}xms ? $1 : () } readdir $charmaps_dh;
        closedir $charmaps_dh;
    }
    return @filesystem_charmaps;
}

sub _get_excluded_charmaps ( $iconv, $unpreferred_aliases ) {
    my %excluded;
    if ($iconv) {
        for my $bl ( _get_iconv_blacklist() ) {
            $excluded{$bl} = 1;
        }
    }
    if ( !$unpreferred_aliases ) {
        my %charset_aliases = _get_charset_aliases;
        for my $alias ( keys %charset_aliases ) {
            $alias =~ tr{A-Z}{a-z};
            $excluded{$alias} = 1;
        }
    }
    return %excluded;
}

1;


} # --- END Cpanel/Locale/Utils/Charmap.pm


{ # --- BEGIN Cpanel/StringFunc/Case.pm
package Cpanel::StringFunc::Case;


use strict;
use warnings;

our $VERSION = '1.2';

sub ToUpper {
    return unless defined $_[0];
    ( local $_ = $_[0] ) =~ tr/a-z/A-Z/;    # avoid altering $_[0] by making a copy
    return $_;
}

sub ToLower {
    return unless defined $_[0];
    ( local $_ = $_[0] ) =~ tr/A-Z/a-z/;    # avoid altering $_[0] by making a copy
    return $_;
}
1;

} # --- END Cpanel/StringFunc/Case.pm


{ # --- BEGIN Cpanel/Locale/Utils/Legacy.pm
package Cpanel::Locale::Utils::Legacy;


use strict;
use warnings;

# use Cpanel::Locale::Utils::Normalize ();
# use Cpanel::Locale::Utils::Paths     ();

my %oldname_to_locale;
my $loc;

sub _load_oldnames {

    %oldname_to_locale = (
        'turkish'                   => 'tr',
        'traditional-chinese'       => 'zh',
        'thai'                      => 'th',
        'swedish'                   => 'sv',
        'spanish-utf8'              => 'es',
        'spanish'                   => 'es',
        'slovenian'                 => 'sl',
        'simplified-chinese'        => 'zh_cn',
        'russian'                   => 'ru',
        'romanian'                  => 'ro',
        'portuguese-utf8'           => 'pt',
        'portuguese'                => 'pt',
        'polish'                    => 'pl',
        'norwegian'                 => 'no',
        'korean'                    => 'ko',
        'japanese-shift_jis'        => 'ja',       # see Cpanel::Locale::Utils::MkDB::compile_single_legacy_from_legacy_system()
        'japanese-euc-jp'           => 'ja',       # see Cpanel::Locale::Utils::MkDB::compile_single_legacy_from_legacy_system()
        'japanese'                  => 'ja',       # see Cpanel::Locale::Utils::MkDB::compile_single_legacy_from_legacy_system()
        'spanish_latinamerica'      => 'es_419',
        'iberian_spanish'           => 'es_es',
        'italian'                   => 'it',
        'indonesian'                => 'id',
        'hungarian'                 => 'hu',
        'german-utf8'               => 'de',
        'german'                    => 'de',
        'french-utf8'               => 'fr',
        'french'                    => 'fr',
        'finnish'                   => 'fi',
        'english-utf8'              => 'en',
        'english'                   => 'en',
        'dutch-utf8'                => 'nl',
        'dutch'                     => 'nl',
        'chinese'                   => 'zh',
        'bulgarian'                 => 'bg',
        'brazilian-portuguese-utf8' => 'pt_br',
        'brazilian-portuguese'      => 'pt_br',
        'arabic'                    => 'ar',
    );

    {
        no warnings 'redefine';
        *_load_oldnames = sub { };
    }

    return;
}

sub get_legacy_to_locale_map {
    _load_oldnames();
    return \%oldname_to_locale;
}

sub get_legacy_list_from_locale {
    my ($locale) = @_;
    return         if !$locale;
    $locale = 'en' if $locale eq 'en_us' || $locale eq 'i_default';
    _load_oldnames();
    return grep { $oldname_to_locale{$_} eq $locale ? 1 : 0 } keys %oldname_to_locale;
}

sub get_best_guess_of_legacy_from_locale {
    my ( $locale, $always_return_useable ) = @_;
    return         if !$locale && !$always_return_useable;
    $locale = 'en' if $locale eq 'en_us' || $locale eq 'i_default';
    _load_oldnames();
    my @legacy_locale_matches = grep { $oldname_to_locale{$_} eq $locale ? 1 : 0 } keys %oldname_to_locale;
    return $legacy_locale_matches[0] if @legacy_locale_matches;
    return 'english'                 if $always_return_useable;
    return;
}

sub get_legacy_name_list {
    _load_oldnames();

    return sort { $a =~ m/\.local$/ ? $a cmp $b : $b cmp $a } keys %oldname_to_locale;
}

sub get_existing_filesys_legacy_name_list {

    require Cpanel::SafeDir::Read;

    my %args = @_;
    my @extras;
    if ( exists $args{'also_look_in'} && ref $args{'also_look_in'} eq 'ARRAY' ) {
        for my $path ( @{ $args{'also_look_in'} } ) {
            my $copy = $path;
            $copy =~ s/\/lang$//;
            next if !-d "$copy/lang";
            push @extras, Cpanel::SafeDir::Read::read_dir("$copy/lang");
        }
    }

    my @local_less_names;
    my %has_local;
    my @names;

    my $legacy_dir = Cpanel::Locale::Utils::Paths::get_legacy_lang_root();
    for my $name ( grep { $_ !~ m/^\./ } ( $args{'no_root'} ? () : Cpanel::SafeDir::Read::read_dir($legacy_dir) ), @extras ) {
        my $copy = $name;
        if ( $copy =~ s/\.local$// ) {
            $has_local{$copy}++;
        }
        else {
            push @local_less_names, $copy;
        }
    }

    for my $name_localless ( sort { $b cmp $a } @local_less_names ) {
        push @names, exists $has_local{$name_localless} ? ( "$name_localless.local", $name_localless ) : $name_localless;
    }

    return @names;
}

sub get_legacy_root_in_locale_database_root {
    return Cpanel::Locale::Utils::Paths::get_locale_database_root() . '/legacy';
}

sub get_legacy_file_cache_path {
    my ($legacy_file) = @_;
    $legacy_file .= 'cache';
    my $legacy_dir = Cpanel::Locale::Utils::Paths::get_legacy_lang_root();
    $legacy_file =~ s{$legacy_dir}{/var/cpanel/lang.cache};
    return $legacy_file;
}

sub map_any_old_style_to_new_style {
    return wantarray
      ? map { get_new_langtag_of_old_style_langname($_) || $_ } @_
      : get_new_langtag_of_old_style_langname( $_[0] ) || $_[0];
}

my %charset_lookup;

sub _determine_via_disassemble {
    my ( $lcl, $oldlang ) = @_;

    my ( $language, $territory, $encoding, $probable_ext );
    my @parts = split( /[^A-Za-z0-9]+/, $oldlang );    # We can't use Cpanel::CPAN::Locales::normalize_tag since it breaks things into 8 character chunks

    return if @parts == 1;                             # we've already tried just $parts[0] if the split is only 1 item
    return if @parts > 4;                              # if there are more than 4 parts then there is unresolveable data

    if ( !ref($lcl) ) {
        $lcl = Cpanel::CPAN::Locales->new($lcl) or return;
    }

    for my $part (@parts) {
        my $found_part = 0;
        if ( $lcl->get_code_from_language($part) || $lcl->get_language_from_code($part) ) {
            if ($language) {
                if ( !$lcl->get_territory_from_code($part) ) {

                    return;
                }
            }
            else {
                $found_part++;
                $language = $lcl->get_language_from_code($part) ? $part : $lcl->get_code_from_language($part);
            }
        }

        if ( !$found_part && ( $lcl->get_code_from_territory($part) || $lcl->get_territory_from_code($part) ) ) {
            if ($territory) {

                return;
            }
            else {
                $found_part++;
                $territory = $lcl->get_territory_from_code($part) ? $part : $lcl->get_code_from_territory($part);
            }
        }
        if ( !$found_part ) {
            if ( $part eq $parts[$#parts] ) {    # && length($part) < $max_len_for_ext
                $probable_ext = $part;
            }
            else {
                if ( !%charset_lookup ) {
                    require Cpanel::Locale::Utils::Charmap;

                    @charset_lookup{ map { Cpanel::Locale::Utils::Normalize::normalize_tag($_) } Cpanel::Locale::Utils::Charmap::get_charmap_list() } = ();
                }

                if ( $charset_lookup{$part} ) {
                    $found_part++;
                    $encoding = $part;
                }
                else {
                    return;
                }
            }
        }
    }

    if ($encoding) {

    }

    if ($probable_ext) {

    }

    if ($language) {
        if ($territory) {
            return "$language\_$territory";
        }
        else {
            return $language;
        }
    }

    return;
}

sub real_get_new_langtag_of_old_style_langname {
    my ($oldlang) = @_;
    $oldlang = Cpanel::StringFunc::Case::ToLower($oldlang) || "";    # case 34321 item #3

    $oldlang =~ s/\.legacy_duplicate\..+$//;                         # This '.legacy_duplicate. naming hack' is for copying legacy file into a name that maps back to it's new target locale

    if ( !defined $oldlang || $oldlang eq '' || $oldlang =~ m/^\s+$/ ) {

        return;                                                      # return a value ?, what is safe ...
    }
    elsif ( Cpanel::Locale::Utils::Normalize::normalize_tag($oldlang) eq 'default' ) {

        return;                                                      # return 'en' ? could be an incorrect assumption ...
    }
    elsif ( exists $oldname_to_locale{$oldlang} ) {
        return $oldname_to_locale{$oldlang};
    }

    {
        local $@;
        $loc ||= Cpanel::CPAN::Locales->new('en') or die $@;
    }

    my $return;
    if ( $loc->get_language_from_code($oldlang) ) {
        $return = Cpanel::Locale::Utils::Normalize::normalize_tag($oldlang);    # case 34321 item #4
    }
    else {

        my $locale = $loc->get_code_from_language($oldlang);
        if ($locale) {
            $return = $locale;    # case 34321 item #2
        }
        else {
            $return = _determine_via_disassemble( $loc, $oldlang );

            if ( !$return ) {

                local $SIG{'__DIE__'};    # may be made moot by case 50857
                for my $nen ( grep { $_ ne 'en' } sort( $loc->get_language_codes() ) ) {


                    my $loca = Cpanel::CPAN::Locales->new($nen) or next;    # singleton

                    my $locale = $loca->get_code_from_language($oldlang);
                    if ($locale) {
                        $return = $locale;                                  # case 34321 item #2
                        last;
                    }
                    else {
                        $return = _determine_via_disassemble( $loca, $oldlang );
                        last if $return;
                    }
                }
            }
        }
    }

    if ( !$return ) {

        $return = Cpanel::CPAN::Locales::get_i_tag_for_string($oldlang);
    }

    return $return;
}

sub get_new_langtag_of_old_style_langname {
    _load_oldnames();
    require Cpanel::StringFunc::Case;
    require Cpanel::CPAN::Locales;
    $loc = Cpanel::CPAN::Locales->new('en');
    {
        no warnings 'redefine';
        *get_new_langtag_of_old_style_langname = \&real_get_new_langtag_of_old_style_langname;
    }
    goto &real_get_new_langtag_of_old_style_langname;
}

my $legacy_lookup;

sub phrase_is_legacy_key {
    my ($key) = @_;
    if ( !$legacy_lookup ) {
        require 'Cpanel/Locale/Utils/MkDB.pm';    ## no critic qw(Bareword) - hide from perlpkg
        $legacy_lookup = {
            %{ Cpanel::Locale::Utils::MkDB::get_hash_of_legacy_file( Cpanel::Locale::Utils::Paths::get_legacy_lang_root() . '/english-utf8' ) || {} },
            %{ Cpanel::Locale::Utils::MkDB::get_hash_of_legacy_file('/usr/local/cpanel/base/frontend/jupiter/lang/english-utf8') || {} },
        };
    }

    return exists $legacy_lookup->{$key} ? 1 : 0;
}

sub fetch_legacy_lookup {
    return $legacy_lookup if $legacy_lookup;
    phrase_is_legacy_key('');    # ensure $legacy_lookup is loaded
    return $legacy_lookup;
}

sub get_legacy_key_english_value {
    my ($key) = @_;
    if ( phrase_is_legacy_key($key) ) {    # inits $legacy_lookup cache
        return $legacy_lookup->{$key};
    }

    return;
}

1;

} # --- END Cpanel/Locale/Utils/Legacy.pm


{ # --- BEGIN Cpanel/Config/LoadCpUserFile/CurrentUser.pm
package Cpanel::Config::LoadCpUserFile::CurrentUser;


use strict;
use warnings;

# use Cpanel::Config::LoadCpUserFile ();



my $_cpuser_ref_singleton;
my $_cpuser_user;

sub load {
    my ($user) = @_;
    if ( $_cpuser_user && $_cpuser_user eq $user ) {
        return $_cpuser_ref_singleton;
    }
    $_cpuser_user = $user;
    return ( $_cpuser_ref_singleton = Cpanel::Config::LoadCpUserFile::load($user) );
}

sub _reset {
    $_cpuser_ref_singleton = undef;
    $_cpuser_user          = undef;

    return;
}

1;

} # --- END Cpanel/Config/LoadCpUserFile/CurrentUser.pm


{ # --- BEGIN Cpanel/YAML/Syck.pm
package Cpanel::YAML::Syck;



use YAML::Syck ();

sub _init {
    $YAML::Syck::LoadBlessed = 0;
    {
        no warnings 'redefine';
        *Cpanel::YAML::Syck::_init = sub { };
    }
    return;
}

_init();

1;

} # --- END Cpanel/YAML/Syck.pm


{ # --- BEGIN Cpanel/FileUtils/TouchFile.pm
package Cpanel::FileUtils::TouchFile;


use strict;
use warnings;


use constant {
    _ENOENT => 2,
};

my $logger;

our $VERSION = '1.3';

sub _log {
    my ( $level, $msg ) = @_;

    require Cpanel::Logger;
    $logger ||= Cpanel::Logger->new();
    $logger->$level($msg);

    return;
}

my $mtime;

sub touchfile {
    my ( $file, $verbose, $fail_ok ) = @_;

    if ( !defined $file ) {
        _log( 'warn', "touchfile called with undefined file" );
        return;
    }

    my $mtime;

    if ( utime undef, undef, $file ) {
        return 1;
    }
    elsif ( $! != _ENOENT() ) {
        _log( 'warn', "utime($file) as $>: $!" );

        $mtime = -e $file ? ( stat _ )[9] : 0;    # for warnings-safe numeric comparison

        if ( !$mtime && $! != _ENOENT ) {
            _log( 'warn', "Failed to stat($file) as $>: $!" );
            return;
        }
    }

    $mtime = ( stat $file )[9] // 0;

    if ( open my $fh, '>>', $file ) {    # append so we don't wipe out contents
        my $mtime_after_open = ( stat $fh )[9] || 0;    # for warnings safe numeric comparison
        return 1 if $mtime != $mtime_after_open;        # in case open does not change it, see comment below
    }
    else {
        _log( 'warn', "Failed to open(>> $file) as $>: $!" ) unless $fail_ok;
    }

    if ($fail_ok) { return; }

    my $at_this_point = ( stat $file )[9] || 0;    # for warnings safe numeric comparison
    if ( $mtime == $at_this_point ) {

        my $new_at_this_point = ( stat $file )[9] || 0;    # for warnings safe numeric comparison
        if ( $mtime == $new_at_this_point ) {
            if ($verbose) {
                _log( 'info', 'Trying to do system “touch” command!' );
            }
            if ( system( 'touch', $file ) != 0 ) {
                if ($verbose) {
                    _log( 'info', 'system method 1 failed.' );
                }
            }
        }
    }

    if ( !-e $file ) {    # obvisouly it didn't touch it if it doesn't exist...
        _log( 'warn', "Failed to create $file: $!" );
        return;
    }
    else {

        my $after_all_that = ( stat $file )[9] || 0;    # for warnings safe numeric comparison
        if ( $mtime && $mtime == $after_all_that ) {
            _log( 'warn', "mtime of “$file” not changed!" );
            return;
        }
        return 1;
    }
}

1;

} # --- END Cpanel/FileUtils/TouchFile.pm


{ # --- BEGIN Cpanel/PwUtils.pm
package Cpanel::PwUtils;


use strict;
use warnings;

# use Cpanel::Exception ();
# use Cpanel::PwCache   ();

sub normalize_to_uid {
    my ($user) = @_;

    if ( !length $user ) {
        die Cpanel::Exception::create( 'MissingParameter', 'Supply a username or a user ID.' );
    }

    return $user if $user !~ tr{0-9}{}c;    # Only has numbers so its a uid

    my $uid = Cpanel::PwCache::getpwnam_noshadow($user);
    if ( !defined $uid ) {
        die Cpanel::Exception::create( 'UserNotFound', [ name => $user ] );
    }

    return $uid;
}

1;

} # --- END Cpanel/PwUtils.pm


{ # --- BEGIN Cpanel/AccessIds/Normalize.pm
package Cpanel::AccessIds::Normalize;


use strict;
use warnings;

# use Cpanel::ArrayFunc::Uniq ();
# use Cpanel::PwCache         ();
# use Cpanel::PwUtils         ();
# use Cpanel::Exception       ();



sub normalize_user_and_groups {
    my ( $user, @groups ) = @_;

    if ( ( scalar @groups == 1 && !defined $groups[0] ) || ( scalar @groups > 1 && scalar( grep { !defined } @groups ) ) ) {
        require Cpanel::Carp;    # no load module for memory
        die Cpanel::Carp::safe_longmess("Undefined group passed to normalize_user_and_groups");
    }
    my $uid;

    if ( defined $user && $user !~ tr{0-9}{}c ) {
        if ( scalar @groups == 1 && $groups[0] !~ tr{0-9}{}c ) {    # we already have a gid
            return ( $user, $groups[0] );
        }
        $uid = $user;

        if ( scalar @groups == 1 && $groups[0] !~ tr{0-9}{}c ) {    # we already have a gid
            return ( $uid, $groups[0] );
        }
    }
    elsif ( !scalar @groups ) {
        ( $uid, @groups ) = ( Cpanel::PwCache::getpwnam_noshadow($user) )[ 2, 3 ];

        if ( !defined $uid ) {
            die Cpanel::Exception::create( 'UserNotFound', [ name => $user ] );
        }
        return ( $uid, @groups );
    }
    else {
        $uid = Cpanel::PwUtils::normalize_to_uid($user);
    }

    my @gids =
      @groups
      ? ( map { !tr{0-9}{}c ? $_ : scalar( ( getgrnam $_ )[2] ) } @groups )
      : ( ( Cpanel::PwCache::getpwuid_noshadow($uid) )[3] );

    if ( scalar @gids > 2 ) {
        return ( $uid, Cpanel::ArrayFunc::Uniq::uniq(@gids) );
    }
    elsif ( scalar @gids == 2 && $gids[0] eq $gids[1] ) {
        return ( $uid, $gids[0] );
    }

    return ( $uid, @gids );
}


sub normalize_code_user_groups {
    my @args = @_;

    my $code_index;
    for my $i ( 0 .. $#args ) {
        if ( ref $args[$i] eq 'CODE' ) {
            $code_index = $i;
            last;
        }
    }

    die "No coderef found!" if !defined $code_index;

    my $code = splice( @args, $code_index, 1 );

    return ( $code, normalize_user_and_groups( grep { defined } @args ) );
}

1;

} # --- END Cpanel/AccessIds/Normalize.pm


{ # --- BEGIN Cpanel/AccessIds/Utils.pm
package Cpanel::AccessIds::Utils;


use strict;
use warnings;

# use Cpanel::ArrayFunc::Uniq ();
# use Cpanel::Debug           ();

sub normalize_user_and_groups {
    require Cpanel::AccessIds::Normalize;
    goto \&Cpanel::AccessIds::Normalize::normalize_user_and_groups;
}

sub normalize_code_user_groups {
    require Cpanel::AccessIds::Normalize;
    goto \&Cpanel::AccessIds::Normalize::normalize_code_user_groups;
}

sub set_egid {
    my @gids = @_;

    if ( !@gids ) {
        Cpanel::Debug::log_die("No arguments passed to set_egid()!");
    }

    if ( scalar @gids > 1 ) {
        @gids = Cpanel::ArrayFunc::Uniq::uniq(@gids);
    }

    _check_positive_int($_) for @gids;

    my $new_egid = join( q{ }, $gids[0], @gids );

    return _set_var( \$), 'EGID', $new_egid );
}

sub set_rgid {
    my ( $gid, @extra_gids ) = @_;

    if (@extra_gids) {
        Cpanel::Debug::log_die("RGID can only be set to a single value! (Do you want set_egid()?)");
    }

    _check_positive_int($gid);

    return _set_var( \$(, 'RGID', $gid );
}

sub set_euid {
    my ($uid) = @_;

    _check_positive_int($uid);

    return _set_var( \$>, 'EUID', $uid );
}

sub set_ruid {
    my ($uid) = @_;

    _check_positive_int($uid);

    return _set_var( \$<, 'RUID', $uid );
}

sub _check_positive_int {
    if ( !length $_[0] || $_[0] =~ tr{0-9}{}c ) {
        Cpanel::Debug::log_die("“$_[0] is not a positive integer!");
    }

    return 1;
}

sub _set_var {
    my ( $var_r, $name, $desired_value ) = @_;

    my $old_value = $$var_r;
    $$var_r = $desired_value;

    return $desired_value eq $$var_r ? 1 : validate_var_set(
        $name,             # The name of the value like 'RUID'
        $desired_value,    # The value we wanted it to be set to
        $$var_r,           # Deferenced variable being set, ex $<
        $old_value         # The value before we set it.
    );
}

sub validate_var_set {
    my ( $name, $desired_value, $new_value, $old_value ) = @_;

    my $error;



    if ( $new_value =~ tr/ // ) {


        my ( $desired_first, @desired_parts ) = split( ' ', $desired_value );
        my ( $new_first,     @new_parts )     = split( ' ', $new_value );

        if ( $new_first != $desired_first ) {
            $error = 1;
        }
        elsif ( @desired_parts && @new_parts ) {
            if ( scalar @desired_parts == 1 && scalar @new_parts == 1 ) {
                if ( $new_parts[0] != $desired_parts[0] ) {
                    $error = 1;
                }
            }
            else {
                @desired_parts = sort { $a <=> $b } Cpanel::ArrayFunc::Uniq::uniq(@desired_parts);
                @new_parts     = sort { $a <=> $b } Cpanel::ArrayFunc::Uniq::uniq(@new_parts);

                for my $i ( 0 .. $#desired_parts ) {
                    if ( $new_parts[$i] != $desired_parts[$i] ) {
                        $error = 1;
                        last;
                    }
                }
            }
        }
    }
    else {
        if ( $new_value != $desired_value ) {
            $error = 1;
        }
    }

    return 1 if !$error;

    if ( defined $old_value ) {
        Cpanel::Debug::log_die("Failed to change $name from “$old_value” to “$desired_value”: $!");
    }
    Cpanel::Debug::log_die("Failed to change $name to “$desired_value”: $!");

    return 0;    #not reached
}

1;

} # --- END Cpanel/AccessIds/Utils.pm


{ # --- BEGIN Cpanel/AccessIds/ReducedPrivileges.pm
package Cpanel::AccessIds::ReducedPrivileges;


use strict;
use warnings;

# use Cpanel::Debug                ();
# use Cpanel::AccessIds::Utils     ();
# use Cpanel::AccessIds::Normalize ();

our $PRIVS_REDUCED = 0;


sub new {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $class = shift;

    if ( $class ne __PACKAGE__ ) {
        Cpanel::Debug::log_die("Attempting to drop privileges as '$class'.");
    }

    my ( $uid, @gids ) = Cpanel::AccessIds::Normalize::normalize_user_and_groups(@_);

    _allowed_to_reduce_privileges();

    _prevent_dropping_to_root( $uid, @gids );

    my $self = {
        'uid'     => $>,
        'gid'     => $),
        'new_uid' => $uid,
        'new_gid' => join( q< >, @gids ),
    };

    _reduce_privileges( $uid, @gids );

    $PRIVS_REDUCED = 1;

    return bless $self;
}

sub DESTROY {
    my ($self) = @_;

    _allowed_to_restore_privileges( $self->{'new_uid'}, $self->{'new_gid'} );

    return _restore_privileges( $self->{'uid'}, $self->{'gid'} );
}

sub call_as_user {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ( $code, $uid, $gid, @supplemental_gids ) = Cpanel::AccessIds::Normalize::normalize_code_user_groups(@_);

    _prevent_dropping_to_root( $uid, $gid );

    if ( !$code ) {
        Cpanel::Debug::log_die("No code reference supplied.");
    }

    _allowed_to_reduce_privileges();

    my ( $saved_uid, $saved_gid ) = ( $>, $) );

    _reduce_privileges( $uid, $gid, @supplemental_gids );

    local $PRIVS_REDUCED = 1;

    my ( $scalar, @list );

    if (wantarray) {    #list context
        @list = eval { $code->(); };
    }
    elsif ( defined wantarray ) {    #scalar context
        $scalar = eval { $code->(); };
    }
    else {                           #void context
        eval { $code->(); };
    }

    my $ex = $@;
    _restore_privileges( $saved_uid, $saved_gid );

    die $ex if $ex;
    return wantarray ? @list : $scalar;
}


sub _allowed_to_reduce_privileges {
    if ( $< != 0 ) {
        Cpanel::Debug::log_die("Attempting to drop privileges as a normal user with RUID $<");
    }

    if ( $> != 0 ) {
        Cpanel::Debug::log_die("Attempting to drop privileges as a normal user with EUID $>");
    }

    return 1;
}

sub _reduce_privileges {
    my ( $uid, $gid, @supplemental_gids ) = @_;

    Cpanel::AccessIds::Utils::set_egid( $gid, @supplemental_gids );
    Cpanel::AccessIds::Utils::set_euid($uid);

    return 1;
}

sub _prevent_dropping_to_root {


    if ( grep { !$_ } @_ ) {
        Cpanel::Debug::log_die("Attempting to drop privileges to root.");
    }

    return 1;
}

sub _allowed_to_restore_privileges {
    my ( $uid, $gid ) = @_;

    if ( $< != 0 ) {
        Cpanel::Debug::log_die("Attempting to restore privileges as a normal user with RUID $<");
    }

    if ( $> != $uid ) {
        Cpanel::Debug::log_warn("EUID ($>) does not match expected reduced user ($uid)");
    }

    my ( $first_egid, $first_given_gid ) = ( $), $gid );
    $_ = ( split m{ } )[0] for ( $first_egid, $first_given_gid );

    if ( int $first_egid != int $first_given_gid ) {
        Cpanel::Debug::log_warn("EGID ($)) does not match expected reduced user ($gid)");
    }
}

sub _restore_privileges {
    my ( $saved_uid, $saved_gid ) = @_;

    Cpanel::AccessIds::Utils::set_euid($saved_uid);
    Cpanel::AccessIds::Utils::set_egid( split m{ }, $saved_gid );

    $PRIVS_REDUCED = 0;

    return 1;
}

1;

} # --- END Cpanel/AccessIds/ReducedPrivileges.pm


{ # --- BEGIN Cpanel/DataStore.pm
package Cpanel::DataStore;


use strict;
use warnings;
# use Cpanel::Debug ();

sub store_ref {
    my ( $file, $outof_ref, $perm ) = @_;

    require Cpanel::YAML::Syck;

    $YAML::Syck::ImplicitTyping = 0;

    local $YAML::Syck::SingleQuote;
    local $YAML::Syck::SortKeys;

    $YAML::Syck::SingleQuote = 1;
    $YAML::Syck::SortKeys    = 1;

    if ( ref($file) ) {

        my $yaml_string = YAML::Syck::Dump($outof_ref);

        print( {$file} _format($yaml_string) ) || return;
        return $file;
    }

    if ( ref($perm) eq 'ARRAY' && !-l $file && !-e $file ) {
        require Cpanel::FileUtils::TouchFile;    # or use() ?

        my $touch_chmod = sub {
            if ( !Cpanel::FileUtils::TouchFile::touchfile($file) ) {
                Cpanel::Debug::log_info("Could not touch \xE2\x80\x9C$file\xE2\x80\x9D: $!");
                return;
            }

            if ( $perm->[0] ) {
                if ( !chmod( oct( $perm->[0] ), $file ) ) {
                    Cpanel::Debug::log_info("Could not chmod \xE2\x80\x9C$file\xE2\x80\x9D to \xE2\x80\x9C$perm->[0]\xE2\x80\x9D: $!");
                    return;
                }
            }

            return 1;
        };

        if ( $> == 0 && $perm->[1] && $perm->[1] ne 'root' ) {
            require Cpanel::AccessIds::ReducedPrivileges;    # or use() ?
            Cpanel::AccessIds::ReducedPrivileges::call_as_user( $perm->[1], $touch_chmod ) || return;
        }
        else {
            $touch_chmod->() || return;
        }
    }

    if ( open my $yaml_out, '>', $file ) {
        my $yaml_string = YAML::Syck::Dump($outof_ref);
        print {$yaml_out} _format($yaml_string);
        close $yaml_out;
        return 1;
    }
    else {
        Cpanel::Debug::log_warn("Could not open file '$file' for writing: $!");
        return;
    }
}

sub fetch_ref {
    my ( $file, $is_array ) = @_;

    my $fetch_ref = load_ref($file);

    my $data_type = ref $fetch_ref;
    my $data      = $data_type ? $fetch_ref : undef;
    $data_type ||= 'UNDEF';

    if ( $is_array && $data_type ne 'ARRAY' ) {
        return [];
    }
    elsif ( !$is_array && $data_type ne 'HASH' ) {
        return {};
    }

    return $data;
}

sub load_ref {
    my ( $file, $into_ref ) = @_;
    return if ( !-e $file || -z _ );

    require Cpanel::YAML::Syck;

    $YAML::Syck::ImplicitTyping = 0;

    my $struct;

    if ( ref($file) ) {

        local $!;
        $struct = eval {
            local $/;
            local $SIG{__WARN__};
            local $SIG{__DIE__};
            ( YAML::Syck::Load(<$file>) )[0];
        };
        Cpanel::Debug::log_warn("Error loading YAML data: $!") if ( !$struct );
    }
    elsif ( open my $yaml_in, '<', $file ) {
        local $!;
        $struct = eval {
            local $/;
            local $SIG{__WARN__};
            local $SIG{__DIE__};
            ( YAML::Syck::Load(<$yaml_in>) )[0];
        };
        Cpanel::Debug::log_warn("Error loading YAML data: $!") if ( !$struct );
        close $yaml_in;
    }
    else {
        my $err = $!;
        Cpanel::Debug::log_warn("Could not open file '$file' for reading: $err");
        return;
    }

    if ( !$struct ) {
        Cpanel::Debug::log_warn("Failed to load YAML data from file $file");
        return;
    }

    if ( defined $into_ref ) {
        my $type      = ref $into_ref;
        my $yaml_type = ref $struct;
        if ( $yaml_type ne $type ) {
            Cpanel::Debug::log_warn("Invalid data type from file $file! YAML type $yaml_type does not match expected type $type. Data ignored!");
            return;    # if we want an empty ref on failure use fetch_ref()
        }

        if ( $yaml_type eq 'HASH' ) {
            %{$into_ref} = %{$struct};
        }
        elsif ( $yaml_type eq 'ARRAY' ) {
            @{$into_ref} = @{$struct};
        }
        else {
            Cpanel::Debug::log_warn("YAML in '$file' is not a hash or array reference");
            return;    # if we want an empty ref on failure use fetch_ref()
        }

        return $into_ref;
    }

    return $struct;
}

sub edit_datastore {
    my ( $file, $editor_cr, $is_array ) = @_;

    if ( ref $editor_cr ne 'CODE' ) {
        Cpanel::Debug::log_warn('second arg needs to be a coderef');
        return;
    }

    my $ref = $is_array ? [] : {};

    if ( !-e $file ) {
        Cpanel::Debug::log_info("Data store file $file does not exist. Attempting to create empty datastore.");
        store_ref( $file, $ref );
    }

    if ( load_ref( $file, $ref ) ) {
        if ( $editor_cr->($ref) ) {
            if ( !store_ref( $file, $ref ) ) {
                Cpanel::Debug::log_warn("Modifications to file $file could not be saved");
                return;
            }
        }
    }
    else {
        Cpanel::Debug::log_warn("Could not load datastore $file");
        return;
    }

    return 1;
}

sub _format {
    my ($s) = @_;

    $s =~ s/[ \t]+$//mg;
    return __grapheme_to_character($s);
}

sub __grapheme_to_character {
    my ($yaml_string) = @_;

    $yaml_string = quotemeta($yaml_string);
    $yaml_string =~ s/\\{2}x/\\x/g;
    $yaml_string = eval qq{"$yaml_string"};

    return $yaml_string;
}

1;


} # --- END Cpanel/DataStore.pm


{ # --- BEGIN Cpanel/LoadFile.pm
package Cpanel::LoadFile;



use strict;
use warnings;

# use Cpanel::Exception          ();
# use Cpanel::Fcntl::Constants   ();
# use Cpanel::LoadFile::ReadFast ();

sub loadfileasarrayref {
    my $fileref = _load_file( shift, { 'array_ref' => 1 } );
    return ref $fileref eq 'ARRAY' ? $fileref : undef;
}

sub loadbinfile {
    my $fileref = _load_file( shift, { 'binmode' => 1 } );
    return ref $fileref eq 'SCALAR' ? $$fileref : undef;
}

sub slurpfile {
    my $fh      = shift;
    my $fileref = _load_file(shift);
    if ( ref $fileref eq 'SCALAR' ) {
        print {$fh} $$fileref;
    }
    return;
}

sub loadfile {
    my $fileref = _load_file(@_);
    return ref $fileref eq 'SCALAR' ? $$fileref : undef;
}

sub loadfile_r {
    my ( $file, $arg_ref ) = @_;

    if ( open my $lf_fh, '<:stdio', $file ) {
        if ( $arg_ref->{'binmode'} ) { binmode $lf_fh; }

        my $data;
        if ( $arg_ref->{'array_ref'} ) {
            @{$data} = readline $lf_fh;
            close $lf_fh;
            return $data;
        }
        else {
            $data = '';
            local $@;

            eval { Cpanel::LoadFile::ReadFast::read_all_fast( $lf_fh, $data ); };
            return $@ ? undef : \$data;
        }
    }

    return;
}

*_load_file = *loadfile_r;

sub _open {
    return _open_if_exists( $_[0] ) || die Cpanel::Exception::create( 'IO::FileNotFound', [ path => $_[0], error => _ENOENT() ] );
}

sub _open_if_exists {
    local $!;
    open my $fh, '<:stdio', $_[0] or do {

        if ( $! == _ENOENT() ) {
            return undef;
        }
        die Cpanel::Exception::create( 'IO::FileOpenError', [ path => $_[0], error => $!, mode => '<' ] );
    };

    return $fh;
}

sub load_if_exists {
    my $ref = _load_r( \&_open_if_exists, @_ );
    return $ref ? $$ref : undef;
}

sub load_r_if_exists {
    return _load_r( \&_open_if_exists, @_ );
}

sub load {
    return ${ _load_r( \&_open, @_ ) };
}

sub load_r {
    return _load_r( \&_open,, @_ );
}

sub _load_r {
    my ( $open_coderef, $path, $offset, $length ) = @_;

    my $fh = $open_coderef->($path) or return undef;

    local $!;

    if ($offset) {
        sysseek( $fh, $offset, $Cpanel::Fcntl::Constants::SEEK_SET );

        if ($!) {
            die Cpanel::Exception::create(
                'IO::FileSeekError',
                [
                    path     => $path,
                    position => $offset,
                    whence   => $Cpanel::Fcntl::Constants::SEEK_SET,
                    error    => $!,
                ]
            );
        }
    }

    my $data = q<>;

    if ( !defined $length ) {

        my $bytes_read = Cpanel::LoadFile::ReadFast::read_fast( $fh, $data, Cpanel::LoadFile::ReadFast::READ_CHUNK );

        if ( $bytes_read == Cpanel::LoadFile::ReadFast::READ_CHUNK ) {
            my $file_size = -f $fh && -s _;

            if ($file_size) {

                Cpanel::LoadFile::ReadFast::read_fast( $fh, $data, $file_size, length $data ) // die _read_err($path);
            }
        }

        Cpanel::LoadFile::ReadFast::read_all_fast( $fh, $data );
    }
    else {
        my $togo = $length;
        my $bytes_read;
        while ( $bytes_read = Cpanel::LoadFile::ReadFast::read_fast( $fh, $data, $togo, length $data ) && length $data < $length ) {
            $togo -= $bytes_read;
        }
    }

    if ($!) {
        die Cpanel::Exception::create( 'IO::FileReadError', [ path => $path, error => $! ] );
    }

    close $fh or warn "The system failed to close the file “$path” because of an error: $!";

    return \$data;
}

sub _ENOENT { return 2; }
1;

} # --- END Cpanel/LoadFile.pm


{ # --- BEGIN Cpanel/StringFunc/Trim.pm
package Cpanel::StringFunc::Trim;


use strict;
use warnings;

$Cpanel::StringFunc::Trim::VERSION = '1.02';

my %ws_chars = ( "\r" => undef, "\n" => undef, " " => undef, "\t" => undef, "\f" => undef );

sub trim {
    my ( $str, $totrim ) = @_;
    $str = rtrim( ltrim( $str, $totrim ), $totrim );
    return $str;
}

sub ltrim {
    my ( $str, $totrim ) = @_;
    $str =~ s/^$totrim*//;
    return $str;
}

sub rtrim {
    my ( $str, $totrim ) = @_;
    $str =~ s/$totrim*$//;
    return $str;
}

sub endtrim {
    my ( $str, $totrim ) = @_;

    if ( substr( $str, ( length($totrim) * -1 ), length($totrim) ) eq $totrim ) {
        return substr( $str, 0, ( length($str) - length($totrim) ) );
    }
    return $str;
}

sub begintrim {
    my ( $str, $totrim ) = @_;

    if (
        defined $str && defined $totrim    # .
        && substr( $str, 0, length($totrim) ) eq $totrim
    ) {
        return substr( $str, length($totrim) );
    }
    return $str;
}

sub ws_trim {
    my ($this) = @_;

    return unless defined $this;

    my $fix = ref $this eq 'SCALAR' ? $this : \$this;

    return unless defined $$fix;

    if ( $$fix =~ tr{\r\n \t\f}{} ) {
        ${$fix} =~ s/^\s+// if exists $ws_chars{ substr( $$fix, 0,  1 ) };
        ${$fix} =~ s/\s+$// if exists $ws_chars{ substr( $$fix, -1, 1 ) };
    }
    return ${$fix};
}

sub ws_trim_array {
    my $ar = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];    # [@_] :: copy @_ w/ out unpack first: !! not \@_ in this case !!
    foreach my $idx ( 0 .. scalar( @{$ar} ) - 1 ) {
        $ar->[$idx] = ws_trim( $ar->[$idx] );
    }
    return wantarray ? @{$ar} : $ar;
}

sub ws_trim_hash_values {
    my $hr = ref $_[0] eq 'HASH' ? $_[0] : {@_};     # {@_} :: copy @_ w/ out unpack first:
    foreach my $key ( keys %{$hr} ) {
        $hr->{$key} = ws_trim( $hr->{$key} );
    }
    return wantarray ? %{$hr} : $hr;
}

1;


} # --- END Cpanel/StringFunc/Trim.pm


{ # --- BEGIN Cpanel/SafeDir/MK.pm
package Cpanel::SafeDir::MK;


use strict;
use warnings;

# use Cpanel::Debug ();

my $DEFAULT_PERMISSIONS = 0755;


sub safemkdir_or_die {
    my ( $dir, $mode, $created ) = @_;
    my $ok = safemkdir( $dir, $mode, $created );
    if ( !$ok ) {
        my $error = $!;
        require Cpanel::Exception;
        die Cpanel::Exception::create(
            'IO::DirectoryCreateError',
            [
                path  => $dir,
                error => $error,
            ]
        );
    }
    return $ok;
}


sub safemkdir {    ## no critic(Subroutines::ProhibitExcessComplexity)  -- Refactoring this function is a project, not a bug fix
    my ( $dir, $mode, $errors, $created ) = @_;

    if ( defined $mode ) {
        if ( $mode eq '' ) {
            $mode = undef;
        }
        elsif ( index( $mode, '0' ) == 0 ) {
            if ( length $mode < 3 || $mode =~ tr{0-7}{}c || !defined oct $mode ) {
                $mode = $DEFAULT_PERMISSIONS;
            }
            else {
                $mode = oct($mode);
            }
        }
        elsif ( $mode =~ tr{0-9}{}c ) {
            $mode = $DEFAULT_PERMISSIONS;
        }
    }
    $dir =~ tr{/}{}s;

    my $default = '';
    if ( index( $dir, '/' ) == 0 ) {
        $default = '/';
    }
    elsif ( $dir eq '.' || $dir eq './' ) {
        if ( !-l $dir && defined $mode ) {
            return chmod $mode, $dir;
        }
        return 1;
    }
    else {
        substr( $dir, 0, 2, '' ) if index( $dir, './' ) == 0;
    }

    if ( _has_dot_dot($dir) ) {
        Cpanel::Debug::log_warn("Possible improper directory $dir specified");
        my @dir_parts = split m{/}, $dir;
        my @good_parts;
        my $first;
        foreach my $part (@dir_parts) {
            next if ( !defined $part || $part eq '' );
            next if $part eq '.';
            if ( $part eq '..' ) {
                if ( !$first || !@good_parts ) {
                    Cpanel::Debug::log_warn("Will not proceed above first directory part $first");
                    return 0;
                }
                if ( $first eq $good_parts[$#good_parts] ) {
                    undef $first;
                }
                pop @good_parts;
                next;
            }
            elsif ( $part !~ tr{.}{}c ) {
                Cpanel::Debug::log_warn("Total stupidity found in directory $dir");
                return 0;
            }
            push @good_parts, $part;
            if ( !$first ) { $first = $part }
        }
        $dir = $default . join '/', @good_parts;
        if ( !$dir ) {
            Cpanel::Debug::log_warn("Could not validate given directory");
            return;
        }
        Cpanel::Debug::log_warn("Improper directory updated to $dir");
    }

    if ( -d $dir ) {
        if ( !-l $dir && defined $mode ) {
            return chmod $mode, $dir;
        }
        return 1;
    }
    elsif ( -e _ ) {
        Cpanel::Debug::log_warn("$dir was expected to be a directory!");
        require Errno;
        $! = Errno::ENOTDIR();    ## no critic qw(Variables::RequireLocalizedPunctuationVars) -- for legacy reasons
        return 0;
    }

    my @dir_parts = split m{/}, $dir;

    if ( scalar @dir_parts > 100 ) {
        Cpanel::Debug::log_warn("Encountered excessive directory length. This should never happen.");
        return 0;
    }
    my $returnvalue;
    foreach my $i ( 0 .. $#dir_parts ) {
        my $newdir = join( '/', @dir_parts[ 0 .. $i ] );
        next if $newdir eq '';
        my $is_dir = -d $newdir;
        my $exists = -e _;

        if ( !$exists ) {
            my $local_mode = defined $mode ? $mode : $DEFAULT_PERMISSIONS;
            if ( mkdir( $newdir, $local_mode ) ) {
                push @{$created}, $newdir if $created;
                $returnvalue++;
            }
            else {
                Cpanel::Debug::log_warn("mkdir $newdir failed: $!");
                return;
            }
        }
        elsif ( !$is_dir ) {
            Cpanel::Debug::log_warn("Encountered non-directory $newdir in path of $dir: $!");
            require Errno;
            $! = Errno::ENOTDIR();    ## no critic qw(Variables::RequireLocalizedPunctuationVars) -- for legacy reasons
            last;
        }
    }
    return $returnvalue;
}

sub _has_dot_dot {    ## no critic qw(RequireArgUnpacking)
    return 1 if $_[0] eq '..';
    return 1 if -1 != index( $_[0], '/../' );
    return 1 if 0 == index( $_[0], '../' );
    return 1 if ( length( $_[0] ) - 3 ) == rindex( $_[0], '/..' );

    return 0;
}

1;

} # --- END Cpanel/SafeDir/MK.pm


{ # --- BEGIN Cpanel/Locale/Utils/3rdparty.pm
package Cpanel::Locale::Utils::3rdparty;


use strict;
use warnings;

our %cpanel_provided = (
    'de'               => 1,
    'en'               => 1,
    'es_es'            => 1,
    'i_cpanel_snowmen' => 1,
    'ru'               => 1,
    'ja'               => 1,
);

my %locale_to_3rdparty;

sub _load_3rdparty {
    return if (%locale_to_3rdparty);

    %locale_to_3rdparty = (
        'ar' => {
            'analog'    => 'us',
            'awstats'   => 'ar',
            'webalizer' => 'english'
        },
        'bg' => {
            'analog'    => 'bg',
            'awstats'   => 'bg',
            'webalizer' => 'english'
        },
        'bn' => {
            'analog'    => 'us',
            'awstats'   => 'en',
            'webalizer' => 'english'
        },
        'de' => {
            'analog'    => 'de',
            'awstats'   => 'de',
            'webalizer' => 'german'
        },
        'en' => {
            'analog'    => 'us',
            'awstats'   => 'en',
            'webalizer' => 'english'
        },
        'es' => {
            'analog'    => 'es',
            'awstats'   => 'es',
            'webalizer' => 'spanish'
        },
        'es_es' => {
            'analog'    => 'es',
            'awstats'   => 'es',
            'webalizer' => 'spanish'
        },
        'fi' => {
            'analog'    => 'fi',
            'awstats'   => 'fi',
            'webalizer' => 'finnish'
        },
        'fr' => {
            'analog'    => 'fr',
            'awstats'   => 'fr',
            'webalizer' => 'french'
        },
        'hi' => {
            'analog'    => 'us',
            'awstats'   => 'en',
            'webalizer' => 'english'
        },
        'hu' => {
            'analog'    => 'hu',
            'awstats'   => 'hu',
            'webalizer' => 'hungarian'
        },
        'id' => {
            'analog'    => 'us',
            'awstats'   => 'id',
            'webalizer' => 'indonesian'
        },
        'it' => {
            'analog'    => 'it',
            'awstats'   => 'it',
            'webalizer' => 'italian'
        },
        'ja' => {
            'analog'    => 'jpu',       # appears to be the UTF-8 one
            'awstats'   => 'jp',
            'webalizer' => 'japanese'
        },
        'ko' => {
            'analog'    => 'us',
            'awstats'   => 'ko',
            'webalizer' => 'korean'
        },
        'nl' => {
            'analog'    => 'nl',
            'awstats'   => 'nl',
            'webalizer' => 'dutch'
        },
        'no' => {
            'analog'    => 'no',
            'awstats'   => 'en',
            'webalizer' => 'norwegian'
        },
        'pl' => {
            'analog'    => 'pl',
            'awstats'   => 'pl',
            'webalizer' => 'polish'
        },
        'pt' => {
            'analog'    => 'pt',
            'awstats'   => 'pt',
            'webalizer' => 'portuguese'
        },
        'pt_br' => {
            'analog'    => 'pt',
            'awstats'   => 'pt',
            'webalizer' => 'portuguese_brazil'
        },
        'ro' => {
            'analog'    => 'ro',
            'awstats'   => 'ro',
            'webalizer' => 'romanian'
        },
        'ru' => {
            'analog'    => 'ru',
            'awstats'   => 'ru',
            'webalizer' => 'russian'
        },
        'sl' => {
            'analog'    => 'us',
            'awstats'   => 'en',
            'webalizer' => 'slovene'
        },
        'sv' => {
            'analog'    => 'us',
            'awstats'   => 'en',
            'webalizer' => 'swedish'
        },
        'th' => {
            'analog'    => 'us',
            'awstats'   => 'th',
            'webalizer' => 'english'
        },
        'tr' => {
            'analog'    => 'tr',
            'awstats'   => 'tr',
            'webalizer' => 'turkish'
        },
        'zh' => {
            'analog'    => 'cn',       # the cn.lng does not say what it is so this is an assumption based on other pervasive bad practices
            'awstats'   => 'cn',
            'webalizer' => 'chinese'
        },
        'zh_cn' => {
            'analog'    => 'cn',                  # the cn.lng does not say what it is so this is an assumption based on other pervasive bad practices
            'awstats'   => 'cn',
            'webalizer' => 'simplified_chinese'
        },
    );
}

sub get_known_3rdparty_lang {
    my ( $locale, $_3rdparty ) = @_;
    _load_3rdparty();
    my $locale_tag = ref $locale ? $locale->get_language_tag() : $locale;
    $locale_tag = 'en' if $locale_tag eq 'en_us' || $locale_tag eq 'i_default';

    return if !exists $locale_to_3rdparty{$locale_tag};
    return if !exists $locale_to_3rdparty{$locale_tag}{$_3rdparty};
    return $locale_to_3rdparty{$locale_tag}{$_3rdparty};
}

my %locale_lookup_cache;

sub get_3rdparty_lang {
    my ( $locale, $_3rdparty ) = @_;
    my $known = get_known_3rdparty_lang( $locale, $_3rdparty );
    return $known if $known;

    return if !ref($locale) && $locale =~ m/(?:\.\.|\/)/;
    return if $_3rdparty               =~ m/(?:\.\.|\/)/;

    my $locale_tag = ref $locale ? $locale->get_language_tag() : $locale;
    $locale_tag = 'en' if $locale_tag eq 'en_us' || $locale_tag eq 'i_default';

    if ( exists $locale_lookup_cache{$_3rdparty} ) {
        return $locale_lookup_cache{$_3rdparty}{$locale_tag} if exists $locale_lookup_cache{$_3rdparty}{$locale_tag};
        return;
    }
    require Cpanel::DataStore;
    my $hr = Cpanel::DataStore::fetch_ref("/var/cpanel/locale/3rdparty/apps/$_3rdparty.yaml");
    my %seen;
    %{ $locale_lookup_cache{$_3rdparty} } = map { ++$seen{ $hr->{$_} } == 1 ? ( $hr->{$_} => $_ ) : () } keys %{$hr};

    return $locale_lookup_cache{$_3rdparty}{$locale_tag} if exists $locale_lookup_cache{$_3rdparty}{$locale_tag};
    return;
}

my @list;

sub get_3rdparty_list {
    return @list if @list;

    @list = qw(analog awstats webalizer);

    if ( -d "/var/cpanel/locale/3rdparty/apps" ) {
        require Cpanel::SafeDir::Read;
        push @list, sort map { my $f = $_; $f =~ s/\.yaml$// ? ($f) : () } Cpanel::SafeDir::Read::read_dir("/var/cpanel/locale/3rdparty/apps");
    }

    return @list;
}

my %opt_cache;

sub get_app_options {
    my ($_3rdparty) = @_;
    return if $_3rdparty =~ m/(?:\.\.|\/)/;

    return $opt_cache{$_3rdparty} if exists $opt_cache{$_3rdparty};
    if ( $_3rdparty eq 'analog' || $_3rdparty eq 'awstats' || $_3rdparty eq 'webalizer' ) {
        _load_3rdparty();
        my %seen;
        $opt_cache{$_3rdparty} = [ sort map { ++$seen{ $locale_to_3rdparty{$_}{$_3rdparty} } == 1 ? ( $locale_to_3rdparty{$_}{$_3rdparty} ) : () } keys %locale_to_3rdparty ];
    }
    else {
        require Cpanel::DataStore;
        my $hr = Cpanel::DataStore::fetch_ref("/var/cpanel/locale/3rdparty/apps/$_3rdparty.yaml");
        $opt_cache{$_3rdparty} = [ sort keys %{$hr} ];
    }

    return $opt_cache{$_3rdparty};
}

sub get_app_setting {
    my ( $locale, $_3rdparty ) = @_;

    return if !ref($locale) && $locale =~ m/(?:\.\.|\/)/;
    return if $_3rdparty               =~ m/(?:\.\.|\/)/;

    require Cpanel::LoadFile;
    require Cpanel::StringFunc::Trim;

    my $locale_tag = ref $locale ? $locale->get_language_tag() : $locale;
    $locale_tag = 'en' if $locale_tag eq 'en_us' || $locale_tag eq 'i_default';

    my $setting = Cpanel::StringFunc::Trim::ws_trim( Cpanel::LoadFile::loadfile("/var/cpanel/locale/3rdparty/conf/$locale_tag/$_3rdparty") ) || '';
    if ( $_3rdparty eq 'analog' && $setting eq 'en' ) {
        $setting = 'us';
    }

    return $setting;
}

sub set_app_setting {
    my ( $locale, $_3rdparty, $setting ) = @_;

    return if !ref($locale) && $locale =~ m/(?:\.\.|\/)/;
    return if $_3rdparty               =~ m/(?:\.\.|\/)/;

    require Cpanel::SafeDir::MK;
    require Cpanel::FileUtils::Write;

    my $locale_tag = ref $locale ? $locale->get_language_tag() : $locale;
    $locale_tag = 'en' if $locale_tag eq 'en_us' || $locale_tag eq 'i_default';

    Cpanel::SafeDir::MK::safemkdir("/var/cpanel/locale/3rdparty/conf/$locale_tag/");
    Cpanel::FileUtils::Write::overwrite_no_exceptions( "/var/cpanel/locale/3rdparty/conf/$locale_tag/$_3rdparty", $setting, 0644 );

    return;
}

1;

} # --- END Cpanel/Locale/Utils/3rdparty.pm


{ # --- BEGIN Cpanel/JS/Variations.pm
package Cpanel::JS::Variations;


use strict;

sub lex_filename_for {
    my ( $filename, $locale ) = @_;
    return if !$filename || !$locale;
    return get_base_file( $filename, "-${locale}.js" );
}

sub get_base_file {
    my ( $filename, $replace_extension ) = @_;
    return if !$filename;
    $replace_extension //= '.js';
    $filename =~ s{/js2-min/}{/js2/};
    $filename =~ s{(?:[\.\-]min|_optimized)?\.js$}{$replace_extension};
    return $filename;
}

1;

} # --- END Cpanel/JS/Variations.pm


{ # --- BEGIN Cpanel/Destruct.pm
package Cpanel::Destruct;


use strict;
my $in_global_destruction = 0;
my ( $package, $filename, $line, $subroutine );    # preallocate

sub in_dangerous_global_destruction {

    if ( !$INC{'Test2/API.pm'} ) {

        return 1 if in_global_destruction() && $INC{'Cpanel/BinCheck.pm'};
    }

    return 0;
}

sub in_global_destruction {
    return $in_global_destruction if $in_global_destruction;

    if ( defined( ${^GLOBAL_PHASE} ) ) {
        if ( ${^GLOBAL_PHASE} eq 'DESTRUCT' ) {
            $in_global_destruction = 1;
        }
    }

    else {
        local $SIG{'__WARN__'} = \&_detect_global_destruction_pre_514_WARN_handler;
        warn;
    }

    return $in_global_destruction;
}

sub _detect_global_destruction_pre_514_WARN_handler {
    if ( length $_[0] > 26 && rindex( $_[0], 'during global destruction.' ) == ( length( $_[0] ) - 26 ) ) {
        $in_global_destruction = 1;
    }

    return;
}

1;

} # --- END Cpanel/Destruct.pm


{ # --- BEGIN Cpanel/Sys/Uname.pm
package Cpanel::Sys::Uname;


use strict;

our $SYS_UNAME       = 63;
our $UNAME_ELEMENTS  = 6;
our $_UTSNAME_LENGTH = 65;
my $UNAME_PACK_TEMPLATE   = ( 'c' . $_UTSNAME_LENGTH ) x $UNAME_ELEMENTS;
my $UNAME_UNPACK_TEMPLATE = ( 'Z' . $_UTSNAME_LENGTH ) x $UNAME_ELEMENTS;

my @uname_cache;

sub get_uname_cached {
    return ( @uname_cache ? @uname_cache : ( @uname_cache = syscall_uname() ) );
}

sub clearcache {
    @uname_cache = ();
    return;
}

sub syscall_uname {
    my $uname;
    if ( syscall( $SYS_UNAME, $uname = pack( $UNAME_PACK_TEMPLATE, () ) ) == 0 ) {
        return unpack( $UNAME_UNPACK_TEMPLATE, $uname );
    }
    else {
        die "The uname() system call failed because of an error: $!";
    }
    return;
}
1;

} # --- END Cpanel/Sys/Uname.pm


{ # --- BEGIN Cpanel/Sys/Hostname/Fallback.pm
package Cpanel::Sys::Hostname::Fallback;


use strict;
use warnings;

use Socket             ();
# use Cpanel::Sys::Uname ();


sub get_canonical_hostname {
    my @uname = Cpanel::Sys::Uname::get_uname_cached();
    my ( $err, @results ) = Socket::getaddrinfo( $uname[1], 0, { flags => Socket::AI_CANONNAME() } );
    if ( @results && $results[0]->{'canonname'} ) {
        return $results[0]->{'canonname'};
    }

    return undef;

}

1;

} # --- END Cpanel/Sys/Hostname/Fallback.pm


{ # --- BEGIN Cpanel/Sys/Hostname.pm
package Cpanel::Sys::Hostname;


use strict;
use warnings;

our $VERSION = 2.0;

# use Cpanel::Sys::Uname ();

our $cachedhostname = '';

sub gethostname {
    my $nocache = shift || 0;
    if ( !$nocache && length $cachedhostname ) { return $cachedhostname }

    my $hostname = _gethostname($nocache);

    if ( length $hostname ) {
        $hostname =~ tr{A-Z}{a-z};    # hostnames must be lowercase (see Cpanel::Sys::Hostname::Modify::make_hostname_lowercase_fqdn)
        $cachedhostname = $hostname;
    }
    return $hostname;
}

sub _gethostname {
    my $nocache = shift || 0;

    my $hostname;
    Cpanel::Sys::Uname::clearcache() if $nocache;
    my @uname = Cpanel::Sys::Uname::get_uname_cached();
    if ( $uname[1] && index( $uname[1], '.' ) > -1 ) {
        $hostname = $uname[1];
        $hostname =~ tr{A-Z}{a-z};    # hostnames must be lowercase (see Cpanel::Sys::Hostname::Modify::make_hostname_lowercase_fqdn)
        return $hostname;
    }

    eval {
        require Cpanel::Sys::Hostname::Fallback;
        $hostname = Cpanel::Sys::Hostname::Fallback::get_canonical_hostname();
    };
    if ($hostname) {
        $hostname =~ tr{A-Z}{a-z};    # hostnames must be lowercase (see Cpanel::Sys::Hostname::Modify::make_hostname_lowercase_fqdn)
        return $hostname;
    }

    require Cpanel::LoadFile;
    chomp( $hostname = Cpanel::LoadFile::loadfile( '/proc/sys/kernel/hostname', { 'skip_exists_check' => 1 } ) );
    if ($hostname) {
        $hostname =~ tr{A-Z}{a-z};    # hostnames must be lowercase (see Cpanel::Sys::Hostname::Modify::make_hostname_lowercase_fqdn)
        $hostname =~ tr{\r\n}{}d;     # chomp is not enough (not sure if this is required, however we cannot test all kernels so its safer to leave it in)
        return $hostname;
    }

    require Cpanel::Debug;
    Cpanel::Debug::log_warn('Unable to determine correct hostname');
    return;
}


sub shorthostname {
    my $hostname = gethostname();
    return $hostname if index( $hostname, '.' ) == -1;    # Hostname is not a FQDN (this should never happen)
    return substr( $hostname, 0, index( $hostname, '.' ) );
}

1;

} # --- END Cpanel/Sys/Hostname.pm


{ # --- BEGIN Cpanel/Hostname.pm
package Cpanel::Hostname;


use strict;
use warnings;

# use Cpanel::Sys::Hostname ();

our $VERSION = 2.0;

{
    no warnings 'once';
    *gethostname   = *Cpanel::Sys::Hostname::gethostname;
    *shorthostname = *Cpanel::Sys::Hostname::shorthostname;
}

1;

} # --- END Cpanel/Hostname.pm


{ # --- BEGIN Cpanel/Config/CpConfGuard/CORE.pm
package Cpanel::Config::CpConfGuard::CORE;


use strict;
use warnings;


# use Cpanel::ConfigFiles                  ();
# use Cpanel::Debug                        ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::LoadModule                   ();
# use Cpanel::Config::CpConfGuard          ();

our $SENDING_MISSING_FILE_NOTICE = 0;

my $FILESYS_PERMS = 0644;

sub find_missing_keys {
    my ($self) = @_;
    _verify_called_as_object_method($self);

    Cpanel::LoadModule::load_perl_module('Cpanel::Config::CpConfGuard::Default');
    my $default = 'Cpanel::Config::CpConfGuard::Default'->new(
        current_config  => $self->{data},
        current_changes => $self->{changes},
    );

    if ( $self->{'is_missing'} ) {

        if ( UNIVERSAL::isa( $self->{'cache'}, 'HASH' ) && %{ $self->{'cache'} } ) {

            $self->{'data'} = {};
            %{ $self->{'data'} } = %{ $self->{'cache'} };
            my $config = $self->{'data'};

            foreach my $key ( $default->get_keys() ) {
                next if exists $config->{$key};
                $config->{$key} = $default->get_default_for($key);
            }

        }
        else {
            $self->{'data'} = $default->get_all_defaults();
        }

        $self->{'modified'} = 1;    # Mark as save needed.
        return;
    }

    my $cache = $self->{'cache'};
    undef( $self->{'cache'} );    # we do not need the cache after the first pass
    my $config = $self->{'data'};

    my $changes = $self->{'changes'};    # used for notifications

    $config->{'tweak_unset_vars'} ||= '';

    foreach my $key ( $default->get_keys() ) {
        next if exists $config->{$key};

        $self->{'modified'} = 1;    # Mark as save needed.

        if ( exists $cache->{$key} ) {
            $config->{$key} = $cache->{$key};

            $changes->{'from_cache'} ||= [];
            push @{ $changes->{'from_cache'} }, $key;

            $changes->{'changed_keys'} ||= {};
            $changes->{'changed_keys'}{$key} = 'from_cache';

            next;
        }

        my $changes_type = $default->is_dynamic($key) ? 'from_dynamic' : 'from_default';

        $changes->{'changed_keys'} ||= {};
        $changes->{'changed_keys'}{$key} = $changes_type;

        $changes->{$changes_type} ||= [];
        push @{ $changes->{$changes_type} }, $key;

        $config->{$key} = $default->get_default_for($key);
    }

    foreach my $key ( @{ $default->dead_variables() } ) {
        next unless exists $config->{$key};

        $self->{'modified'} = 1;    # Mark as save needed.

        delete( $config->{$key} );

        $changes->{'dead_variable'} ||= [];
        push @{ $changes->{'dead_variable'} }, $key;

    }

    return;
}

sub validate_keys {
    my ($self) = @_;

    _verify_called_as_object_method($self);

    Cpanel::LoadModule::load_perl_module('Cpanel::Config::CpConfGuard::Validate');
    my $invalid = 'Cpanel::Config::CpConfGuard::Validate'->can('patch_cfg')->( $self->{'data'} );
    if (%$invalid) {
        $self->{modified} = 1;
        $self->{'changes'}->{'invalid'} = $invalid;
    }

    return;
}

sub notify_and_save_if_changed {
    my ($self) = @_;
    _verify_called_as_object_method($self);

    return if !$self->{'use_lock'};
    return if !$self->{'modified'};

    my $config = $self->{'data'};

    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        ;    # Do nothing for notification.
    }
    elsif ( $self->{'is_missing'} ) {
        $config->{'tweak_unset_vars'} = '';
        Cpanel::Debug::log_warn("Missing cpanel.config regenerating …");

        $self->notify_missing_file;
    }
    elsif ( %{ $self->{'changes'} } ) {
        my $changes = $self->{'changes'};

        my %uniq = map { $_ => 1 } @{ $changes->{'from_default'} || [] }, @{ $changes->{'from_dynamic'} || [] }, split( /\s*,\s*/, $config->{'tweak_unset_vars'} );
        $config->{'tweak_unset_vars'} = join ",", sort keys %uniq;

        $self->log_missing_values();
    }

    return $self->save( keep_lock => 1 );
}

sub _server_locale {
    my ($self) = @_;

    _verify_called_as_object_method($self);

    my $locale_name = $self->{'data'}->{'server_locale'} || 'en';
    require Cpanel::Locale;
    return Cpanel::Locale->_real_get_handle($locale_name);
}

sub _longest {
    my @array = @_;
    return length( ( sort { length $b <=> length $a } @array )[0] );
}

sub _stringify_undef {
    my $value = shift;
    return defined $value ? $value : '<undef>';
}

sub log_missing_values {
    my ($self) = @_;

    require Cpanel::Hostname;
    my $changes = $self->{'changes'};

    my $locale = $self->_server_locale();

    my $hostname = Cpanel::Hostname::gethostname();

    my $prev = $locale->set_context_plain();

    my $message = '';
    $message .= $locale->maketext( 'One or more key settings for “[_1]” were either not found in [asis,cPanel amp() WHM]’s server configuration file ([_2]), or were present but did not pass validation.', $hostname, $self->{'path'} ) . "\n";

    if ( $changes->{'from_dynamic'} ) {
        $message .= $locale->maketext('The following settings were absent and have been selected based on the current state of your installation.');
        $message .= "\n";

        my @keys    = @{ $changes->{'from_dynamic'} };
        my $max_len = _longest(@keys) + 2;
        foreach my $key (@keys) {
            $message .= sprintf( "    %-${max_len}s= %s\n", $key, _stringify_undef( $self->{'data'}->{$key} ) );
        }
        $message .= "\n";
    }

    if ( $changes->{'from_cache'} ) {
        $message .= $locale->maketext('The following settings were absent, but were restored from your [asis,cpanel.config.cache] file:');
        $message .= "\n";

        my @keys    = @{ $changes->{'from_cache'} };
        my $max_len = _longest(@keys) + 2;
        foreach my $key (@keys) {
            $message .= sprintf( "    %-${max_len}s= %s\n", $key, _stringify_undef( $self->{'data'}->{$key} ) );
        }
        $message .= "\n";
    }

    if ( $changes->{'from_default'} or $changes->{'invalid'} ) {
        $message .= $locale->maketext('The following settings were absent or invalid. Your server has copied the defaults for them from the configuration defaults file ([asis,/usr/local/cpanel/etc/cpanel.config]).');
        $message .= "\n";

        if ( $changes->{'from_default'} ) {
            my @keys    = @{ $changes->{'from_default'} };
            my $max_len = _longest(@keys) + 2;
            foreach my $key (@keys) {
                $message .= sprintf( "    %-${max_len}s= %s\n", $key, _stringify_undef( $self->{'data'}->{$key} ) );
            }
        }

        if ( $changes->{'invalid'} ) {
            my $invalid = $changes->{'invalid'};
            my @keys    = keys %$invalid;
            my $max_len = _longest(@keys) + 2;
            foreach my $key (@keys) {
                $message .= sprintf( "    %-${max_len}s= %s (Previously set to '%s')\n", $key, _stringify_undef( $invalid->{$key}->{'to'} ), _stringify_undef( $invalid->{$key}->{'from'} ) );
            }
        }
        $message .= "\n";
    }

    if ( $changes->{'dead_variable'} ) {
        $message .= $locale->maketext('The following settings are obsolete and have been removed from the server configuration file:');
        $message .= "\n";
        $message .= '    ' . join( ', ', @{ $changes->{'dead_variable'} } );
        $message .= "\n\n";
    }

    $message .= $locale->maketext( 'Read the [asis,cpanel.config] file [output,url,_1,documentation] for important information about this file.', 'https://go.cpanel.net/cpconfig' );
    $message .= "\n\n";

    Cpanel::Debug::logger();    # initialize the logger
    local $Cpanel::Logger::ENABLE_BACKTRACE = 0;
    foreach my $chunk ( split( /\n+/, $message ) ) {
        Cpanel::Debug::log_warn($chunk);
    }

    $locale->set_context($prev);

    return;
}

sub notify_missing_file {
    my ($self) = @_;

    if ($SENDING_MISSING_FILE_NOTICE) {
        return;    #Already sending notification, don't double up
    }

    require Cpanel::Hostname;
    local $SENDING_MISSING_FILE_NOTICE = 1;

    my $locale = $self->_server_locale();
    my $prev   = $locale->set_context_plain();

    my @to_log;
    my %critical_values;

    my $hostname = Cpanel::Hostname::gethostname();
    push @to_log, $locale->maketext('Your server has copied the defaults from your cache and the configuration defaults file ([asis,/usr/local/cpanel/etc/cpanel.config]) to [asis,/var/cpanel/cpanel.config], and it has generated the following critical values:');
    Cpanel::LoadModule::load_perl_module('Cpanel::Config::CpConfGuard::Default');
    my $critical = Cpanel::Config::CpConfGuard::Default::critical_values();
    my $max_len  = _longest(@$critical) + 2;
    my $critical_value;
    foreach my $key ( sort @$critical ) {
        $critical_value = _stringify_undef( $self->{'data'}->{$key} );
        $critical_values{$key} = $critical_value;
        push @to_log, sprintf( "    %-${max_len}s= %s\n", $key, $critical_value );
    }

    push @to_log, $locale->maketext( 'Read the [asis,cpanel.config] file [output,url,_1,documentation] for more information about this file.', 'https://go.cpanel.net/cpconfig' ) . ' ';

    Cpanel::Debug::logger();    # initialize the logger
    local $Cpanel::Logger::ENABLE_BACKTRACE = 0;

    foreach my $chunk (@to_log) {
        chomp $chunk;
        Cpanel::Debug::log_warn($chunk);
    }

    _icontact( \%critical_values );

    $locale->set_context($prev);

    return;
}

sub _icontact {
    my $critical_values = shift;

    Cpanel::LoadModule::load_perl_module("Cpanel::iContact::Class::Config::CpConfGuard");
    Cpanel::LoadModule::load_perl_module('Cpanel::Notify');
    'Cpanel::Notify'->can('notification_class')->(
        'class'            => 'Config::CpConfGuard',
        'application'      => 'Config::CpConfGuard',
        'constructor_args' => [
            'origin'          => 'cpanel.config',
            'critical_values' => $critical_values,
        ]
    );

    return;
}

sub save {
    my ( $self, %opts ) = @_;

    _verify_called_as_object_method($self);

    return unless ( $self->{'use_lock'} );

    return if ( $] > 5.007 && $] < 5.014 );

    return 1 if $Cpanel::Config::CpConfGuard::memory_only;

    if ( !$self->{'rw'} ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::SafeFile');
        $self->{'fh'} = 'Cpanel::SafeFile'->can('safereopen')->( $self->{'fh'}, '+>', $Cpanel::ConfigFiles::cpanel_config_file );
        return $self->abort('Cannot reopen file for rw') unless $self->{'fh'};
        $self->{'rw'} = 1;
    }

    return $self->abort('Locked in parent, cannot save') if $self->{'pid'} != $$;
    return $self->abort('hash reference required')       if !UNIVERSAL::isa( $self->{'data'}, 'HASH' );

    Cpanel::LoadModule::load_perl_module('Cpanel::Config::FlushConfig');
    Cpanel::LoadModule::load_perl_module('Cpanel::Config::SaveCpConf');

    'Cpanel::Config::FlushConfig'->can('flushConfig')->(
        $self->{'fh'},
        $self->{'data'},
        '=',
        'Cpanel::Config::SaveCpConf'->can('header_message')->(),
        {
            sort  => 1,
            perms => $FILESYS_PERMS,
        },
    );


    %{$Cpanel::Config::CpConfGuard::MEM_CACHE} = %{ $self->{'data'} };

    return 1 if $opts{keep_lock};

    $self->release_lock;

    return 1;
}

sub _update_cache {
    my ($self) = @_;

    _verify_called_as_object_method($self);

    return 0 if Cpanel::Config::CpConfGuard::_cache_is_valid() && $self->{'cache_is_valid'};    # Don't re-write the file if it looks correct.

    $Cpanel::Config::CpConfGuard::MEM_CACHE_CPANEL_CONFIG_MTIME = ( stat($Cpanel::ConfigFiles::cpanel_config_file) )[9] || 0;

    return unless $self->{'use_lock'};                                                          # never update the cache when not root


    local $@;

    my $ok = eval { Cpanel::FileUtils::Write::JSON::Lazy::write_file( $Cpanel::ConfigFiles::cpanel_config_cache_file, $Cpanel::Config::CpConfGuard::MEM_CACHE, $FILESYS_PERMS ) || 0 };

    if ( !$ok ) {

        if ( !defined $ok ) {
            Cpanel::Debug::log_warn("Cannot update cache file: $Cpanel::ConfigFiles::cpanel_config_cache_file $@");

            unlink $Cpanel::ConfigFiles::cpanel_config_cache_file;
            return -1;
        }

        return;
    }

    my $past = ( stat($Cpanel::ConfigFiles::cpanel_config_cache_file) )[9] - 1;

    return _adjust_timestamp_for( $Cpanel::ConfigFiles::cpanel_config_file => $past );
}

sub _adjust_timestamp_for {
    my ( $f, $time ) = @_;

    return unless defined $f && defined $time;

    return 1 if utime( $time, $time, $f );

    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime($time);
    my $stamp = sprintf( "%04d%02d%02d%02d%02d.%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec );

    unless ( _touch( $f => $stamp ) ) {
        Cpanel::Debug::log_warn("Cannot update mtime on $f: $@");
        return;
    }

    return 1;
}

sub _touch {    # mainly created to easily mock that part during the tests
    my ( $f, $stamp ) = @_;
    return system( 'touch', '-t', $stamp, $f ) == 0 ? 1 : 0;
}

sub _verify_called_as_object_method {
    if ( ref( $_[0] ) ne "Cpanel::Config::CpConfGuard" ) {
        die '' . ( caller(0) )[3] . " was not called as an object method [" . ref( $_[0] ) . "]\n";
    }
    return;
}

sub abort {
    my ( $self, $msg ) = @_;

    _verify_called_as_object_method($self);

    if ( $self->{'pid'} != $$ ) {
        Cpanel::Debug::log_die('Locked in parent, cannot release lock');
        return;
    }

    $self->release_lock();

    Cpanel::Debug::log_die($msg) if $msg;


    return 1;
}

sub set {
    my ( $self, $k, $v ) = @_;

    _verify_called_as_object_method($self);

    return unless defined $k;

    my $config = $self->{'data'};

    $config->{$k} = $v;

    if ( $config->{'tweak_unset_vars'} && index( $config->{'tweak_unset_vars'}, $k ) > -1 ) {
        my %unset = map { ( $_ => 1 ) } split( /\s*,\s*/, $config->{'tweak_unset_vars'} );
        delete( $unset{$k} );
        $config->{'tweak_unset_vars'} = join( ',', sort keys %unset );
    }

    return 1;
}

1;

} # --- END Cpanel/Config/CpConfGuard/CORE.pm


{ # --- BEGIN Cpanel/Config/CpConfGuard.pm
package Cpanel::Config::CpConfGuard;


use strict;
use warnings;

# use Cpanel::JSON::FailOK ();
# use Cpanel::ConfigFiles  ();

# use Cpanel::Debug    ();
# use Cpanel::Destruct ();

use constant {
    _ENOENT => 2,
};

our $IN_LOAD                     = 0;
our $SENDING_MISSING_FILE_NOTICE = 0;

my $FILESYS_PERMS = 0644;

my $is_daemon;

BEGIN {
    $is_daemon = 0;    # initialize the value in the begin block
    if (   index( $0, 'updatenow' ) > -1
        || index( $0, 'cpsrvd' ) > -1
        || index( $0, 'cpdavd' ) > -1
        || index( $0, 'queueprocd' ) > -1
        || index( $0, 'tailwatchd' ) > -1
        || index( $0, 'cpanellogd' ) > -1
        || ( length $0 > 7 && substr( $0, -7 ) eq '.static' ) ) {
        $is_daemon = 1;
    }
}

my $module_file;

our ( $MEM_CACHE_CPANEL_CONFIG_MTIME, $MEM_CACHE ) = ( 0, undef );

our $memory_only;

sub _is_daemon { $is_daemon };    # for testing

sub clearcache {
    $MEM_CACHE_CPANEL_CONFIG_MTIME = 0;
    $MEM_CACHE                     = undef;
    return;
}

sub new {
    my ( $class, %opts ) = @_;

    Cpanel::JSON::FailOK::LoadJSONModule() if !$is_daemon && !$INC{'Cpanel/JSON.pm'};

    my $self = bless {
        %opts,    # to be improved
        'path'     => $Cpanel::ConfigFiles::cpanel_config_file,
        'pid'      => $$,
        'modified' => 0,
        'changes'  => {},
    }, $class;

    $self->{'use_lock'} //= ( $> == 0 ) ? 1 : 0;

    if ($memory_only) {
        $self->{'data'} = ref($memory_only) eq 'HASH' ? $memory_only : {};
        return $self;
    }

    ( $self->{'cache'}, $self->{'cache_is_valid'} ) = get_cache();

    return $self if $self->{'loadcpconf'} && $self->{'cache_is_valid'};

    $self->load_cpconf_file();

    return $self if $is_daemon || $opts{'no_validate'} || !$self->{'use_lock'};

    $self->find_missing_keys();
    $self->validate_keys();
    $self->notify_and_save_if_changed();

    return $self;
}

sub set {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::set;
}

sub config_copy {
    my ($self) = @_;
    _verify_called_as_object_method($self);

    my $config = $self->{'data'} || $self->{'cache'} || {};
    return {%$config};
}

sub find_missing_keys {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::find_missing_keys;
}

sub validate_keys {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::validate_keys;
}

sub notify_and_save_if_changed {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::notify_and_save_if_changed;
}

sub log_missing_values {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::log_missing_values;
}

sub notify_missing_file {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::notify_missing_file;
}

sub save {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::save;
}

sub release_lock {
    my ($self) = @_;

    _verify_called_as_object_method($self);

    return unless $self->{'use_lock'} && defined $self->{'pid'} && $self->{'pid'} eq $$ && $self->{'lock'};

    require Cpanel::SafeFile;
    Cpanel::SafeFile::safeclose( $self->{'fh'}, $self->{'lock'}, sub { return $self->_update_cache() } );

    $self->{'fh'}        = $self->{'lock'} = undef;
    $self->{'is_locked'} = 0;

    return;
}

sub abort {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::abort;
}

sub _update_cache {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::_update_cache;
}

sub _server_locale {
    require Cpanel::Config::CpConfGuard::CORE;
    goto \&Cpanel::Config::CpConfGuard::CORE::_server_locale;
}

sub get_cache {

    my $cpanel_config_mtime = ( stat($Cpanel::ConfigFiles::cpanel_config_file) )[9] || 0;

    my $verbose = ( defined $Cpanel::Debug::level ? $Cpanel::Debug::level : 0 ) >= 5;

    if ( $MEM_CACHE && ref($MEM_CACHE) eq 'HASH' && $cpanel_config_mtime && $cpanel_config_mtime == $MEM_CACHE_CPANEL_CONFIG_MTIME ) {
        Cpanel::Debug::log_info("loadcpconf memory cache hit") if $verbose;

        return ( $MEM_CACHE, 1 );
    }

    clearcache();    # Invalidate the memory cache.

    Cpanel::Debug::log_info("loadcpconf memory cache miss") if $verbose;

    my $mtime_before_read;

    if ( !$INC{'Cpanel/JSON.pm'} ) {
        Cpanel::Debug::log_info("Cpanel::JSON not loaded. Skipping cache load.") if $verbose;
        return ( undef, 0 );
    }
    elsif ( -e $Cpanel::ConfigFiles::cpanel_config_cache_file ) {    # No need to do -r (costs 5 additional syscalls) since we write this 0644
        $mtime_before_read = ( stat _ )[9] || 0;
    }
    else {
        Cpanel::Debug::log_info("The cache file “$Cpanel::ConfigFiles::cpanel_config_cache_file” could not be read. Skipping cache load.") if $verbose;
        return ( undef, 0 );
    }

    my ( $mtime_after_read, $cpconf_ref ) = (0);

    my $loop_count = 0;
    while ( $mtime_after_read != $mtime_before_read && $loop_count++ < 10 ) {
        sleep 1 if ( $mtime_after_read == time );    # If it was just written to, give it a second in case it's being written to.

        Cpanel::Debug::log_info( "loadcpconf cache_filesys_mtime = $mtime_before_read , filesys_mtime: $cpanel_config_mtime , memory_mtime: $MEM_CACHE_CPANEL_CONFIG_MTIME , now: " . time ) if $verbose;

        $cpconf_ref       = Cpanel::JSON::FailOK::LoadFile($Cpanel::ConfigFiles::cpanel_config_cache_file);
        $mtime_after_read = ( stat($Cpanel::ConfigFiles::cpanel_config_cache_file) )[9] || 0;

        sleep 1 if ( $mtime_after_read != $mtime_before_read );
    }

    if ( $cpconf_ref && scalar keys %{$cpconf_ref} ) {
        if ( _cache_is_valid( $cpanel_config_mtime, $mtime_after_read ) ) {
            Cpanel::Debug::log_info("loadcpconf file system cache hit") if $verbose;

            ( $MEM_CACHE, $MEM_CACHE_CPANEL_CONFIG_MTIME ) = ( $cpconf_ref, $cpanel_config_mtime );
            return ( $cpconf_ref, 1 );
        }
        Cpanel::Debug::log_info("loadcpconf cpanel.config.cache miss.") if $verbose;
        return ( $cpconf_ref, 0 );
    }

    Cpanel::Debug::log_info("loadcpconf cpanel.config.cache miss.") if $verbose;
    return ( undef, 0 );
}

sub _cache_is_valid {
    my ( $config_mtime, $cache_mtime ) = @_;

    $cache_mtime ||= ( stat($Cpanel::ConfigFiles::cpanel_config_cache_file) )[9] || 0;
    return 0 unless $cache_mtime;

    $config_mtime ||= ( stat($Cpanel::ConfigFiles::cpanel_config_file) )[9] || 0;
    return 0 unless $config_mtime;

    return ( $config_mtime + 1 == $cache_mtime ) ? 1 : 0;
}

sub load_cpconf_file {
    my ($self) = @_;

    if ($IN_LOAD) {
        require Cpanel::Carp;
        die Cpanel::Carp::safe_longmess("Load loop detected");
    }

    local $IN_LOAD = 1;

    _verify_called_as_object_method($self);

    my $config = {};

    my $config_file = $Cpanel::ConfigFiles::cpanel_config_file;

    $self->{'is_missing'} = ( -e $config_file ) ? 0 : 1;

    return if ( !$self->{'use_lock'} && $self->{'is_missing'} );    # We can't do anything if the file is missing and we're not root. ABORT!

    if ( $self->{'use_lock'} && $self->{'is_missing'} ) {
        if ( open( my $touch_fh, '>>', $config_file ) ) {
            print {$touch_fh} '';
            close $touch_fh;
            chown 0, 0, $config_file;    # avoid pulling in Cpanel::PwCache for memory reasons
            chmod 0644, $config_file;
        }
    }

    $self->{'rw'} = 0;
    $self->{'rw'} = 1 if ( $self->{'use_lock'} && !$self->{'cache_is_valid'} );

    require Cpanel::Config::LoadConfig;
    my ( $ref, $fh, $conflock, $err ) = Cpanel::Config::LoadConfig::loadConfig(
        $Cpanel::ConfigFiles::cpanel_config_file,
        $config,

        (undef) x 4,
        {
            'keep_locked_open'   => !!$self->{'use_lock'},
            'nocache'            => 1,
            'rw'                 => $self->{'rw'},
            'allow_undef_values' => 1,
        },
    );

    if ( !$ref && !$fh && $! != _ENOENT() ) {
        $err ||= '(unknown error)';
        require Cpanel::Carp;
        die Cpanel::Carp::safe_longmess("Can’t read “$Cpanel::ConfigFiles::cpanel_config_file” ($err)");
    }

    $self->{'fh'}   = $fh;
    $self->{'lock'} = $conflock;
    $self->{'data'} = $config;

    if ( $self->{'use_lock'} ) {
        Cpanel::Debug::log_warn("Failed to establish lock on $Cpanel::ConfigFiles::cpanel_config_file") unless $self->{'lock'};

        Cpanel::Debug::log_warn("Failed to get file handle for $Cpanel::ConfigFiles::cpanel_config_file") unless $self->{'fh'};
    }

    $self->{'is_locked'} = defined $self->{'lock'} ? 1 : 0;    # alias for external usage

    if ( !$MEM_CACHE ) {
        $MEM_CACHE  = {};
        %$MEM_CACHE = %$config;
    }

    return;
}

sub _verify_called_as_object_method {
    if ( ref( $_[0] ) ne __PACKAGE__ ) {
        die '' . ( caller(0) )[3] . " was not called as an object method [" . ref( $_[0] ) . "]\n";
    }
    return;
}

sub DESTROY {    ## no critic(RequireArgUnpacking)
    return 1 if ( $>     || $memory_only );        # Special modes we don't or won't write to cpanel.config files.
    return 2 if ( !$_[0] || !keys %{ $_[0] } );    # Nothing to cleanup if we're just a blessed empty hash.

    return if !$_[0]->{'lock'};

    return if Cpanel::Destruct::in_dangerous_global_destruction();

    $_[0]->release_lock();                         # Close the file so we can update the cache properly.
    return;
}

1;

} # --- END Cpanel/Config/CpConfGuard.pm


{ # --- BEGIN Cpanel/Config/LoadCpConf.pm
package Cpanel::Config::LoadCpConf;


use strict;
use warnings;


# use Cpanel::Config::CpConfGuard ();


sub loadcpconf {
    my $cpconf = Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 )->config_copy;
    return wantarray ? %$cpconf : $cpconf;
}


sub loadcpconf_not_copy {

    if ( !defined $Cpanel::Config::CpConfGuard::memory_only && $Cpanel::Config::CpConfGuard::MEM_CACHE_CPANEL_CONFIG_MTIME ) {
        my ( $cache, $cache_is_valid ) = Cpanel::Config::CpConfGuard::get_cache();
        if ($cache_is_valid) {
            return wantarray ? %$cache : $cache;
        }
    }

    my $cpconf_obj = Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 );
    my $cpconf     = $cpconf_obj->{'data'} || $cpconf_obj->{'cache'} || {};
    return wantarray ? %$cpconf : $cpconf;
}

sub clearcache;
*clearcache = *Cpanel::Config::CpConfGuard::clearcache;

1;

} # --- END Cpanel/Config/LoadCpConf.pm


{ # --- BEGIN Cpanel/Locale/Utils/Display.pm
package Cpanel::Locale::Utils::Display;


use warnings;
use strict;
# use Cpanel::Locale::Utils::Paths ();

sub get_locale_list {
    my ($lh) = @_;
    my @result = @{ $lh->{'_cached_get_locale_list'} ||= [ sort ( 'en', $lh->list_available_locales() ) ] };

    if ( !-e "/var/cpanel/enable_snowmen" ) {
        @result = grep { !/i_cpanel_snowmen/ } @result;
    }
    return @result;
}

sub get_non_existent_locale_list {
    my ( $lh, $loc_obj ) = @_;

    $loc_obj ||= $lh->get_locales_obj('en');
    my %have;
    @have{ get_locale_list($lh), 'en_us', 'i_default', 'und', 'zxx', 'mul', 'mis', 'art' } = ();
    return sort grep { !exists $have{$_} } $loc_obj->get_language_codes();
}

sub get_locale_menu_hashref {
    my ( $lh, $omit_current_locale, $native_only, $skip_locales ) = @_;

    $skip_locales ||= {};
    my %langs;
    my %dir;

    my @langs = get_locale_list($lh);

    my @wanted_langs = grep { !$skip_locales->{$_} } @langs;

    if ( !@wanted_langs ) {
        return ( {}, \@langs, {} );
    }

    my $func = $native_only ? 'lang_names_hashref_native_only' : 'lang_names_hashref';
    my ( $localized_name_for_tag, $native_name_for_tag, $direction_map ) = $lh->$func(@wanted_langs);
    my $current_tag = $lh->get_language_tag();
    $current_tag = 'en' if $current_tag eq 'en_us' || $current_tag eq 'i_default';

    my $i_locales_path = Cpanel::Locale::Utils::Paths::get_i_locales_config_path();
    if ($omit_current_locale) {
        delete $localized_name_for_tag->{$current_tag};
        delete $native_name_for_tag->{$current_tag};
        @langs = grep { $_ ne $current_tag } @langs;
    }

    foreach my $tag ( keys %{$localized_name_for_tag} ) {
        if ( index( $tag, 'i_' ) == 0 ) {
            require Cpanel::DataStore;
            my $i_conf = Cpanel::DataStore::fetch_ref("$i_locales_path/$tag.yaml");
            $langs{$tag} = exists $i_conf->{'display_name'} && defined $i_conf->{'display_name'} && $i_conf->{'display_name'} ne '' ? "$i_conf->{'display_name'} - $tag" : $tag;                    # slightly different format than real tags to visually indicate specialness
            $native_name_for_tag->{$tag} = $langs{$tag};

            if ( exists $i_conf->{'character_orientation'} ) {
                $dir{$tag} = $lh->get_html_dir_attr( $i_conf->{'character_orientation'} );
            }
            elsif ( exists $i_conf->{'fallback_locale'} && exists $direction_map->{ $i_conf->{'fallback_locale'} } ) {
                $dir{$tag} = $direction_map->{ $i_conf->{'fallback_locale'} };
            }

            next;
        }

        if ( exists $direction_map->{$tag} ) {
            $dir{$tag} = $lh->get_html_dir_attr( $direction_map->{$tag} );
        }

        next if $native_only;

        if ( $native_name_for_tag->{$tag} eq $localized_name_for_tag->{$tag} ) {
            if ( $tag eq $current_tag ) {
                $langs{$tag} = $native_name_for_tag->{$tag};
            }
            else {
                $langs{$tag} = "$localized_name_for_tag->{$tag} ($tag)";
            }
        }
        else {
            $langs{$tag} = "$localized_name_for_tag->{$tag} ($native_name_for_tag->{$tag})";
        }
    }

    if ($native_only) {
        return wantarray ? ( $native_name_for_tag, \@langs, \%dir ) : $native_name_for_tag;
    }

    return wantarray ? ( \%langs, \@langs, \%dir ) : \%langs;
}

sub get_non_existent_locale_menu_hashref {
    my $lh = shift;

    $lh->{'Locales.pm'}{'_main_'} ||= $lh->get_locales_obj();

    my %langs;
    my %dir;
    my @langs = get_non_existent_locale_list( $lh, $lh->{'Locales.pm'}{'_main_'} );

    my $wantarray = wantarray() ? 1 : 0;

    for my $code (@langs) {
        if ($wantarray) {
            if ( my $orient = $lh->{'Locales.pm'}{'_main_'}->get_character_orientation_from_code_fast($code) ) {
                $dir{$code} = $lh->get_html_dir_attr($orient);
            }
        }

        my $current = $lh->{'Locales.pm'}{'_main_'}->get_language_from_code( $code, 1 );
        my $native  = $lh->{'Locales.pm'}{'_main_'}->get_native_language_from_code( $code, 1 );
        $langs{$code} = $current eq $native ? "$current ($code)" : "$current ($native)";
    }

    return wantarray ? ( \%langs, \@langs, \%dir ) : \%langs;
}

sub in_translation_vetting_mode {
    return ( -e '/var/cpanel/translation_vetting_mode' ) ? 1 : 0;
}

1;

} # --- END Cpanel/Locale/Utils/Display.pm


{ # --- BEGIN Cpanel/Locale/Utils/Api1.pm
package Cpanel::Locale::Utils::Api1;


use strict;
use warnings;


# use Cpanel::Locale ();

my $_lh;

sub _api1_maketext {    ## no critic qw(Subroutines::RequireArgUnpacking)                             ## no extract maketext
    $_lh ||= Cpanel::Locale->get_handle();
    $_[0] =~ s{\\'}{'}g;
    my $localized_str = $_lh->makevar(@_);
    if ($Cpanel::Parser::Vars::embtag) {    # PPI NO PARSE -- module will already be there is we care about it

        require Cpanel::Encoder::Tiny;
        $localized_str = Cpanel::Encoder::Tiny::safe_html_encode_str($localized_str);
    }
    elsif ($Cpanel::Parser::Vars::javascript) {    # PPI NO PARSE -- module will already be there is we care about it
        $localized_str =~ s/"/\\"/g;
        $localized_str =~ s/'/\\'/g;
    }
    return {
        status    => 1,
        statusmsg => $localized_str,
    };
}

1;

} # --- END Cpanel/Locale/Utils/Api1.pm


{ # --- BEGIN Cpanel/OS/SysPerlBootstrap.pm
package Cpanel::OS::SysPerlBootstrap;


use strict;
use warnings;

use constant CACHE_FILE        => '/var/cpanel/caches/Cpanel-OS';
use constant CACHE_FILE_CUSTOM => CACHE_FILE . '.custom';


sub get_os_info {
    my ($iknowwhatimdoing) = @_;
    die("Please use Cpanel::OS for your OS info needs") unless ( $iknowwhatimdoing && $iknowwhatimdoing eq 'DO NOT USE THIS CALL' );

    my @os_info = _read_os_info_cache();
    return @os_info if @os_info;

    my ( $distro, $major, $minor, $build ) = _get_os_without_cache('redhat_first');

    if ( !defined $distro || !length $distro || !defined $major || !length $major || !defined $minor || !length $minor || !defined $build || !length $build ) {
        die sprintf( "Could not determine OS info (distro: %s, major: %s, minor: %s, build: %s)\n", $distro // '', $major // '', $minor // '', $build // '' );
    }

    _cache_os_info( $^O, $distro, $major, $minor, $build );

    return ( $^O, $distro, $major, $minor, $build );
}


sub _get_os_without_cache {
    my ($redhat_first) = @_;

    my @os;
    if ($redhat_first) {    # preserve existing behavior for Cpanel::OS
        @os = _read_redhat_release();
        @os = _read_os_release() unless scalar @os;
    }
    else {
        @os = _read_os_release();
        @os = _read_redhat_release() unless scalar @os;
    }

    return @os;
}


sub _read_os_info_cache {

    my $cache_mtime = ( lstat CACHE_FILE )[9] or return;

    my $custom_os = readlink CACHE_FILE_CUSTOM;

    if ( !$custom_os ) {
        my $os_rel_mtime = ( stat("/etc/os-release") )[9];
        $os_rel_mtime //= ( stat("/etc/redhat-release") )[9];    # in the case of cloudlinux 6, we check against this instead

        return if ( defined($os_rel_mtime) && $cache_mtime <= $os_rel_mtime );
    }

    return split /\|/, readlink(CACHE_FILE);
}


sub _read_os_release {

    return unless -e '/etc/os-release';

    open( my $os_fh, "<", "/etc/os-release" ) or die "Could not open /etc/os-release for reading: $!\n";

    my ( $distro, $ver, $ver_id );
    while ( my $line = <$os_fh> ) {
        my ( $key, $value ) = split( qr/\s*=\s*/, $line, 2 );
        chomp $value;
        $value =~ s/\s.+//;
        $value =~ s/"\z//;
        $value =~ s/^"//;

        if ( !$distro && $key eq "ID" ) {
            $distro = $value;
        }
        elsif ( !$ver_id && $key eq "VERSION_ID" ) {
            $ver_id = $value;
        }
        elsif ( !$ver && $key eq "VERSION" ) {
            $ver = $value;
        }

        last if defined $distro && length $distro && defined $ver && length $ver && defined $ver_id && length $ver_id;
    }
    close $os_fh;

    my ( $major, $minor, $build ) = split( qr/\./, $ver_id );
    return unless $distro;    # We have to at a minimum have a distro name. All hope is lost otherwise.

    unless ( defined $major && length $major && defined $minor && length $minor && defined $build && length $build ) {
        my ( $ver_major, $ver_minor, $ver_build ) = split( qr/\./, $ver );
        $major //= $ver_major;
        $minor //= ( $ver_minor // 0 );
        $build //= ( $ver_build // 0 );
    }

    return ( $distro, $major, $minor, $build );
}


sub _read_redhat_release {

    return unless -e '/etc/redhat-release';

    open( my $cr_fh, "<", "/etc/redhat-release" ) or die "Could not open /etc/redhat-release for reading: $!\n";
    my $line = <$cr_fh>;
    chomp $line;

    my ($distro) = $line =~ m/^(\w+)/i;
    $distro = lc($distro);
    $distro = 'rhel' if $distro eq 'red';

    my ( $major, $minor, $build ) = $line =~ m{\b([0-9]+)\.([0-9]+)\.([0-9]+)};
    if ( !defined $major || !length $major ) {
        ( $major, $minor ) = $line =~ m{\b([0-9]+)\.([0-9]+)};
    }
    if ( !defined $major || !length $major ) {
        ($major) = $line =~ m{\b([0-9]+)};
    }
    $minor //= 0;
    $build //= 0;

    return ( $distro, $major, $minor, $build );
}


sub _cache_os_info {
    my ( $os, $distro, $major, $minor, $build ) = @_;
    $> == 0 or return;

    mkdir '/var/cpanel',        0711;
    mkdir '/var/cpanel/caches', 0711;

    local $!;
    unlink CACHE_FILE;
    symlink "$os|$distro|$major|$minor|$build", CACHE_FILE;

    return 1;
}

1;

} # --- END Cpanel/OS/SysPerlBootstrap.pm


{ # --- BEGIN Cpanel/OS/Linux.pm
package Cpanel::OS::Linux;


use cPstrict;
use Carp ();

# use Cpanel::OS ();
# use Cpanel::OS();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS); }

use constant eol_advice                      => '';
use constant is_supported                    => 0;        # Base OS class for all platforms we currently support.
use constant support_needs_minor_at_least_at => undef;    # by default no restriction on minor version

use constant is_experimental  => 0;                       # By default, no distros are experimental.
use constant experimental_url => '';                      # ... and so no URL to document it.

use constant dns_supported                 => [qw{ powerdns }];    # All platforms support powerdns as it is our default.
use constant supports_3rdparty_wpt         => 1;                   # We support WPT on all platforms ATM.
use constant supports_plugins_repo         => 1;
use constant supports_imunify_av           => 0;
use constant supports_imunify_av_plus      => 0;
use constant supports_imunify_360          => 0;
use constant supports_letsencrypt_v2       => 1;
use constant supports_cpanel_analytics     => 1;
use constant supports_cpanel_cloud_edition => 0;

use constant can_elevate_to => [];

use constant setup_tz_method => q[timedatectl];

use constant nobody  => q[nobody];
use constant nogroup => q[nobody];

use constant default_uid_min     => 1_000;
use constant default_gid_min     => 1_000;
use constant default_sys_uid_min => 201;
use constant default_sys_gid_min => 201;

use constant dns_named_basedir => '/var/named';
use constant dns_named_conf    => '/etc/named.conf';
use constant dns_named_log     => '/var/log/named';
use constant service_manager   => 'systemd';
use constant arch              => 'x86_64';
use constant maillog_path      => '/var/log/maillog';

use constant supports_hostaccess => 1;

use constant rsyslog_triggered_by_socket => 0;

use constant packages_supplemental_epel => [];
use constant quota_packages_conditional => {};

use constant unsupported_db_versions => [];
use constant mariadb_repo_template   => '';    # Not provided on ubuntu for instance.

use constant mariadb_minimum_supported_version    => '10.0';
use constant mysql_default_version                => '5.7';
use constant postgresql_minimum_supported_version => undef;
use constant postgresql_packages                  => [];
use constant postgresql_service_aliases           => [];
use constant postgresql_initdb_commands           => [];
use constant openssl_minimum_supported_version    => '1.0.2e';

use constant ea4_install_repo_from_package => 0;
use constant ea4_from_pkg_url              => undef;
use constant ea4_from_pkg_reponame         => undef;
use constant ea4_from_custom_repo_url      => undef;
use constant ea4_from_custom_repo_path     => undef;
use constant ea4_testing_yum_repo          => undef;
use constant ea4tooling_all                => [qw{ ea-cpanel-tools ea-profiles-cpanel }];

sub ea4tooling_dnsonly   { return Carp::confess('unimplemented for this distro') }
sub ea4tooling           { return Carp::confess('unimplemented for this distro') }
sub system_exclude_rules { return Carp::confess('unimplemented for this distro') }
sub base_distro          { return Carp::confess('unimplemented for this distro') }

sub kernel_package_pattern { return Carp::confess('unimplemented for this distro') }
use constant check_kernel_version_method => q[grubby];
use constant stock_kernel_version_regex  => undef;

sub mysql_versions_use_repo_template   { return Carp::confess('unimplemented for this distro') }
sub mariadb_versions_use_repo_template { return Carp::confess('unimplemented for this distro') }

sub binary_sync_source { return Carp::confess('unimplemented for this distro') }

use constant package_repositories => [];

use constant system_package_providing_perl => 'perl';

use constant rpm_versions_system => 'centos';
use constant packages_arch       => 'x86_64';

use constant package_MySQL_Shell => q[mysql-shell];
use constant package_crond       => undef;

use constant retry_rpm_cmd_no_tty_hack => 0;

use constant check_ntpd_pid_method => 'pid_check_var_run_ntpd';    # how to check ntp daemon pid

use constant prelink_config_path => undef;

use constant pam_file_controlling_crypt_algo => undef;

use constant iptables_ipv4_savefile => '/etc/sysconfig/iptables';
use constant iptables_ipv6_savefile => '/etc/sysconfig/ip6tables';
use constant sysconfig_network      => q[/etc/sysconfig/network];

use constant bin_grub_mkconfig => q[/usr/sbin/grub2-mkconfig];

use constant ssh_supported_algorithms => [qw{ ed25519 ecdsa rsa }];

use constant bin_needs_restarting => q[/usr/local/cpanel/bin/needs-restarting-cpanel];

use constant outdated_services_check  => q[default];
use constant outdated_processes_check => q[default];
use constant check_reboot_method      => q[default];

use constant program_to_apply_kernel_args => undef;

use constant security_service => 'selinux';

use constant supports_kernelcare                       => 0;
use constant supports_kernelcare_free                  => 0;
use constant supports_or_can_become_cloudlinux         => 0;
use constant can_become_cloudlinux                     => 0;
use constant supports_inetd                            => 0;
use constant supports_syslogd                          => 0;
use constant install_gcc_from_slc6_devtoolset          => 0;
use constant supports_postgresql                       => 0;
use constant openssl_escapes_subjects                  => 0;
use constant has_cloudlinux_enhanced_quotas            => 0;
use constant ea4_install_from_profile_enforce_packages => 0;
use constant repos_requires_dump_flag                  => 0;
use constant is_cloudlinux                             => 0;
use constant can_be_elevated                           => 0;
use constant kernel_supports_fs_protected_regular      => 0;
use constant needs_els                                 => 0;

use constant has_quota_support_for_xfs => 1;
use constant is_systemd                => 1;
use constant has_tcp_wrappers          => 1;
use constant can_clean_plugins_repo    => 1;
use constant supports_cpaddons         => 1;

use constant pretty_distro => undef;

sub display_name {
    return sprintf( "%s v%s.%s.%s", Cpanel::OS::pretty_distro() // '', Cpanel::OS::major() // '', Cpanel::OS::minor() // '', Cpanel::OS::build() // '' );    ## no critic(Cpanel::CpanelOS) internal usage
}

sub display_name_lite {
    return sprintf( "%s %s", lc( Cpanel::OS::distro() // '' ), Cpanel::OS::major() // '' );                                                                  ## no critic(Cpanel::CpanelOS) internal usage
}

sub cpanalytics_cpos {
    return sprintf( "%s %s.%s", uc( Cpanel::OS::distro() // '' ), Cpanel::OS::major() // '', Cpanel::OS::minor() // '' );                                    ## no critic(Cpanel::CpanelOS) internal usage
}

use constant nat_server_buffer_connections => 4;

1;


} # --- END Cpanel/OS/Linux.pm


{ # --- BEGIN Cpanel/OS/Rhel.pm
package Cpanel::OS::Rhel;


use cPstrict;

# use Cpanel::OS::Linux ();    # ea4tooling_all
# use Cpanel::OS::Linux();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Linux); }

use constant is_supported => 0;    # Base OS class for all Rhel derivatives.

use constant pretty_distro => 'Red Hat Enterprise Linux';

use constant sudoers         => 'wheel';
use constant has_wheel_group => 1;

use constant dns_supported                     => [qw{ bind powerdns }];
use constant supports_kernelcare               => 1;
use constant supports_kernelcare_free          => 1;
use constant supports_or_can_become_cloudlinux => 1;
use constant can_become_cloudlinux             => 1;
use constant supports_imunify_av               => 1;
use constant supports_imunify_av_plus          => 1;

use constant cron_bin_path                   => '/usr/sbin/crond';
use constant systemd_service_name_map        => {};
use constant ea4_modern_openssl              => '/opt/cpanel/ea-openssl11/bin/openssl';
use constant firewall                        => 'iptables';
use constant firewall_module                 => 'IpTables';
use constant networking                      => 'networkscripts';
use constant package_manager                 => 'yum';
use constant package_manager_module          => 'Yum';
use constant base_distro                     => 'rhel';
use constant is_apt_based                    => 0;
use constant is_yum_based                    => 1;
use constant is_rpm_based                    => 1;
use constant kernel_package_pattern          => 'kernel';
use constant stock_kernel_version_regex      => qr/\.(?:noarch|x86_64|i[3-6]86)$/;
use constant program_to_apply_kernel_args    => 'grub2-mkconfig';
use constant prelink_config_path             => '/etc/sysconfig/prelink';
use constant pam_file_controlling_crypt_algo => 'system-auth';
use constant user_crontab_dir                => '/var/spool/cron';

use constant ea4_from_custom_repo_url  => 'https://securedownloads.cpanel.net/EA4/EA4.repo';
use constant ea4_from_custom_repo_path => '/etc/yum.repos.d/EA4.repo';

use constant ea4_conflicting_apache_distro_packages => [qw( httpd httpd-tools php-cli )];

use constant ea4tooling => [ 'yum-plugin-universal-hooks', Cpanel::OS::Linux->ea4tooling_all->@* ];

use constant ea4tooling_dnsonly => ['yum-plugin-universal-hooks'];

use constant syslog_service_name => 'rsyslogd';

use constant jetbackup_repo_pkg => 'https://repo.jetlicense.com/centOS/jetapps-repo-latest.rpm';

use constant plugins_repo_url => 'https://securedownloads.cpanel.net/cpanel-plugins/0/cpanel-plugins.repo';

use constant repo_suffix => 'repo';
use constant repo_dir    => '/etc/yum.repos.d';

use constant system_exclude_rules => {
    'dovecot'     => 'dovecot*',
    'nsd'         => 'nsd*',
    'php'         => 'php*',
    'exim'        => 'exim*',
    'pure-ftpd'   => 'pure-ftpd*',
    'proftpd'     => 'proftpd*',
    'p0f'         => 'p0f',
    'filesystem'  => 'filesystem',
    'kernel'      => 'kernel kernel-xen kernel-smp kernel-pae kernel-PAE kernel-SMP kernel-hugemem kernel-debug* kernel-core kernel-modules',
    'kmod-'       => 'kmod-[a-z]*',
    'bind-chroot' => 'bind-chroot',
};

use constant packages_supplemental => [

    'nfs-utils',

    qw{
      ImageMagick
      autoconf
      automake
      bind-devel
      bison
      boost-serialization
      cairo
      e2fsprogs-devel
      expat-devel
      flex
      fontconfig
      freetype
      ftp
      gcc-c++
      gd-devel
      gdbm-devel
      gettext-devel
      ghostscript
      giflib
      glib2
      hunspell
      hunspell-en
      krb5-devel
      libX11-devel
      libXpm
      libXpm-devel
      libaio-devel
      libidn-devel
      libjpeg-turbo-devel
      libpng-devel
      libstdc++-devel
      libtiff-devel
      libtool
      libtool-ltdl
      libtool-ltdl-devel
      libwmf
      libxml2-devel
      libxslt-devel
      ncurses
      ncurses-devel
      nscd
      openssl-devel
      pango
      perl-CPAN
      perl-ExtUtils-MakeMaker
      perl-IO-Tty
      perl-Module-Build
      perl-YAML-Syck
      perl-core
      perl-devel
      perl-libwww-perl
      pixman
      python-devel
      python-tools
      quota-devel
      strace
      sysstat
      tcp_wrappers-devel
      traceroute
      urw-fonts
      zlib-devel
    }
];

use constant packages_supplemental_epel => [
    qw{
      perl-Expect
      perl-JSON-XS
      perl-Try-Tiny
      perl-local-lib
    }
];

use constant packages_required => [
    qw{
      aspell
      at
      bind
      bind-libs
      bind-utils
      binutils
      boost-program-options
      bzip2
      compat-db
      coreutils
      cpio
      cpp
      crontabs
      curl
      db4
      db4-devel
      e2fsprogs
      expat
      file
      gawk
      gcc
      gd
      gd-progs
      gdbm
      gettext
      glibc-devel
      gmp
      gnupg2
      grubby
      gzip
      initscripts
      iptables
      iptables-ipv6
      json-c
      kernel-headers
      lcms
      less
      libaio
      libevent
      libgcc
      libgomp
      libicu
      libidn
      libjpeg-turbo
      libpcap
      libpng
      libstdc++
      libtiff
      libxml2
      libxslt
      libzip
      lsof
      make
      nano
      openssh
      openssh-clients
      openssh-server
      openssl
      pam
      pam-devel
      passwd
      patch
      pcre
      pcre2
      popt
      procps
      python
      python-docs
      python-setuptools
      quota
      rdate
      rsync
      sed
      shadow-utils
      smartmontools
      tar
      tmpwatch
      unzip
      util-linux-ng
      wget
      which
      xz
      yum-utils
      zip
      zlib
    }
];

use constant package_ImageMagick_Devel => 'ImageMagick-devel';
use constant package_crond             => 'cronie';

use constant mysql_incompatible => [
    qw{
      mariadb-client
      mariadb-devel
      mariadb-embedded
      mariadb-embedded-devel
      mariadb-libs
      mariadb-libs-compat
      mariadb-release
      mariadb-server
      mariadb-test
      mysql-client
      mysql-devel
      mysql-embedded
      mysql-embedded-devel
      mysql-libs
      mysql-libs-compat
      mysql-release
      mysql-server
      mysql-test
      mysql55-mysql-bench
      mysql55-mysql-devel
      mysql55-mysql-libs
      mysql55-mysql-server
      mysql55-mysql-test
      mysqlclient16
      rh-mysql56-mysql-bench
      rh-mysql56-mysql-common
      rh-mysql56-mysql-config
      rh-mysql56-mysql-devel
      rh-mysql56-mysql-errmsg
      rh-mysql56-mysql-server
      rh-mysql56-mysql-test
      rh-mysql57-mysql-common
      rh-mysql57-mysql-config
      rh-mysql57-mysql-devel
      rh-mysql57-mysql-errmsg
      rh-mysql57-mysql-server
      rh-mysql57-mysql-test
    }
];

use constant mysql_community_packages => [
    qw/
      mysql-community-devel
      mysql-community-libs-compat
      mysql-community-server
      /
];
use constant mysql_dependencies => [
    qw/
      coreutils
      grep
      perl-DBI
      shadow-utils
      /
];

use constant db_package_manager_key_params => {
    method => 'add_repo_key',
    keys   => [qw{https://repo.mysql.com/RPM-GPG-KEY-mysql-2023 https://repo.mysql.com/RPM-GPG-KEY-MySQL-2022 https://repo.mysql.com/RPM-GPG-KEY-mysql https://archive.mariadb.org/PublicKey https://supplychain.mariadb.com/MariaDB-Server-GPG-KEY}],
};

use constant mariadb_repo_template => <<'___END_REPO_TEMPLATE___';
[MariaDB###MARIADB_FLAT_VERSION_SHORT###]
name = MariaDB###MARIADB_FLAT_VERSION_SHORT###
baseurl = https://archive.mariadb.org/mariadb-###MARIADB_VERSION_SHORT###/yum/centos/###DISTRO_MAJOR###/x86_64
gpgkey=https://archive.mariadb.org/PublicKey
       https://supplychain.mariadb.com/MariaDB-Server-GPG-KEY
gpgcheck=1
___END_REPO_TEMPLATE___

use constant mysql_repo_template => <<'___END_REPO_TEMPLATE___';
[Mysql-connectors-community]
name=MySQL Connectors Community
baseurl=https://repo.mysql.com/yum/mysql-connectors-community/el/###DISTRO_MAJOR###/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql-2023
       https://repo.mysql.com/RPM-GPG-KEY-MySQL-2022
       https://repo.mysql.com/RPM-GPG-KEY-mysql
[Mysql-tools-community]
name=MySQL Tools Community
baseurl=https://repo.mysql.com/yum/mysql-tools-community/el/###DISTRO_MAJOR###/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql-2023
       https://repo.mysql.com/RPM-GPG-KEY-MySQL-2022
       https://repo.mysql.com/RPM-GPG-KEY-mysql
[Mysql###MYSQL_FLAT_VERSION_SHORT###-community]
name=MySQL ###MYSQL_VERSION_SHORT### Community Server
baseurl=https://repo.mysql.com/yum/mysql-###MYSQL_VERSION_SHORT###-community/el/###DISTRO_MAJOR###/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql-2023
       https://repo.mysql.com/RPM-GPG-KEY-MySQL-2022
       https://repo.mysql.com/RPM-GPG-KEY-mysql
[Mysql-tools-preview]
name=MySQL Tools Preview
baseurl=https://repo.mysql.com/yum/mysql-tools-preview/el/###DISTRO_MAJOR###/$basearch/
enabled=0
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql-2023
       https://repo.mysql.com/RPM-GPG-KEY-MySQL-2022
       https://repo.mysql.com/RPM-GPG-KEY-mysql
___END_REPO_TEMPLATE___

use constant supports_postgresql => 1;

use constant package_descriptions => {
    'short' => 'summary',
    'long'  => 'description',
};

1;


} # --- END Cpanel/OS/Rhel.pm


{ # --- BEGIN Cpanel/OS/Almalinux.pm
package Cpanel::OS::Almalinux;


use cPstrict;

# use Cpanel::OS::Rhel();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel); }

use constant is_supported => 0;

use constant pretty_distro => 'AlmaLinux';

1;


} # --- END Cpanel/OS/Almalinux.pm


{ # --- BEGIN Cpanel/OS/Rhel6.pm
package Cpanel::OS::Rhel6;


use cPstrict;

# use Cpanel::OS::Rhel();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel); }

use constant is_supported => 0;

use constant binary_sync_source         => 'linux-c6-x86_64';
use constant package_release_distro_tag => '~el6';

use constant service_manager                    => 'initd';
use constant unsupported_db_versions            => [qw/10.5 10.6/];
use constant mariadb_versions_use_repo_template => [qw/10.0 10.1 10.2 10.3/];
use constant mysql_versions_use_repo_template   => [qw/8.0/];

use constant dns_supported => [qw{ bind }];

use constant who_wins_if_soft_gt_hard => 'hard';

use constant postgresql_minimum_supported_version => '7.4';

use constant postgresql_packages => [
    qw{
      postgresql      postgresql-devel    postgresql-libs     postgresql-server
      rh-postgresql   rh-postgresql-devel rh-postgresql-libs  rh-postgresql-server
    }
];

use constant postgresql_service_aliases => [qw/rhdb/];
use constant postgresql_initdb_commands => ['/sbin/service postgresql initdb'];

1;


} # --- END Cpanel/OS/Rhel6.pm


{ # --- BEGIN Cpanel/OS/Rhel7.pm
package Cpanel::OS::Rhel7;


use cPstrict;

# use Cpanel::OS::Rhel6();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel6); }

use constant is_supported => 1;    # Rhel 7 support

use constant binary_sync_source         => 'linux-c7-x86_64';
use constant package_release_distro_tag => '~el7';

use constant service_manager                    => 'systemd';
use constant unsupported_db_versions            => [];
use constant mariadb_versions_use_repo_template => [qw/10.0 10.1 10.2 10.3 10.5 10.6/];
use constant mysql_versions_use_repo_template   => [qw/5.7 8.0/];

use constant dns_supported => [qw{ bind powerdns }];

use constant who_wins_if_soft_gt_hard => 'soft';

use constant postgresql_minimum_supported_version => '9.2';
use constant postgresql_service_aliases           => [];
use constant postgresql_initdb_commands           => ['/usr/bin/postgresql-setup initdb'];

use constant check_ntpd_pid_method => 'systemd_ntpd';

sub packages_supplemental ($self) {
    my @packages = $self->SUPER::packages_supplemental()->@*;
    push @packages, qw/ncurses-term perl-Try-Tiny perl-local-lib/;

    return [ sort @packages ];
}

sub packages_supplemental_epel ($self) {
    my @packages = $self->SUPER::packages_supplemental_epel()->@*;

    push @packages, qw/dpkg/;

    @packages = grep {
        my $p = $_;
        !grep { $p eq $_ } qw/perl-Try-Tiny perl-local-lib/;
    } @packages;

    return [ sort @packages ];
}

sub packages_required ($self) {
    my @packages = $self->SUPER::packages_required()->@*;
    @packages = grep {
        my $p = $_;
        !grep { $p eq $_ } qw/db4 db4-devel iptables-ipv6 lcms procps tmpwatch util-linux-ng/
    } @packages;
    push @packages, qw/libdb libmount net-tools procps-ng psmisc python-tools/;

    return [ sort @packages ];
}

1;


} # --- END Cpanel/OS/Rhel7.pm


{ # --- BEGIN Cpanel/OS/Rhel8.pm
package Cpanel::OS::Rhel8;


use cPstrict;

# use Cpanel::OS::Linux ();    # ea4tooling_all
# use Cpanel::OS::Rhel7();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel7); }

use constant is_supported => 0;    # Rhel 8 is NOT supported but we use it as a base class for all Rhel derivatives.

use constant binary_sync_source => 'linux-c8-x86_64';

use constant ea4_modern_openssl  => '/usr/bin/openssl';
use constant firewall            => 'firewalld_nftables';
use constant firewall_module     => 'NFTables';
use constant supports_hostaccess => 0;
use constant package_manager     => 'dnf';

use constant package_release_distro_tag => '~el8';

use constant kernel_supports_fs_protected_regular => 1;

use constant can_clean_plugins_repo => 0;

use constant mysql_community_packages          => [qw/mysql-community-server mysql-community-devel/];    # Removed mysql-community-libs-compat in RHEL 8
use constant mysql_default_version             => '8.0';
use constant mariadb_minimum_supported_version => '10.3';

use constant postgresql_packages => [
    qw{
      postgresql      postgresql-devel    postgresql-libs     postgresql-server
    }
];

use constant openssl_escapes_subjects => 1;

use constant ea4tooling_dnsonly => ['dnf-plugin-universal-hooks'];
use constant ea4tooling         => [ 'dnf-plugin-universal-hooks', Cpanel::OS::Linux->ea4tooling_all->@* ];

use constant package_repositories => [qw/epel powertools/];

use constant system_package_providing_perl => 'perl-interpreter';

use constant retry_rpm_cmd_no_tty_hack => 1;

use constant check_ntpd_pid_method => 'pid_check_var_run_ntpd';
use constant has_tcp_wrappers      => 0;

use constant ea4_install_from_profile_enforce_packages => 1;

use constant repos_requires_dump_flag => 1;

use constant system_exclude_rules => {
    'dovecot'     => 'dovecot*',
    'php'         => 'php*',
    'exim'        => 'exim*',
    'pure-ftpd'   => 'pure-ftpd*',
    'proftpd'     => 'proftpd*',
    'p0f'         => 'p0f',
    'filesystem'  => 'filesystem',
    'kernel'      => 'kernel kernel-xen kernel-smp kernel-pae kernel-PAE kernel-SMP kernel-hugemem kernel-debug* kernel-core kernel-modules*',
    'kmod-'       => 'kmod-[a-z]*',
    'bind-chroot' => 'bind-chroot',
};

use constant bin_needs_restarting => q[/usr/bin/needs-restarting];

sub packages_supplemental ($self) {
    my @packages = $self->SUPER::packages_supplemental()->@*;

    @packages = grep {
        my $p = $_;
        !grep { $p eq $_ } qw/ncurses-term python-devel python-tools quota-devel tcp_wrappers-devel/
    } @packages;
    push @packages, qw{ python2-devel };

    return [ sort @packages ];
}

sub packages_required ($self) {
    my @packages = $self->SUPER::packages_required()->@*;

    @packages = grep {
        my $p = $_;
        !grep { $p eq $_ } qw/compat-db gd-progs libdb libmount procps-ng psmisc python python-docs python-setuptools python-tools rdate /
    } @packages;
    push @packages, qw/dnf glibc-locale-source mailx nftables python2 python2-docs python2-setuptools python2-tools python3-dnf python3-docs python3-libdnf python3-setuptools python36 util-linux-user sqlite cmake-filesystem/;

    return [ sort @packages ];
}

use constant nat_server_buffer_connections => 2;

1;


} # --- END Cpanel/OS/Rhel8.pm


{ # --- BEGIN Cpanel/OS/Almalinux8.pm
package Cpanel::OS::Almalinux8;


use cPstrict;

use Cpanel::OS::Almalinux;
# use Cpanel::OS::Rhel8();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel8); }

use constant is_supported => 1;    # Almalinux 8

use constant pretty_distro => Cpanel::OS::Almalinux->pretty_distro;

use constant supports_imunify_360 => 1;

use constant supports_cpanel_cloud_edition => 1;

1;


} # --- END Cpanel/OS/Almalinux8.pm


{ # --- BEGIN Cpanel/OS/Centos.pm
package Cpanel::OS::Centos;


use cPstrict;

# use Cpanel::OS::Rhel();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel); }

use constant is_supported => 0;    # Base OS class for all Centos derivatives.

use constant pretty_distro => 'CentOS';

1;


} # --- END Cpanel/OS/Centos.pm


{ # --- BEGIN Cpanel/OS/Centos7.pm
package Cpanel::OS::Centos7;


use cPstrict;

use Cpanel::OS::Centos;
# use Cpanel::OS::Rhel7();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel7); }

use constant is_supported => 1;    # Centos 7

use constant pretty_distro => Cpanel::OS::Centos->pretty_distro;

use constant supports_imunify_360 => 1;

use constant can_be_elevated => 1;
use constant can_elevate_to  => [qw(Almalinux8)];

use constant needs_els => 1;

1;


} # --- END Cpanel/OS/Centos7.pm


{ # --- BEGIN Cpanel/OS/Cloudlinux.pm
package Cpanel::OS::Cloudlinux;


use cPstrict;

# use Cpanel::OS::Rhel();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel); }

use constant is_supported => 0;    # Base class for CL.

use constant is_cloudlinux => 1;

use constant pretty_distro => 'CloudLinux';

use constant ea4_yum_tooling => [qw{ yum-plugin-universal-hooks ea-cpanel-tools ea-profiles-cloudlinux }];
use constant ea4_dnf_tooling => [qw{ dnf-plugin-universal-hooks ea-cpanel-tools ea-profiles-cloudlinux }];

use constant supports_kernelcare_free => 0;

1;


} # --- END Cpanel/OS/Cloudlinux.pm


{ # --- BEGIN Cpanel/OS/Cloudlinux6.pm
package Cpanel::OS::Cloudlinux6;


use cPstrict;

# use Cpanel::OS ();
use Cpanel::OS::Cloudlinux;

# use Cpanel::OS::Rhel6();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel6); }

use constant is_cloudlinux => 1;

use constant default_uid_min => 500;
use constant default_gid_min => 500;

use constant setup_tz_method => q[sysconfig];

use constant pretty_distro => Cpanel::OS::Cloudlinux->pretty_distro;

use constant ea4_install_repo_from_package => 1;
use constant ea4_from_pkg_url              => 'https://repo.cloudlinux.com/cloudlinux/EA4/cloudlinux-ea4-release-latest-6.noarch.rpm';
use constant ea4_from_pkg_reponame         => 'cloudlinux-ea4-release';
use constant ea4_from_custom_repo_url      => undef;
use constant ea4_from_custom_repo_path     => undef;

use constant ea4tooling => Cpanel::OS::Cloudlinux->ea4_yum_tooling;

use constant supports_kernelcare_free => Cpanel::OS::Cloudlinux->supports_kernelcare_free;

use constant has_quota_support_for_xfs    => 0;
use constant program_to_apply_kernel_args => 'none';

use constant ssh_supported_algorithms => [qw{ ecdsa rsa }];

use constant supports_inetd                   => 1;
use constant supports_syslogd                 => 1;
use constant install_gcc_from_slc6_devtoolset => 1;
use constant is_systemd                       => 0;

use constant openssl_minimum_supported_version => 0;    # check skipped on CL6
use constant has_cloudlinux_enhanced_quotas    => 1;
use constant can_become_cloudlinux             => 0;
use constant supports_imunify_360              => 1;

use constant outdated_services_check => q[centos6];

use constant support_needs_minor_at_least_at => 6;

sub packages_required ($self) {
    my @packages = $self->SUPER::packages_required()->@*;
    push @packages, qw/alt-libcurlssl alt-libxml2/;
    return [ sort @packages ];
}

sub is_supported {

    my $needs_minor = Cpanel::OS::support_needs_minor_at_least_at();
    return 0 if defined $needs_minor && Cpanel::OS::minor() < $needs_minor;

    return 1;
}

1;


} # --- END Cpanel/OS/Cloudlinux6.pm


{ # --- BEGIN Cpanel/OS/Cloudlinux7.pm
package Cpanel::OS::Cloudlinux7;


use cPstrict;

use Cpanel::OS::Cloudlinux;
# use Cpanel::OS::Rhel7();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel7); }

use constant is_supported  => 1;    # Cloudlinux 7
use constant is_cloudlinux => 1;

use constant pretty_distro => Cpanel::OS::Cloudlinux->pretty_distro;

use constant can_be_elevated => 1;
use constant can_elevate_to  => [qw(Cloudlinux8)];

use constant ea4_install_repo_from_package => 1;
use constant ea4_from_pkg_url              => 'https://repo.cloudlinux.com/cloudlinux/EA4/cloudlinux-ea4-release-latest-7.noarch.rpm';
use constant ea4_from_pkg_reponame         => 'cloudlinux-ea4-release';
use constant ea4_from_custom_repo_url      => undef;
use constant ea4_from_custom_repo_path     => undef;

use constant ea4tooling => Cpanel::OS::Cloudlinux->ea4_yum_tooling;

use constant supports_kernelcare_free => Cpanel::OS::Cloudlinux->supports_kernelcare_free;

use constant has_cloudlinux_enhanced_quotas => 1;
use constant program_to_apply_kernel_args   => 'none';
use constant can_become_cloudlinux          => 0;
use constant supports_imunify_360           => 1;

1;


} # --- END Cpanel/OS/Cloudlinux7.pm


{ # --- BEGIN Cpanel/OS/Cloudlinux8.pm
package Cpanel::OS::Cloudlinux8;


use cPstrict;

use Cpanel::OS::Cloudlinux;
# use Cpanel::OS::Rhel8();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel8); }

use constant is_supported => 1;    # Cloudlinux 8

use constant is_cloudlinux => 1;

use constant pretty_distro => Cpanel::OS::Cloudlinux->pretty_distro;

use constant ea4_install_from_profile_enforce_packages => 0;

use constant ea4_install_repo_from_package => 1;
use constant ea4_from_pkg_url              => 'https://repo.cloudlinux.com/cloudlinux/EA4/cloudlinux-ea4-release-latest-8.noarch.rpm';
use constant ea4_from_pkg_reponame         => 'cloudlinux-ea4-release';
use constant ea4_from_custom_repo_url      => undef;
use constant ea4_from_custom_repo_path     => undef;
use constant ea4_testing_yum_repo          => 'cl-ea4-testing';

use constant ea4tooling           => Cpanel::OS::Cloudlinux->ea4_dnf_tooling;
use constant package_repositories => [qw/cloudlinux-PowerTools epel/];

use constant supports_kernelcare_free       => Cpanel::OS::Cloudlinux->supports_kernelcare_free;
use constant has_cloudlinux_enhanced_quotas => 1;
use constant can_become_cloudlinux          => 0;
use constant supports_imunify_360           => 1;

1;


} # --- END Cpanel/OS/Cloudlinux8.pm


{ # --- BEGIN Cpanel/OS/Ubuntu.pm
package Cpanel::OS::Ubuntu;


use cPstrict;

# use Cpanel::OS::Linux ();    # ea4tooling_all
# use Cpanel::OS::Linux();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Linux); }
use constant is_supported => 0;

use constant nogroup         => q[nogroup];
use constant sudoers         => 'sudo';       # Warning: need to change dynamicui.conf when updating this value
use constant has_wheel_group => 0;

use constant default_sys_uid_min => 100;
use constant default_sys_gid_min => 100;

use constant pretty_distro => 'Ubuntu';

use constant firewall               => 'ufw_iptables';
use constant firewall_module        => 'IpTables';
use constant networking             => 'netplan';
use constant sysconfig_network      => undef;
use constant package_manager        => 'apt';
use constant package_manager_module => 'Apt';
use constant is_apt_based           => 1;
use constant is_yum_based           => 0;
use constant is_rpm_based           => 0;
use constant base_distro            => 'debian';

use constant supports_cpaddons => 0;

use constant kernel_supports_fs_protected_regular => 1;

use constant rpm_versions_system => 'ubuntu';
use constant packages_arch       => 'amd64';

use constant mariadb_versions_use_repo_template => [];
use constant mysql_versions_use_repo_template   => ['8.0'];

use constant db_package_manager_key_params => {
    method => 'add_repo_key_by_id',

    keys => [
        'A8D3785C',    # For MySQL 8.0.36 and up
        '3A79BD29',    # For MySQL 8.0.28 and up
        '5072E1F5',    # For MySQL 8.0.27 and below
        'C74CD1D8',    # For all MariaDB versions
    ],
};

use constant who_wins_if_soft_gt_hard => 'hard';

use constant security_service                => 'apparmor';
use constant cron_bin_path                   => '/usr/sbin/cron';
use constant systemd_service_name_map        => { 'crond' => 'cron' };
use constant ea4_modern_openssl              => '/usr/bin/openssl';
use constant kernel_package_pattern          => '^linux-image-[0-9]';
use constant check_kernel_version_method     => q[boot-vmlinuz-file];
use constant stock_kernel_version_regex      => qr/-(?:(?:(?:generic|lowlatency)(?:-hwe)?)|kvm|aws|azure|gcp|oracle)$/;
use constant openssl_escapes_subjects        => 1;
use constant prelink_config_path             => '/etc/default/prelink';
use constant pam_file_controlling_crypt_algo => 'common-password';
use constant user_crontab_dir                => '/var/spool/cron/crontabs';

use constant supports_kernelcare      => 1;
use constant supports_kernelcare_free => 1;

use constant iptables_ipv4_savefile => '/etc/iptables/rules.v4';
use constant iptables_ipv6_savefile => '/etc/iptables/rules.v6';

use constant mysql_incompatible => [
    qw{
      default-mysql-server
      default-mysql-server-core
      mariadb-client
      mariadb-client-10.3
      mariadb-server
      mariadb-server-10.3
      mariadb-test
      mysql-client-8.0
      mysql-server-8.0
      mysql-testsuite
      mysql-testsuite-8.0
    }
];

use constant mysql_community_packages          => [qw/mysql-community-server mysql-shell libmysqlclient-dev/];
use constant mysql_dependencies                => [qw/libdbi-perl passwd adduser login coreutils/];
use constant mysql_default_version             => '8.0';
use constant mariadb_minimum_supported_version => '10.3';

use constant outdated_services_check  => q[needrestart_b];
use constant outdated_processes_check => q[checkrestart];
use constant check_reboot_method      => q[check-reboot-required];
use constant bin_needs_restarting     => undef;                      # The needs-restarting program is not supported on Ubuntu, so blank it out to reduce confusion.

use constant syslog_service_name         => 'rsyslog';
use constant rsyslog_triggered_by_socket => 1;
use constant ea4_from_custom_repo_url    => 'https://securedownloads.cpanel.net/EA4/EA4.list';
use constant ea4_from_custom_repo_path   => '/etc/apt/sources.list.d/EA4.list';

use constant ea4_conflicting_apache_distro_packages => [qw( apache2 apache2-utils php-cli )];

use constant ea4tooling_dnsonly => ['apt-plugin-universal-hooks'];
use constant ea4tooling         => [ 'apt-plugin-universal-hooks', Cpanel::OS::Linux->ea4tooling_all->@* ];
use constant system_exclude_rules => {
    'dovecot'    => 'dovecot*',
    'exim'       => 'exim*',
    'filesystem' => 'base-files',                                   # block Ubuntu updates to current installed version (20.04)
    'kernel'     => 'linux-headers* linux-image* linux-modules*',
    'nsd'        => 'nsd',
    'p0f'        => 'p0f',
    'php'        => 'php*',
    'proftpd'    => 'proftpd*',
    'pure-ftpd'  => 'pure-ftpd*',

};

use constant packages_supplemental => [

    'nfs-common',

    qw{
      libcpan-perl-releases-perl
      libexpect-perl
      libio-pty-perl
      libjson-xs-perl
      liblocal-lib-perl
      libmodule-build-perl
      libtry-tiny-perl
      libwww-perl
      libyaml-syck-perl
      lsof
      nscd
      rpm
      strace
      sysstat
      tcpd
      util-linux
    }
];

use constant can_clean_plugins_repo => 0;

use constant jetbackup_repo_pkg => 'https://repo.jetlicense.com/ubuntu/jetapps-repo-latest_amd64.deb';

use constant repo_suffix => 'list';
use constant repo_dir    => '/etc/apt/sources.list.d';

use constant packages_required => [
    qw{
      acl
      apt-file
      apt-transport-https
      aspell
      at
      bind9
      bind9-libs
      bind9-utils
      binutils
      bzip2
      coreutils
      cpio
      cpp
      cracklib-runtime
      cron
      curl
      debian-goodies
      debianutils
      e2fsprogs
      expat
      file
      g++
      g++-9
      gawk
      gcc
      gdbmtool
      gettext
      glibc-source
      gnupg2
      graphicsmagick-imagemagick-compat
      gzip
      icu-devtools
      iptables
      iptables-persistent
      language-pack-en-base
      less
      libaio1
      libapt-pkg-perl
      libboost-program-options1.71.0
      libcairo2-dev
      libcrack2
      libdb5.3
      libevent-2.1-7
      libfile-fcntllock-perl
      libfontconfig1-dev
      libgcc1
      libgd-tools
      libgd3
      libgmp10
      libgomp1
      libicu-dev
      libicu66
      libidn11
      libjpeg-turbo8
      liblua5.3-dev
      libmount1
      libmysqlclient21
      libncurses5
      libpam0g
      libpam0g-dev
      libpango-1.0-0
      libpangocairo-1.0-0
      libpcap0.8
      libpcre2-8-0
      libpcre2-posix2
      libpcre3
      libpixman-1-0
      libpng16-16
      libpopt0
      libreadline-dev
      libssl-dev
      libstdc++-9-dev
      libstdc++6
      libtiff5
      libuser
      libxml2
      libxml2-dev
      libxslt1.1
      libzip5
      linux-libc-dev
      lsof
      make
      nano
      needrestart
      net-tools
      openssh-client
      openssh-server
      openssl
      passwd
      patch
      pcre2-utils
      procps
      python-setuptools
      python2
      python2-doc
      python2.7-dev
      quota
      rdate
      rsync
      sed
      smartmontools
      ssl-cert
      sysstat
      tar
      unzip
      usrmerge
      wget
      xz-utils
      zip
      zlib1g
    }
];

use constant package_ImageMagick_Devel => 'libmagick++-6.q16-dev';
use constant package_crond             => 'cron';

use constant system_package_providing_perl => 'perl-base';

use constant bin_grub_mkconfig            => q[/usr/sbin/grub-mkconfig];
use constant program_to_apply_kernel_args => 'grub-mkconfig';

use constant package_descriptions => {
    'short' => 'description',
    'long'  => 'longdesc',
};

use constant nat_server_buffer_connections => 2;

1;


} # --- END Cpanel/OS/Ubuntu.pm


{ # --- BEGIN Cpanel/OS/Ubuntu20.pm
package Cpanel::OS::Ubuntu20;


use cPstrict;

# use Cpanel::OS::Ubuntu();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Ubuntu); }

use constant is_supported => 1;

use constant binary_sync_source         => 'linux-u20-x86_64';
use constant package_release_distro_tag => '~u20';

use constant maillog_path => '/var/log/mail.log';

use constant plugins_repo_url => 'https://securedownloads.cpanel.net/cpanel-plugins/cpanel-plugins.list';

use constant supports_imunify_360 => 1;

use constant supports_cpanel_cloud_edition => 1;

use constant mysql_repo_template => <<'___END_REPO_TEMPLATE___';
deb https://repo.mysql.com/apt/ubuntu/ focal mysql-apt-config
deb https://repo.mysql.com/apt/ubuntu/ focal mysql-###MYSQL_VERSION_SHORT###
deb https://repo.mysql.com/apt/ubuntu/ focal mysql-tools
deb-src https://repo.mysql.com/apt/ubuntu/ focal mysql-###MYSQL_VERSION_SHORT###
___END_REPO_TEMPLATE___

use constant quota_packages_conditional => {

    'linux-aws'             => ['linux-modules-extra-aws'],
    'linux-aws-edge'        => ['linux-modules-extra-aws-edge'],
    'linux-aws-lts-20.04'   => ['linux-modules-extra-aws-lts-20.04'],
    'linux-azure'           => ['linux-modules-extra-azure'],
    'linux-azure-cvm'       => ['linux-modules-extra-azure-cvm'],
    'linux-azure-edge'      => ['linux-modules-extra-azure-edge'],
    'linux-azure-fde'       => ['linux-modules-extra-azure-fde'],
    'linux-azure-lts-20.04' => ['linux-modules-extra-azure-lts-20.04'],
    'linux-gcp'             => ['linux-modules-extra-gcp'],
    'linux-gcp-edge'        => ['linux-modules-extra-gcp-edge'],
    'linux-gcp-lts-20.04'   => ['linux-modules-extra-gcp-lts-20.04'],
    'linux-gke'             => ['linux-modules-extra-gke'],
    'linux-gke-5.4'         => ['linux-modules-extra-gke-5.4'],
    'linux-gkeop'           => ['linux-modules-extra-gkeop'],
    'linux-gkeop-5.4'       => ['linux-modules-extra-gkeop-5.4'],
    'linux-ibm'             => ['linux-modules-extra-ibm'],
    'linux-ibm-lts-20.04'   => ['linux-modules-extra-ibm-lts-20.04'],

    'linux-virtual'                => ['linux-image-extra-virtual'],
    'linux-virtual-hwe-20.04'      => ['linux-image-extra-virtual-hwe-20.04'],
    'linux-virtual-hwe-20.04-edge' => ['linux-image-extra-virtual-hwe-20.04-edge'],
};

1;


} # --- END Cpanel/OS/Ubuntu20.pm


{ # --- BEGIN Cpanel/OS/Rocky.pm
package Cpanel::OS::Rocky;


use cPstrict;

# use Cpanel::OS::Rhel();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel); }

use constant is_supported => 0;

use constant pretty_distro => 'Rocky Linux';

1;


} # --- END Cpanel/OS/Rocky.pm


{ # --- BEGIN Cpanel/OS/Rocky8.pm
package Cpanel::OS::Rocky8;


use cPstrict;

use Cpanel::OS::Rocky;
# use Cpanel::OS::Rhel8();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::OS::Rhel8); }

use constant is_supported => 1;    # Rockylinux 8

use constant pretty_distro => Cpanel::OS::Rocky->pretty_distro;

use constant supports_imunify_360 => 1;

1;


} # --- END Cpanel/OS/Rocky8.pm


{ # --- BEGIN Cpanel/OS/All.pm
package Cpanel::OS::All;


use cPstrict;
use utf8;

# use Cpanel::OS::Almalinux8  ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Centos7     ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Cloudlinux6 ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Cloudlinux7 ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Cloudlinux8 ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Rhel7       ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Ubuntu20    ();    # PPI USE OK - fatpack usage
# use Cpanel::OS::Rocky8      ();    # PPI USE OK - fatpack usage

sub supported_distros() {
    return (
        [ Almalinux  => 8 ],
        [ Centos     => 7 ],
        [ Cloudlinux => 6 ],
        [ Cloudlinux => 7 ],
        [ Cloudlinux => 8 ],
        [ Rhel       => 7 ],
        [ Rocky      => 8 ],
        [ Ubuntu     => 20 ],
    );
}

sub advertise_supported_distros() {

    my $current_name;
    my $current_versions = [];

    my $advertise = '';

    my $map_os_display_name = {
        'Almalinux'  => 'AlmaLinux',
        'Centos'     => 'CentOS',
        'Rhel'       => 'Red Hat Enterprise Linux',
        'Cloudlinux' => 'CloudLinux&reg;',
        'Rocky'      => 'Rocky Linux&trade;',
    };

    foreach my $d ( supported_distros() ) {
        my ( $name, $version ) = $d->@*;

        if ( !defined $current_name ) {
            $current_name = $name;
            push $current_versions->@*, $version;
            next;
        }

        if ( $current_name eq $name ) {
            push $current_versions->@*, $version;
        }
        else {
            my $display_name = $map_os_display_name->{$current_name} // $current_name;
            $advertise .= $display_name . ' ' . join( '/', $current_versions->@* ) . ', ';
            $current_name     = $name;
            $current_versions = [$version];
        }
    }

    if ( defined $current_name ) {
        my $display_name = $map_os_display_name->{$current_name} // $current_name;
        $advertise .= $display_name . ' ' . join( '/', $current_versions->@* );
    }

    return $advertise;
}

1;


} # --- END Cpanel/OS/All.pm


{ # --- BEGIN Cpanel/OS.pm
package Cpanel::OS;


use cPstrict;

use Carp                         ();
# use Cpanel::OS::SysPerlBootstrap ();
# use Cpanel::LoadModule           ();

our $VERSION = '2.0';

sub _new_instance ( $os, $distro, $major, $minor, $build ) {
    my $distro_class = 'Cpanel::OS::' . ucfirst($distro) . $major;

    if ( !eval "require $distro_class; 1" ) {    ## no critic qw(ProhibitStringyEval) -- This is how we do a runtime load here.
        require Cpanel::OS::Linux;               # PPI USE OK -- used just after
        $distro_class = q[Cpanel::OS::Linux];    # unsupported distro

        $os //= q[Unknown];
    }

    my $self = bless {
        os     => $os,
        distro => $distro,
        major  => $major,
        minor  => $minor,
        build  => $build,
    }, $distro_class;

    return $self;
}

my $instance;

sub clear_cache {
    $INC{'Test/Cpanel/Policy.pm'} or Carp::croak("This interface is only for unit testing");
    undef $instance;

    return;
}

sub clear_cache_after_cloudlinux_update {
    undef $instance;
    return;
}

sub _instance {    ## no critic(RequireArgUnpacking) - Most of the time we do not need to process args.
    return $instance if $instance;

    Carp::croak("Cpanel::OS may not be called during cPanel binary compilation") if $INC{'B/C.pm'};

    my ( $os, $distro, $major, $minor, $build ) = @_;
    if ( !length $build ) {
        ( $os, $distro, $major, $minor, $build ) = Cpanel::OS::SysPerlBootstrap::get_os_info('DO NOT USE THIS CALL');
    }

    return $instance = _new_instance( $os, $distro, $major, $minor, $build );
}

sub flush_disk_caches {
    local $!;

    return 0 if readlink Cpanel::OS::SysPerlBootstrap::CACHE_FILE_CUSTOM;
    unlink Cpanel::OS::SysPerlBootstrap::CACHE_FILE;

    return 1;
}

sub distro { return _instance()->{'distro'} }
sub major  { return _instance()->{'major'} }
sub minor  { return _instance()->{'minor'} }
sub build  { return _instance()->{'build'} }

my %methods;

BEGIN {

    %methods = map { $_ => 0 } (
        'is_supported',                       # This OS is supported by cPanel and not a virtual class (these exist!).
        'eol_advice',                         # Additional information provided to updatenow blockers when the customer tries to upgrade on a removed distro.
        'support_needs_minor_at_least_at',    # miniimum minor version we support for this distro (optional
        'is_experimental',                    # Defines if this distro is in experimental state or not.
        'experimental_url',                   # Provides a link to information about the experimental state if it's currently that way.
        'arch',                               # Somewhat of an unnecessary variable as all of our distros are set to x86_64.
        'service_manager',                    # Does this distro use systemd or initd to manage services?
        'is_systemd',                         # Easy boolean helper we use in most places to determine if the local system uses systemd.
        'base_distro',                        # What is the root distro this distro is derived from? rhel/debian
        'pretty_distro',                      # What is the preferred stylization of the distro name when being displayed for a user?
        'display_name',                       # Example: Centos v7.9.2009
        'display_name_lite',                  # Example: centos 7
        'cpanalytics_cpos',                   # How should we present data regarding the OS to Google Analytics?
        'binary_sync_source',                 # Provides the string corresponding to the binary sync source directory.

        'nobody',                             # name of the user used for nobody
        'nogroup',                            # name of the group used for nobody / nogroup

        'sudoers',                            # name of the group used for sudo (by sudoers)
        'has_wheel_group',                    # flag for whether wheel group is needed by sudo

        'default_uid_min',                    # default value from /etc/login.defs
        'default_gid_min',                    # default value from /etc/login.defs
        'default_sys_uid_min',                # default value from /etc/login.defs
        'default_sys_gid_min',                # default value from /etc/login.defs

        'has_tcp_wrappers',                   # The distro supports TPC wrappers.

        'setup_tz_method',                    # what method to use to setup a timezone
        'is_cloudlinux',                      # is it a CloudLinux based distro? boolean

        'can_be_elevated',                    # ELevate supports current OS as a source
        'can_elevate_to',                     # ELevate can directly convert the current OS to these other OSes listed in the arrayref

        'rsyslog_triggered_by_socket',        # Is rsyslog triggered by syslog.socket

        'has_quota_support_for_xfs',          # Does this distro support xfs quota?
        'program_to_apply_kernel_args',       # What program do we need to run to ensure that kernels are booted with updated args?
        'has_cloudlinux_enhanced_quotas',     # Cloud linux does fancy things with quota we need to know about.
        'who_wins_if_soft_gt_hard',           # If we try to set a soft quota higher than a hard quota, which value wins?
        'quota_packages_conditional',         # Hashref of needed kernel package dependencies not encoded in the upstream distro in order for quotas to work

        'bin_grub_mkconfig',                  # path to sbin/grub2-mkconfig

        'bin_needs_restarting',               # path to needs-restarting binary

        'outdated_services_check',            # which method to use to check outdated services?
        'outdated_processes_check',           # which method to use to check outdated processes?
        'check_reboot_method',                # which method to use to check if we need to reboot

        'dns_supported',                      # Provides a list of dns servers supported on this platform.
        'dns_named_basedir',                  # The path to the bind nameserver files.
        'dns_named_conf',                     # /etc/named.conf
        'dns_named_log',                      # What dir named logs are stored (/var/log/named)

        'ssh_supported_algorithms',           # list of supported ssh algo [ordered by preference]

        'openssl_minimum_supported_version',  # minimum openssl version to run
        'openssl_escapes_subjects',           # On generated certs, openssl started escaping subject lines at some point...


        'unsupported_db_versions',                 # What DB versions does this distro NOT support.
        'db_package_manager_key_params',           # Hashref describing what to do to ensure keys are in place for DBMSes installed from a 3rdparty repo
        'mysql_versions_use_repo_template',        # Which MySQL versions use mysql_repo_template.
        'mariadb_versions_use_repo_template',      # Which MariaDB versions use mariadb_repo_template.
        'mysql_repo_template',                     # What goes in the repo file to download mysql packages.
        'mariadb_repo_template',                   # What goes in the repo file to download mariadb packages.
        'mariadb_minimum_supported_version',       # Minimum version of MariaDB supported
        'mysql_community_packages',                # Which MySQL packages need to be installed on this distro?
        'mysql_dependencies',                      # Which distro packages need to be installed for MySQL to be happy?
        'mysql_incompatible',                      # Which mysql packages need to be blocked as incompatible with cPanel packages on this distro?
        'mysql_default_version',                   # Default MySQL version to use
        'supports_postgresql',                     # Do we support PostgreSQL on this distro?
        'postgresql_minimum_supported_version',    # What is the minimum versions of PostgreSQL supported on this distro?
        'postgresql_packages',                     # What packages do we need to install?
        'postgresql_service_aliases',              # What aliases, if any, of the service name might we expect to find PostgreSQL using?
        'postgresql_initdb_commands',              # Which commands do we run to make PostgreSQL initialize its DB storage area?

        'ea4_install_repo_from_package',             # Does a RPM provide the EA4 repo or do we download the repo file?
        'ea4_from_pkg_url',                          # If we're installing the repo from RPM, where do we get it from?
        'ea4_from_pkg_reponame',                     # ... And what will the repo be called when we install it?
        'ea4_from_custom_repo_url',                  # Where can we download the repo file from? (needs to be over https)
        'ea4_from_custom_repo_path',                 # ... And where should we put it when we download it?
        'ea4tooling_all',                            # LIST - What are the packages to install which provide ea4 tooling on all server types?
        'ea4tooling',                                # LIST - What ea4 tooling packages do we install on full cpanel servers?
        'ea4tooling_dnsonly',                        # LIST - What additional packages do we need for dnsonly? << FACT CHECK
        'ea4_modern_openssl',                        # Which openssl should be used on this platform to get the L&G Stuff? EA4 provides one in the event the distro's version is insufficient.
        'ea4_testing_yum_repo',                      # undef or string with the name of the yum repo to enable
        'ea4_conflicting_apache_distro_packages',    # Conflicting packages that Cpanel::EA4::MigrateBlocker checks for
        'ea4_install_from_profile_enforce_packages',

        'package_manager',                           # which package manager does the distro use? ( yum/dnf/apt)
        'package_manager_module',                    # Cpanel::whatever::$package_manager_module::... ( Yum or Apt )
        'package_repositories',                      # what additional repos need to be installed and enabled to install needed software?
        'package_release_distro_tag',                # the postfix extension used for the packages: ~el6, ~el7, ~el8, ~el9, ~u20, ~u22
        'system_exclude_rules',                      # On yum based systems, how what will we block the main distro from installing
        'kernel_package_pattern',                    # What are the kernal packages named so we can sometimes block them when updating.
        'check_kernel_version_method',               # What method to use to check the kernel version
        'stock_kernel_version_regex',                # Regular expression used to determine whether the version string returned for the kernel matches what the distro would return with a stock kernel.
        'kernel_supports_fs_protected_regular',      # Does fs.protected_regular a valid settings
        'packages_required',                         # Which packages should /scripts/sysup assure are present on this system? ( provided during fresh install )
        'packages_supplemental',                     # Which packages should /scripts/sysup assure are present on this system? ( provided AFTER fresh install )
        'packages_supplemental_epel',                # Packages we want to install from epel if it is available to us.
        'is_apt_based',                              # Does this system use apt (and therefore deb packages) for package management?
        'is_yum_based',                              # Does this system use a yum or a yum derivative (dnf)
        'is_rpm_based',                              # Does this system do its package management with rpms?
        'system_package_providing_perl',             # Name of the package providing system Perl
        'retry_rpm_cmd_no_tty_hack',                 # Hack: retry RPM comand when no TTY
        'can_clean_plugins_repo',                    # Can we clean the 'plugins' repo
        'repos_requires_dump_flag',                  # shiykd we use '--dump' when enabling a repo
        'rpm_versions_system',                       # Which rpm_versions_system is currently used
        'packages_arch',                             # Default architecture used by the rpm.versions system
        'package_ImageMagick_Devel',                 # Name of the imagemagick devel package
        'package_MySQL_Shell',                       # Name of the mysql-shell package (installed on demand)
        'package_crond',                             # Name of the package providing the cron daemon
        'plugins_repo_url',                          # URL to .repo / .list for cpanel-plugins
        'repo_suffix',                               # Suffix for repo files, such as .repo or .list
        'repo_dir',                                  # Local directory path where system repo config files are stored for the package manager
        'package_descriptions',                      # Description fields used in manage plugins

        'supports_cpanel_cloud_edition',             # Is cPCloud supported by this distro?

        'supports_cpaddons',                         # Are cpaddons supported by this distro?
        'supports_kernelcare',                       # Is Kernel Care available for this distro?
        'supports_kernelcare_free',                  # Is Kernel Care Free available for this distro? << FACT CHECK (Note: This check implicitly ensures the system is not running CloudLinux)
        'supports_3rdparty_wpt',                     # Is Wordpress Toolkit supported on this platform?
        'supports_plugins_repo',                     # Is Cpanel::Plugins::Repo supported on this platform?
        'supports_or_can_become_cloudlinux',         # Does the system can become/or is CloudLinux?
        'can_become_cloudlinux',                     # Can the system become CloudLinux?
        'supports_imunify_av',                       # Can install Imunify AV
        'supports_imunify_av_plus',                  # Can install Imunify AV Plus
        'supports_imunify_360',                      # Can install Imunify AV 360
        'jetbackup_repo_pkg',                        # URL to the package we install to set up the JetBackup repo ( somewhere on http://repo.jetlicense.com/ )
        'supports_letsencrypt_v2',
        'supports_cpanel_analytics',

        'security_service',                          # What security service the distro is using? apparmor or selinux

        'firewall',                                  # Which firewall is this distro using? (iptables / firewalld_nftables / ufw_iptables)
        'firewall_module',                           # Which firewall module is used to manage it? (IpTables / NFTables)
        'networking',                                # Not sure what this is for. Nothing uses it. ( networkscripts / netplan ) << FACT CHECK
        'iptables_ipv4_savefile',                    # Where to store iptables rules for IPv4
        'iptables_ipv6_savefile',                    # Where to store iptables rules for IPv6
        'sysconfig_network',                         # sysconfig networ file to use, undef when unused.
        'supports_hostaccess',                       # Does the system provide support for /etc/hosts.allow, etc.?
        'supports_inetd',                            # Does the system provide support for inetd?
        'supports_syslogd',                          # Does the system provide support for syslogd?
        'install_gcc_from_slc6_devtoolset',          # Do we need to install a custom gcc for building?
        'check_ntpd_pid_method',                     # Method used to check the ntp daemon pid
        'syslog_service_name',                       # Name of the service that handles syslog data, such as syslog, rsyslog, rsyslogd, etc, eg: `/usr/bin/systemctl show -p MainPID rsyslog.service`
        'cron_bin_path',                             # Path to the cron daemon
        'systemd_service_name_map',                  # Map of service names to possible counterparts, such as crond -> cron
        'prelink_config_path',                       # Where do the control knobs for prelinking live?
        'pam_file_controlling_crypt_algo',           # Which file in /etc/pam.d manages the algorithm used to generate the passwd hash written to /etc/shadow for a user?
        'user_crontab_dir',                          # Path to directory where user crontabs are stored by the crontab binary
        'needs_els',                                 # Does this server require the ELS product

        'maillog_path',                              # Path to the mail.* syslog output as defined by the distro

        'nat_server_buffer_connections',             # Number of connections_required to trigger a test failure in simultaneous connections for NAT detection.
    );
}

sub supported_methods {
    return sort keys %methods;                       ##no critic qw( ProhibitReturnSort ) - this will always be a list.
}

our $AUTOLOAD;                                       # keep 'use strict' happy

sub AUTOLOAD {    ## no critic(RequireArgUnpacking) - Most of the time we do not need to process args.
    my $sub = $AUTOLOAD;
    $sub =~ s/.*:://;

    exists $methods{$sub} or Carp::croak("$sub is not a supported data variable for Cpanel::OS");

    my $i   = _instance();
    my $can = $i->can($sub) or Carp::croak( ref($i) . " does not implement $sub" );
    return $can->( $i, @_ );
}

sub list_contains_value ( $key, $value ) {
    my $array_ref = _instance()->$key;
    ref $array_ref eq 'ARRAY' or Carp::croak("$key is not a list!");
    if ( !defined $value ) {
        return ( grep { !defined $_ } @$array_ref ) ? 1 : 0;
    }
    return ( grep { $value eq $_ } @$array_ref ) ? 1 : 0;
}

sub DESTROY { }    # This is a must for autoload modules.


sub assert_unreachable_on_ubuntu ( $msg = "Ubuntu reached somewhere it shouldn't!" ) {
    Carp::croak($msg) if Cpanel::OS::base_distro() eq "debian";
    return;
}

sub lookup_pretty_distro ($target) {


    require Cpanel::OS::All;

    my ( $name, $major ) = ( $target =~ m/^([A-Za-z]+)([0-9]+)$/ );
    return if !$name || !$major;
    return unless grep { $_->[0] eq $name && $_->[1] == $major } Cpanel::OS::All::supported_distros();

    my $module = "Cpanel::OS::$target";
    Cpanel::LoadModule::load_perl_module($module);

    my $pretty_name = $module->pretty_distro;
    return "$pretty_name $major";
}

1;


} # --- END Cpanel/OS.pm


{ # --- BEGIN Cpanel/FileUtils/Lines.pm
package Cpanel::FileUtils::Lines;


use strict;
# use Cpanel::Debug ();
use IO::SigGuard  ();

use constant _ENOENT => 2;

our $VERSION = '1.0';

my $MAX_LINE_SIZE = 32768;

sub get_file_lines {
    my $cfgfile     = shift;
    my $line_number = shift;
    return if ( !$line_number || $line_number !~ m/^\d+$/ );

    my $numpadding = 7;
    my %ret;
    if ( open( my $cfg_fh, '<', $cfgfile ) ) {
        my $linecounter = 0;
        while ( readline($cfg_fh) ) {
            $linecounter++;
            if ( $linecounter < $line_number && $linecounter > ( $line_number - $numpadding ) ) {
                push @{ $ret{'previouslines'} }, { 'line' => $linecounter, 'data' => $_ };
            }
            elsif ( $linecounter > $line_number && $linecounter < ( $line_number + $numpadding ) ) {
                push @{ $ret{'afterlines'} }, { 'line' => $linecounter, 'data' => $_ };
            }
            elsif ( $linecounter == $line_number ) {
                push @{ $ret{'lines'} }, { 'line' => $linecounter, 'data' => $_ };
            }
            elsif ( $linecounter > ( $line_number + $numpadding ) ) {
                last;
            }
        }
        close $cfg_fh;
    }
    return \%ret;
}

sub get_last_lines {
    my $cfgfile = shift;
    my $number  = shift;
    if ( !$number || $number !~ m/^\d+$/ ) {
        $number = 10;
    }
    my @lines;

    if ( open( my $cfg_fh, '<', $cfgfile ) ) {
        my $size = ( stat($cfg_fh) )[7];
        if ( $size > ( $MAX_LINE_SIZE * $number ) ) {

            seek( $cfg_fh, $size - ( $MAX_LINE_SIZE * $number ), 0 );
        }
        my $linecounter = 0;
        while ( my $line = readline($cfg_fh) ) {
            chomp $line;
            if ( $linecounter >= $number ) {
                shift @lines;
            }
            push @lines, $line;
            $linecounter++;
        }
        close $cfg_fh;
    }
    else {
        Cpanel::Debug::log_warn("Unable to open $cfgfile: $!");
    }
    return wantarray ? @lines : \@lines;
}

sub has_txt_in_file {
    my ( $file, $txt ) = @_;

    my $regex;
    eval { $regex = qr($txt); };
    if ($@) {
        Cpanel::Debug::log_warn('Invalid regex');
        return;
    }

    my $fh;
    if ( open $fh, '<', $file ) {
        while ( my $line = readline $fh ) {
            if ( $line =~ $regex ) {
                close $fh;
                return 1;
            }
        }

        close $fh;
    }

    return;
}

sub appendline {
    my ( $filename, $line ) = @_;
    my $fh;

    if ( open my $fh, '>>:stdio', $filename ) {

        IO::SigGuard::syswrite( $fh, $line . "\n" ) or do {
            warn "write($filename): $!";
        };

        close $fh;
        return 1;
    }
    else {
        warn "open($filename): $!" if $! != _ENOENT();
    }

    return;
}

1;

} # --- END Cpanel/FileUtils/Lines.pm


{ # --- BEGIN Cpanel/FHUtils/Autoflush.pm
package Cpanel::FHUtils::Autoflush;



use strict;
use warnings;

sub enable {
    select( ( select( $_[0] ), $| = 1 )[0] );    ## no critic qw(InputOutput::ProhibitOneArgSelect Variables::RequireLocalizedPunctuationVars) - aka $socket->autoflush(1) without importing IO::Socket

    return;
}

1;

} # --- END Cpanel/FHUtils/Autoflush.pm


{ # --- BEGIN Cpanel/SafeRun/Simple.pm
package Cpanel::SafeRun::Simple;


use strict;

# use Cpanel::FHUtils::Autoflush ();
# use Cpanel::LoadFile::ReadFast ();
# use Cpanel::SV                 ();

BEGIN {
    eval { require Proc::FastSpawn; };
}

my $KEEP_STDERR  = 0;
my $MERGE_STDERR = 1;
my $NULL_STDERR  = 2;
my $NULL_STDOUT  = 3;

sub saferun_r {
    return _saferun_r( \@_ );
}

sub _saferun_r {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $cmdline, $error_flag ) = @_;

    if ($Cpanel::AccessIds::ReducedPrivileges::PRIVS_REDUCED) {    # PPI NO PARSE --  can't be reduced if the module isn't loaded
        eval "use Cpanel::Carp;";                                  ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        die Cpanel::Carp::safe_longmess( __PACKAGE__ . " cannot be used with ReducedPrivileges. Use Cpanel::SafeRun::Object instead" );
    }
    elsif ( scalar @$cmdline == 1 && $cmdline->[0] =~ tr{><*?[]`$()|;&#$\\\r\n\t }{} ) {
        eval "use Cpanel::Carp;";                                  ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        die Cpanel::Carp::safe_longmess( __PACKAGE__ . " prevents accidental execution of a shell.  If you intended to execute a shell use saferun(" . join( ',', '/bin/sh', '-c', @$cmdline ) . ")" );
    }

    my $output;

    if ( index( $cmdline->[0], '/' ) == 0 ) {
        my ($check) = !-e $cmdline->[0] && $cmdline->[0] =~ /[\s<>&\|\;]/ ? split( /[\s<>&\|\;]/, $cmdline->[0], 2 ) : $cmdline->[0];

        if ( !-x $check ) {
            $? = -1;

            return \$output;
        }

    }
    $error_flag ||= 0;
    local ($/);
    my ( $pid, $prog_fh, $did_fastspawn );

    if ( $INC{'Proc/FastSpawn.pm'} ) {    # may not be available yet due to upcp.static or updatenow.static

        my @env = map { exists $ENV{$_} && $_ ne 'IFS' && $_ ne 'CDPATH' && $_ ne 'ENV' && $_ ne 'BASH_ENV' ? ( $_ . '=' . ( $ENV{$_} // '' ) ) : () } keys %ENV;

        my ($child_write);
        pipe( $prog_fh, $child_write ) or warn "Failed to pipe(): $!";

        my $null_fh;
        if ( $error_flag == $NULL_STDERR || $error_flag == $NULL_STDOUT ) {
            open( $null_fh, '>', '/dev/null' ) or die "Failed open /dev/null: $!";
        }

        Cpanel::FHUtils::Autoflush::enable($_) for ( $prog_fh, $child_write );

        $did_fastspawn = 1;

        my $stdout_fileno = fileno($child_write);
        my $stderr_fileno = -1;

        if ( $error_flag == $MERGE_STDERR ) {
            $stderr_fileno = fileno($child_write);
        }
        elsif ( $error_flag == $NULL_STDERR ) {
            $stderr_fileno = fileno($null_fh);
        }
        elsif ( $error_flag == $NULL_STDOUT ) {
            $stdout_fileno = fileno($null_fh);
            $stderr_fileno = fileno($child_write);
        }

        $pid = Proc::FastSpawn::spawn_open3(
            -1,                # stdin
            $stdout_fileno,    # stdout
            $stderr_fileno,    # stderr
            $cmdline->[0],     # program
            $cmdline,          # args
            \@env,             #env
        );

    }
    else {
        if ( $pid = open( $prog_fh, '-|' ) ) {

        }
        elsif ( defined $pid ) {

            delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};

            $ENV{'PATH'} ||= '';
            Cpanel::SV::untaint( $ENV{'PATH'} );

            if ( $error_flag == $MERGE_STDERR ) {
                open( STDERR, '>&STDOUT' ) or die "Failed to redirect STDERR to STDOUT: $!";
            }
            elsif ( $error_flag == $NULL_STDERR ) {
                open( STDERR, '>', '/dev/null' ) or die "Failed to open /dev/null: $!";
            }
            elsif ( $error_flag == $NULL_STDOUT ) {
                open( STDERR, '>&STDOUT' ) or die "Failed to redirect STDERR to STDOUT: $!";
                open( STDOUT, '>', '/dev/null' ) or die "Failed to redirect STDOUT to /dev/null: $!";
            }
            exec(@$cmdline) or exit( $! || 127 );
        }
        else {
            die "fork() failed: $!";
        }
    }
    if ( !$prog_fh || !$pid ) {

        $? = -1;    ## no critic qw(Variables::RequireLocalizedPunctuationVars)

        return \$output;
    }
    Cpanel::LoadFile::ReadFast::read_all_fast( $prog_fh, $output );
    close($prog_fh);

    waitpid( $pid, 0 ) if $did_fastspawn;

    return \$output;
}

sub _call_saferun {
    my ( $args, $flag ) = @_;
    my $ref = _saferun_r( $args, $flag || 0 );

    return $$ref if $ref;
    return;
}

sub saferun {
    return _call_saferun( \@_, $KEEP_STDERR );
}

sub saferunallerrors {
    return _call_saferun( \@_, $MERGE_STDERR );
}

sub saferunnoerror {
    return _call_saferun( \@_, $NULL_STDERR );
}

sub saferunonlyerrors {
    return _call_saferun( \@_, $NULL_STDOUT );
}

1;

} # --- END Cpanel/SafeRun/Simple.pm


{ # --- BEGIN Cpanel/SafeRun/Errors.pm
package Cpanel::SafeRun::Errors;


use strict;

# use Cpanel::SafeRun::Simple ();


sub saferunallerrors {
    my $output_ref = Cpanel::SafeRun::Simple::_saferun_r( \@_, 1 );    #1 = errors to stdout
    return wantarray ? split( /\n/, $$output_ref ) : $$output_ref;
}

sub saferunnoerror {
    my $output_ref = Cpanel::SafeRun::Simple::_saferun_r( \@_, 2 );    # 2 = errors to devnull
    return wantarray ? split( /\n/, $$output_ref ) : $$output_ref;
}

sub saferunonlyerrors {
    my $output_ref = Cpanel::SafeRun::Simple::_saferun_r( \@_, 3 );
    return wantarray ? split( /\n/, $$output_ref ) : $$output_ref;
}

1;

} # --- END Cpanel/SafeRun/Errors.pm


{ # --- BEGIN Cpanel/Timezones.pm
package Cpanel::Timezones;


use cPstrict;

# use Cpanel::OS    ();
# use Cpanel::Debug ();
use Cwd           ();

use constant _ENOENT => 2;

our $timezones_cachefile = '/var/cpanel/timezones.cache';
my $cache_ttl = 3_600 * 24 * 7 * 6;    #6 WEEKS

our $timezones_cache;

our $timezonedir   = '/usr/share/zoneinfo';
our $zonetabfile   = '/usr/share/zoneinfo/zone.tab';
our $etc_localtime = '/etc/localtime';

sub gettimezones() {
    if ( !$timezones_cache ) {
        my $timezones;

        if ( open my $fh, '<', $timezones_cachefile ) {
            $timezones = -f $fh;
            $timezones &&= ( time - ( stat $fh )[9] ) < $cache_ttl;

            $timezones &&= [<$fh>];
            chomp @$timezones if $timezones;
        }
        elsif ( $! != _ENOENT ) {
            warn "open($timezones_cachefile): $!";
        }

        if ( !$timezones || !scalar @{$timezones} || !grep { $_ eq "UTC" } @$timezones ) {
            $timezones = [];
            get_timezones_from_zonetab($timezones);

            if ( !scalar @{$timezones} ) {
                require Cpanel::FileUtils::Lines;
                require File::Find;
                File::Find::find(
                    sub {
                        if ( Cpanel::FileUtils::Lines::has_txt_in_file( $File::Find::name, '\ATZif' ) ) {
                            ( my $stripped_name = $File::Find::name ) =~ s{\A$timezonedir/}{};
                            push @{$timezones}, $stripped_name;
                        }
                    },
                    $timezonedir
                );
            }
            push @$timezones, "UTC" unless grep { $_ eq "UTC" } @$timezones;

            if ( _running_as_root() ) {
                require Cpanel::FileUtils::Write;
                Cpanel::FileUtils::Write::overwrite_no_exceptions( $timezones_cachefile, join( "\n", @{$timezones} ), 0644 );
            }
        }

        $timezones_cache = $timezones;
    }

    return wantarray ? @$timezones_cache : $timezones_cache;
}

sub _running_as_root {
    return $> == 0 ? 1 : 0;
}

sub is_valid ($tz) {
    my $is_valid;

    require Cpanel::FileUtils::Lines;
    if ($timezones_cache) {
        $is_valid = grep { $_ eq $tz } @$timezones_cache;
    }
    elsif ( -f $timezones_cachefile && ( time() - ( stat $timezones_cachefile )[9] <= $cache_ttl ) ) {

        $is_valid = Cpanel::FileUtils::Lines::has_txt_in_file( $timezones_cachefile, qr(\A\Q$tz\E\Z) );
    }
    else {
        $is_valid = grep { $_ eq $tz } ( gettimezones() );
    }

    return $is_valid;
}

sub set ($tz) {

    return unless is_valid($tz);

    my $method = Cpanel::OS::setup_tz_method();

    if ( $method eq 'timedatectl' ) {
        _setup_clock_using_timedatectl($tz);
    }
    elsif ( $method eq 'sysconfig' ) {
        _setup_clock_using_sysconfig($tz);
    }
    else {
        Cpanel::Debug::log_die("Invalid setup_tz_method method: $method");
    }

    return;
}

sub _setup_clock_using_timedatectl ($tz) {

    require Cpanel::SafeRun::Errors;
    Cpanel::SafeRun::Errors::saferunallerrors( '/usr/bin/timedatectl', 'set-timezone', $tz );

    return;
}

sub _setup_clock_using_sysconfig ($tz) {

    my @CLOCK;

    if ( open( my $fh, '<', '/etc/sysconfig/clock' ) ) {
        @CLOCK = (<$fh>);
        close($fh);
    }
    else {
        Cpanel::Debug::log_warn(qq[Could not open file "/etc/sysconfig/clock" for reading ($!)]);
    }

    if ( open( my $fh, '>', '/etc/sysconfig/clock' ) ) {
        my $ok;
        foreach my $line (@CLOCK) {
            if ( $line =~ m{\AZONE=}i ) {
                $ok = 1;
                print {$fh} qq[ZONE="$tz"\n];
            }
            else {
                print {$fh} $line;
            }
        }
        print {$fh} qq[ZONE="$tz"\n] unless $ok;
        close($fh);

        unlink $etc_localtime;
        symlink "/usr/share/zoneinfo/$tz", $etc_localtime;

    }
    else {
        Cpanel::Debug::log_warn(qq[Could not open file "/etc/sysconfig/clock" for writing ($!)]);
    }

    return;
}

sub get_timezones_from_zonetab ($timezones_ar) {

    my $fh;
    if ( !open $fh, '<', $zonetabfile ) {
        Cpanel::Debug::log_warn("Could not open file \"$zonetabfile\" for reading ($!), will attempt to determine the time zone list by other (probably less precise) method(s)");
        return;
    }

    while (<$fh>) {
        next unless m{ ^ [A-Z]+ \s+ [-+][-+\d]+ \s+ (\S+) }ax;
        push @{$timezones_ar}, $1;
    }

    close $fh;

    return 1;
}

sub _hash_file ($file) {

    require Digest::SHA;
    return Digest::SHA->new(512)->addfile($file)->hexdigest;
}

sub get_current_timezone (%opts) {

    my $tz = 'UTC';    # default value when none found

    if ( -l $etc_localtime ) {    # check file being symlinked, if symlinked
        $tz = Cwd::abs_path($etc_localtime);
        $tz =~ s{^.*/usr/share/zoneinfo/}{};
    }
    else {
        my $localhash = _hash_file($etc_localtime);
        my @TZS       = gettimezones();
        foreach my $tzfile (@TZS) {
            my $check = $timezonedir . '/' . $tzfile;
            next unless -f $check;
            my $digest = _hash_file($check);
            if ( $localhash eq $digest ) {
                $tz = $tzfile;
                last;
            }
        }

    }

    $tz =~ s{^posix/}{} if $opts{noposix};
    return $tz;
}

sub calculate_TZ_env() {
    return get_current_timezone( noposix => 1 );
}

sub set_zonetabfile ($file) {
    $zonetabfile = $file;
    return;
}

sub clear_caches() {
    undef $timezones_cache;
    unlink $timezones_cachefile;

    return;
}

1;

} # --- END Cpanel/Timezones.pm


{ # --- BEGIN Cpanel/Locale/Utils/DateTime.pm
package Cpanel::Locale::Utils::DateTime;



use strict;
# use Cpanel::LoadModule ();
# use Cpanel::Locale     ();

our $ENCODE_MODULE          = 'Encode';
our $DATETIME_MODULE        = 'DateTime';
our $DATETIME_LOCALE_MODULE = 'DateTime::Locale';
my %known_ids = ();

sub datetime {
    my ( $lh, $epoch, $format, $timezone ) = @_;

    if ( $epoch && ref $epoch eq 'ARRAY' ) {
        $epoch = $epoch->[0];
    }
    elsif ( !$epoch ) {
        $epoch = time;
    }
    $format ||= 'date_format_long';

    my $encoding = $lh->encoding();

    if ( _can_use_cpanel_date_format( $encoding, $timezone ) ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Date::Format');
        return Cpanel::Date::Format::translate_for_locale( $epoch, $format, $lh->language_tag() );
    }

    my $locale = _get_best_locale_for_datetime_obj( $lh->language_tag() );
    return _get_formatted_datetime( $locale, $encoding, $format, $epoch, $timezone );
}

sub _can_use_cpanel_date_format {
    my ( $encoding, $timezone ) = @_;

    return ( $encoding eq 'utf-8' ) && ( !$timezone || $timezone eq 'UTC' );
}

sub get_lookup_hash_of_multi_epoch_datetime {
    my ( $lh, $epochs_ar, $format, $timezone ) = @_;

    $format ||= 'date_format_long';
    my %lookups;

    my $encoding = $lh->encoding();

    my $can_use_cpanel_date_format = _can_use_cpanel_date_format( $encoding, $timezone );
    my $locale;

    if ($can_use_cpanel_date_format) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Date::Format');
        $locale = $lh->language_tag();
    }
    else {
        $locale = _get_best_locale_for_datetime_obj( $lh->language_tag() );
    }

    foreach my $epoch ( @{$epochs_ar} ) {
        $lookups{$epoch} ||= do {
            if ($can_use_cpanel_date_format) {
                Cpanel::Date::Format::translate_for_locale( $epoch, $format, $locale );
            }
            else {
                _get_formatted_datetime( $locale, $encoding, $format, $epoch, $timezone );
            }
        };
    }
    return \%lookups;
}

sub _get_formatted_datetime {
    my ( $locale, $encoding, $format, $epoch, $timezone ) = @_;

    if ( !$timezone ) {
        $timezone = 'UTC';
    }
    elsif ( $timezone !~ m{^[\.0-9A-Za-z\/_\+\-]+$} ) {
        die "Invalid timezone “$timezone”";
    }

    my $datetime_obj = $DATETIME_MODULE->from_epoch( 'epoch' => $epoch, 'locale' => $locale, 'time_zone' => $timezone );

    if ( $format && $format !~ m{_format$} && $datetime_obj->{'locale'}->can($format) ) {
        return $ENCODE_MODULE->can('encode')->( $encoding, $datetime_obj->format_cldr( $datetime_obj->{'locale'}->$format ) );
    }

    die 'Invalid datetime format: ' . $format;
}

sub _get_best_locale_for_datetime_obj {
    my ($language_tag) = @_;
    my ( $fallback, $locale ) = _get_fallback_locale($language_tag);

    Cpanel::LoadModule::load_perl_module($ENCODE_MODULE) if !$INC{'Encode.pm'};
    Cpanel::LoadModule::load_perl_module($DATETIME_MODULE);

    foreach my $try_locale ( $locale, $fallback, 'en_US', 'en' ) {
        next               if !$try_locale;
        return $try_locale if $known_ids{$try_locale} || $Cpanel::Locale::known_locales_character_orientation{$try_locale};
        if ( eval { $DATETIME_MODULE->load($try_locale) } ) {
            $known_ids{$try_locale} = 1;
            return $try_locale;
        }
    }

    die "Could not locale any working DateTime locale";
}

sub _get_fallback_locale {
    my ($locale) = @_;
    my $fallback;
    if ( substr( $locale, 0, 2 ) eq 'i_' ) {
        require Cpanel::Locale::Utils::Paths;
        my $dir = Cpanel::Locale::Utils::Paths::get_i_locales_config_path();
        if ( -e "$dir/$locale.yaml" ) {
            require Cpanel::DataStore;
            my $hr = Cpanel::DataStore::fetch_ref("$dir/$locale.yaml");
            if ( exists $hr->{'fallback_locale'} && $hr->{'fallback_locale'} ) {
                $fallback = $hr->{'fallback_locale'};
            }
        }
    }
    else {
        my ( $pre, $pst ) = split( /[\_\-]/, $locale, 2 );
        if ($pst) {
            $fallback = $pre;
            $locale   = $pre . '_' . uc($pst);
        }
    }
    $fallback ||= 'en';

    return ( $fallback, $locale );
}

1;

} # --- END Cpanel/Locale/Utils/DateTime.pm


{ # --- BEGIN Cpanel/Time/ISO.pm
package Cpanel::Time::ISO;


use strict;
use warnings;

# use Cpanel::Debug      ();
# use Cpanel::LoadModule ();


sub unix2iso {
    Cpanel::LoadModule::load_perl_module('Cpanel::Time') unless $INC{'Cpanel/Time.pm'};
    return sprintf( '%04d-%02d-%02dT%02d:%02d:%02dZ', reverse( ( Cpanel::Time::gmtime( $_[0] || time() ) )[ 0 .. 5 ] ) );
}


sub iso2unix {
    my ($iso_time) = @_;

    if ( rindex( $iso_time, 'Z' ) != length($iso_time) - 1 ) {
        die "Only UTC times, not “$iso_time”!";
    }

    my @smhdmy = reverse split m<[^0-9.]>, $iso_time;
    Cpanel::LoadModule::load_perl_module('Cpanel::Time') unless $INC{'Cpanel/Time.pm'};

    return Cpanel::Time::timegm(@smhdmy);
}


sub unix2iso_date {
    Cpanel::LoadModule::load_perl_module('Cpanel::Time') unless $INC{'Cpanel/Time.pm'};
    Cpanel::Debug::log_deprecated('This function will be removed, please use locale datetime');

    return sprintf( '%04d-%02d-%02d', reverse( ( Cpanel::Time::gmtime( $_[0] || time() ) )[ 3 .. 5 ] ) );
}


sub unix2iso_time {
    Cpanel::LoadModule::load_perl_module('Cpanel::Time') unless $INC{'Cpanel/Time.pm'};
    Cpanel::Debug::log_deprecated('This function will be removed, please use locale datetime');
    return sprintf( '%02d:%02d:%02d', reverse( ( Cpanel::Time::gmtime( $_[0] || time() ) )[ 0 .. 2 ] ) );
}

1;

} # --- END Cpanel/Time/ISO.pm


{ # --- BEGIN Cpanel/Config/LoadUserDomains/Count.pm
package Cpanel::Config::LoadUserDomains::Count;


use strict;
use warnings;

# use Cpanel::Autodie            qw(exists);
INIT { Cpanel::Autodie->import(qw{exists}); }
# use Cpanel::LoadFile::ReadFast ();
# use Cpanel::ConfigFiles        ();



sub counttrueuserdomains {
    if ( !Cpanel::Autodie::exists( _trueuserdomains() ) ) {
        return 0;
    }
    return _count_file_lines( _trueuserdomains() );
}


sub countuserdomains {
    if ( !Cpanel::Autodie::exists( _userdomains() ) ) {
        return 0;
    }
    return _count_file_lines( _userdomains() ) - 1;    # -1 for *: nobody
}

sub _count_file_lines {
    my ($file) = @_;
    open( my $ud_fh, '<', $file ) or die "open($file): $!";

    my $buffer = '';
    Cpanel::LoadFile::ReadFast::read_all_fast( $ud_fh, $buffer );
    my $num_ud = ( $buffer =~ tr/\n// );
    close($ud_fh) or warn "close($file): $!";

    $num_ud++ if length($buffer) && substr( $buffer, -1 ) ne "\n";

    return $num_ud;
}

sub _userdomains {
    return $Cpanel::ConfigFiles::USERDOMAINS_FILE;
}

sub _domainusers {
    return $Cpanel::ConfigFiles::DOMAINUSERS_FILE;
}

sub _trueuserdomains {
    return $Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE;
}

1;

} # --- END Cpanel/Config/LoadUserDomains/Count.pm


{ # --- BEGIN Cpanel/Server/Type.pm
package Cpanel::Server::Type;


use cPstrict;

use constant NUMBER_OF_USERS_TO_ASSUME_IF_UNREADABLE => 1;


sub _get_license_file_path { return q{/usr/local/cpanel/cpanel.lisc} }
sub _get_dnsonly_file_path { return q{/var/cpanel/dnsonly} }

use constant _ENOENT => 2;

my @server_config;
our %PRODUCTS;
our $MAXUSERS;
our %FIELDS;
our ( $DNSONLY_MODE, $NODE_MODE );


sub is_dnsonly {
    return $DNSONLY_MODE if defined $DNSONLY_MODE;

    return 1 if -e _get_dnsonly_file_path();
    return 0 if $! == _ENOENT();
    my $err = $!;


    if ( _read_license() ) {
        return $PRODUCTS{'dnsonly'} ? 1 : 0;
    }

    die sprintf( 'stat(%s): %s', _get_dnsonly_file_path(), "$err" );
}


sub get_producttype {
    return $NODE_MODE if defined $NODE_MODE;
    return 'DNSONLY' unless _read_license();

    return 'STANDARD' if $PRODUCTS{'cpanel'};

    foreach my $product (qw/dnsnode mailnode databasenode dnsonly/) {
        return uc($product) if $PRODUCTS{$product};
    }

    return 'DNSONLY';
}


sub get_max_users {
    return $MAXUSERS if defined $MAXUSERS;
    return NUMBER_OF_USERS_TO_ASSUME_IF_UNREADABLE unless _read_license();
    return $MAXUSERS // NUMBER_OF_USERS_TO_ASSUME_IF_UNREADABLE;
}


sub has_els {
    return $FIELDS{els} if defined $FIELDS{els};
    return 0 unless _read_license();
    return $FIELDS{els} // 0;
}


sub get_license_expire_gmt_date {
    return $FIELDS{'license_expire_gmt_date'} if defined $FIELDS{'license_expire_gmt_date'};
    return 0 unless _read_license();
    return $FIELDS{'license_expire_gmt_date'} // 0;
}


sub is_licensed_for_product ($product) {
    return unless $product;
    $product = lc $product;
    return unless _read_license();
    return exists $PRODUCTS{$product};
}


sub get_features {
    return unless _read_license();

    my @features = split( ",", $FIELDS{'features'} // '' );
    return @features;
}


sub has_feature ( $feature = undef ) {
    length $feature or return;

    return ( grep { $_ eq $feature } get_features() ) ? 1 : 0;
}


sub get_products {
    return unless _read_license();
    return keys %PRODUCTS;
}

sub _read_license {
    my $LICENSE_FILE = _get_license_file_path();

    my @new_stat = stat($LICENSE_FILE) if @server_config;

    if ( @server_config && @new_stat && $new_stat[9] == $server_config[9] && $new_stat[7] == $server_config[7] ) {
        return 1;
    }

    open( my $fh, '<', $LICENSE_FILE ) or do {

        if ( $! != _ENOENT() ) {
            warn "open($LICENSE_FILE): $!";
        }

        return;
    };

    _reset_cache();

    my $content;

    read( $fh, $content, 1024 ) // do {
        warn "read($LICENSE_FILE): $!";
        $content = q<>;
    };

    return _parse_license_contents_sr( $fh, \$content );
}

sub _parse_license_contents_to_hashref ($content_sr) {

    my %vals = map { ( split( m{: }, $_ ) )[ 0, 1 ] } split( m{\n}, $$content_sr );

    return \%vals;
}

sub _parse_license_contents_sr ( $fh, $content_sr ) {
    my $vals_hr = _parse_license_contents_to_hashref($content_sr);

    if ( length $vals_hr->{'products'} ) {
        %PRODUCTS = map { ( $_ => 1 ) } split( ",", $vals_hr->{'products'} );
    }
    else {
        return;
    }

    if ( length $vals_hr->{'maxusers'} ) {

        $MAXUSERS //= int $vals_hr->{'maxusers'};
    }
    else {
        return;
    }

    foreach my $field (qw/license_expire_time license_expire_gmt_date support_expire_time updates_expire_time/) {
        $FIELDS{$field} = $vals_hr->{$field} // 0;
    }
    foreach my $field (qw/client features/) {
        $FIELDS{$field} = $vals_hr->{$field} // '';
    }

    if ( length $vals_hr->{'fields'} ) {
        foreach my $field ( split( ",", $vals_hr->{'fields'} ) ) {
            my ( $k, $v ) = split( '=', $field, 2 );
            $FIELDS{$k} = $v;

        }
    }
    else {
        return;
    }

    @server_config = stat($fh);
    return 1;
}

sub _reset_cache {
    undef %PRODUCTS;
    undef %FIELDS;
    undef @server_config;
    undef $MAXUSERS;
    undef $DNSONLY_MODE;

    return;
}

1;


} # --- END Cpanel/Server/Type.pm


{ # --- BEGIN Cpanel/Config/LoadUserDomains.pm
package Cpanel::Config::LoadUserDomains;


use strict;
use warnings;

# use Cpanel::Config::LoadConfig             ();
# use Cpanel::Config::LoadUserDomains::Count ();
# use Cpanel::Server::Type                   ();


sub loaduserdomains {
    my ( $conf_ref, $reverse, $usearr ) = @_;
    $conf_ref = Cpanel::Config::LoadConfig::loadConfig(
        Cpanel::Config::LoadUserDomains::Count::_userdomains(),
        $conf_ref,
        ': ',     # We write the file so there is no need to match stray spaces
        '0E0',    # Avoid looking for comments since there will not be any
        0,        # reverse
        1,        # allow_undef_values since there will not be any
        {
            'use_reverse'          => $reverse ? 0 : 1,
            'skip_keys'            => ['nobody'],
            'use_hash_of_arr_refs' => ( $usearr || 0 ),
        }
    );
    if ( !defined($conf_ref) ) {
        $conf_ref = {};
    }
    return wantarray ? %{$conf_ref} : $conf_ref;
}


sub loadtrueuserdomains {
    my ( $conf_ref, $reverse, $ignore_limit ) = @_;
    $conf_ref = Cpanel::Config::LoadConfig::loadConfig(
        ( $reverse ? Cpanel::Config::LoadUserDomains::Count::_domainusers() : Cpanel::Config::LoadUserDomains::Count::_trueuserdomains() ),
        $conf_ref,
        ': ',     # We write the file so there is no need to match stray spaces
        '0E0',    # Avoid looking for comments since there will not be any
        0,        # reverse
        1,        # allow_undef_values since there will not be any
        { 'limit' => ( $ignore_limit ? 0 : Cpanel::Server::Type::get_max_users() ) }
    );
    if ( !defined($conf_ref) ) {
        $conf_ref = {};
    }
    return wantarray ? %{$conf_ref} : $conf_ref;
}

*counttrueuserdomains = *counttrueuserdomains = *Cpanel::Config::LoadUserDomains::Count::counttrueuserdomains;

1;

} # --- END Cpanel/Config/LoadUserDomains.pm


{ # --- BEGIN Cpanel/Config/CpUser.pm
package Cpanel::Config::CpUser;


use strict;

# use Cpanel::Debug                        ();
# use Cpanel::LoadModule                   ();
# use Cpanel::Config::LoadUserDomains      ();
# use Cpanel::Config::LoadCpUserFile       ();
# use Cpanel::ConfigFiles                  ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();

our $cpuser_dir;
*cpuser_dir = \$Cpanel::ConfigFiles::cpanel_users;
our $cpuser_cache_dir = "$cpuser_dir.cache";

our $header = <<END;
END

my %memory_file_list_key = qw(
  DOMAINS         DNS
  DEADDOMAINS     XDNS
  HOMEDIRLINKS    HOMEDIRPATHS
);

sub clean_cpuser_hash {
    my ( $cpuser_ref, $user ) = @_;

    {
        my @missing = grep { !exists $cpuser_ref->{$_} } required_cpuser_keys();
        if (@missing) {
            $user = q{} if !defined $user;
            Cpanel::Debug::log_warn( "The following keys are missing from supplied '$user' cPanel user data: " . join( ', ', @missing ) . ", to prevent data loss, the data was not saved." );
            return;
        }
    }

    if ( grep { $_ && index( $_, "\n" ) != -1 } %$cpuser_ref ) {

        Cpanel::Debug::log_warn("The cpuser data contains newlines.  This is not allowed as it would corrupt the file.");
        return;
    }

    my $domain = $cpuser_ref->{'DOMAIN'};
    if ( !$domain ) {    # Try to lookup main domain in /etc/trueuserdomains
        my $trueuserdomains_ref = Cpanel::Config::LoadUserDomains::loadtrueuserdomains( undef, 1 );
        $domain = $trueuserdomains_ref->{$user} || '';
        if ( !$domain ) {
            Cpanel::Debug::log_info("Unable to determine user ${user}'s main domain");
        }
    }

    my %clean_data = (
        %$cpuser_ref,
        DNS => $domain,
    );

    delete @clean_data{
        q{},
        'DOMAIN',
        'DBOWNER',
        '__CACHE_DATA_VERSION',
        ( keys %memory_file_list_key ),
    };

    if ( defined $clean_data{'DISK_BLOCK_LIMIT'} && $clean_data{'DISK_BLOCK_LIMIT'} eq 'unlimited' ) {
        $clean_data{'DISK_BLOCK_LIMIT'} = 0;
    }

    while ( my ( $memkey, $filekey ) = each %memory_file_list_key ) {
        if ( exists $cpuser_ref->{$memkey} && scalar @{ $cpuser_ref->{$memkey} } ) {
            my $doms_ar = $cpuser_ref->{$memkey};
            my $count   = 0;
            @clean_data{ ( map { $filekey . ++$count } @$doms_ar ) } = @$doms_ar;
        }
    }

    my $homedirs_key_in_file = $memory_file_list_key{'HOMEDIRLINKS'};
    if ( exists $clean_data{ $homedirs_key_in_file . 1 } ) {
        $clean_data{$homedirs_key_in_file} = delete $clean_data{ $homedirs_key_in_file . 1 };
    }

    return wantarray ? %clean_data : \%clean_data;
}

sub get_cpgid {
    my ($user) = @_;

    my $cpgid = 0;

    if ( exists $INC{'Cpanel/PwCache.pm'} || Cpanel::LoadModule::load_perl_module('Cpanel::PwCache') ) {
        $cpgid = ( Cpanel::PwCache::getpwnam_noshadow($user) )[3];
    }

    return $cpgid;
}

sub recache {
    my ( $cpuser_ref, $user, $cpgid ) = @_;

    my $user_cache_file = $cpuser_cache_dir . '/' . $user;

    Cpanel::Config::LoadCpUserFile::create_users_cache_dir();
    $cpuser_ref->{'__CACHE_DATA_VERSION'} = $Cpanel::Config::LoadCpUserFile::VERSION;    # set this before the cache is written so that it will be included in the cache

    if ( Cpanel::FileUtils::Write::JSON::Lazy::write_file( $user_cache_file, $cpuser_ref, 0640 ) ) {
        chown 0, $cpgid, $user_cache_file if $cpgid;                                     # this is ok if the chown happens after as we fall though to reading the non-cache on a failed open
    }
    else {
        unlink $user_cache_file;                                                         #outdated
    }
}

sub required_cpuser_keys {
    my @keys = qw( FEATURELIST HASCGI MAXSUB MAXADDON DEMO RS USER MAXFTP MAXLST MAXPARK STARTDATE BWLIMIT IP MAXSQL DOMAIN MAXPOP PLAN OWNER );

    return wantarray ? @keys : \@keys;
}

1;

} # --- END Cpanel/Config/CpUser.pm


{ # --- BEGIN Cpanel/Config/FlushConfig.pm
package Cpanel::Config::FlushConfig;



use strict;
use warnings;

# use Cpanel::FileUtils::Write ();
# use Cpanel::Debug            ();
# use Cpanel::Exception        ();

our $VERSION = '1.4';

my $DEFAULT_DELIMITER = '=';


sub flushConfig {
    my ( $filename_or_fh, $conf, $delimiter, $header, $opts ) = @_;

    if ( !$filename_or_fh ) {
        Cpanel::Debug::log_warn('flushConfig requires valid filename or fh as first argument');
        return;
    }
    elsif ( !$conf || ref $conf ne 'HASH' ) {
        Cpanel::Debug::log_warn('flushConfig requires HASH reference as second argument');
        return;
    }

    if ( ref $opts && $opts->{'no_overwrite'} ) {
        die Cpanel::Exception::create( 'Unsupported', 'Function ”flushConfig” called with an unsupported option “no_overwrite”.' );
    }

    my $contents_sr = serialize(
        $conf,
        do_sort            => $opts && $opts->{'sort'},
        delimiter          => $delimiter,
        header             => $header,
        allow_array_values => $opts && $opts->{'allow_array_values'},
    );

    my $perms = 0644;    # default permissions when unset
    if ( defined $opts->{'perms'} ) {
        $perms = $opts->{'perms'};
    }
    elsif ( !ref $filename_or_fh && -e $filename_or_fh ) {
        $perms = ( stat(_) )[2] & 0777;
    }

    if ( ref $filename_or_fh ) {
        return Cpanel::FileUtils::Write::write_fh(
            $filename_or_fh,
            ref $contents_sr eq 'SCALAR' ? $$contents_sr : $contents_sr
        );
    }

    return Cpanel::FileUtils::Write::overwrite_no_exceptions(
        $filename_or_fh,
        ref $contents_sr eq 'SCALAR' ? $$contents_sr : $contents_sr,
        $perms,
    );
}


sub serialize {
    my ( $conf, %opts ) = @_;

    my ( $do_sort, $delimiter, $header, $allow_array_values ) = @opts{qw(do_sort delimiter header allow_array_values)};

    $delimiter ||= $DEFAULT_DELIMITER;


    if ($allow_array_values) {
        my $contents = '';
        $contents .= $header . "\n" if $header;

        foreach my $key ( $do_sort ? ( sort keys %{$conf} ) : ( keys %{$conf} ) ) {
            if ( ref( $conf->{$key} ) eq 'ARRAY' ) {
                $contents .= join(
                    "\n",
                    map { $key . $delimiter . $_ } ( @{ $conf->{$key} } )
                ) . "\n";
            }
            else {
                $contents .= $key . $delimiter . ( defined $conf->{$key} ? $conf->{$key} : '' ) . "\n";
            }
        }

        return \$contents;
    }

    my $contents = ( $header ? ( $header . "\n" ) : '' ) . join(
        "\n",
        map { $_ . ( defined $conf->{$_} ? ( $delimiter . $conf->{$_} ) : '' ) } ( $do_sort ? ( sort keys %{$conf} ) : ( keys %{$conf} ) )
    ) . "\n";

    return \$contents;
}

1;

} # --- END Cpanel/Config/FlushConfig.pm


{ # --- BEGIN Cpanel/Config/CpUser/Write.pm
package Cpanel::Config::CpUser::Write;


use cPstrict;



# use Cpanel::Config::CpUser      ();
# use Cpanel::Config::FlushConfig ();



sub serialize ($cpuser_data) {
    die 'Pass data through clean_cpuser_hash() first!' if grep { ref } values %$cpuser_data;

    return ${
        Cpanel::Config::FlushConfig::serialize(
            $cpuser_data,
            do_sort   => 1,
            delimiter => '=',
            'header'  => $Cpanel::Config::CpUser::header,
        )
    };
}

1;

} # --- END Cpanel/Config/CpUser/Write.pm


{ # --- BEGIN Cpanel/LinkedNode/Worker/Storage.pm
package Cpanel::LinkedNode::Worker::Storage;


use strict;
use warnings;




sub read {
    my ( $cpuser_hr, $worker_type ) = @_;

    my $str = $cpuser_hr->{ _get_key($worker_type) };

    return _parse($str);
}



sub set {
    my ( $cpuser_hr, $worker_type, $alias, $token ) = @_;

    $cpuser_hr->{ _get_key($worker_type) } = "$alias:$token";

    return;
}



sub unset {
    my ( $cpuser_hr, $worker_type ) = @_;

    return _parse( delete $cpuser_hr->{ _get_key($worker_type) } );
}


sub _get_key {
    my ($worker_type) = @_;

    substr( $worker_type, 0, 1 ) =~ tr<A-Z><> or do {
        die "Worker type names always begin with a capital! (given: “$worker_type”)";
    };

    return "WORKER_NODE-$worker_type";
}

sub _parse {
    my ($str) = @_;

    return $str ? [ split m<:>, $str, 2 ] : undef;
}

1;

} # --- END Cpanel/LinkedNode/Worker/Storage.pm


{ # --- BEGIN Cpanel/SafeFile/Replace.pm
package Cpanel::SafeFile::Replace;


use strict;
use warnings;

# use Cpanel::Fcntl::Constants ();
# use Cpanel::FileUtils::Open  ();
use File::Basename           ();

use constant {
    WRONLY_CREAT_EXCL => $Cpanel::Fcntl::Constants::O_WRONLY | $Cpanel::Fcntl::Constants::O_CREAT | $Cpanel::Fcntl::Constants::O_EXCL,
    _EEXIST           => 17
};

sub safe_replace_content {
    my ( $fh, $safelock, @content ) = @_;

    return locked_atomic_replace_contents(
        $fh,
        $safelock,
        sub {
            local $!;

            @content = @{ $content[0] } if scalar @content == 1 && ref $content[0] eq 'ARRAY';

            print { $_[0] } @content;

            if ($!) {
                my $length = 0;
                $length += length for @content;

                my $err = $!;
                require Cpanel::Exception;
                die Cpanel::Exception::create( 'IO::WriteError', [ length => $length, error => $err ] );
            }

            return 1;
        }
    );
}

my $_lock_ex_nb;

sub locked_atomic_replace_contents {
    my ( $fh, $safelock, $coderef ) = @_;

    $_lock_ex_nb //= $Cpanel::Fcntl::Constants::LOCK_EX | $Cpanel::Fcntl::Constants::LOCK_NB;
    if ( !flock $fh, $_lock_ex_nb ) {
        my $err = $!;
        require Cpanel::Exception;
        die Cpanel::Exception::create_raw( 'IOError', "locked_atomic_replace_contents could not lock the file handle because of an error: $err" );
    }

    if ( !ref $safelock ) {
        local $@;
        if ( !eval { $safelock->isa('Cpanel::SafeFileLock') } ) {
            die "locked_atomic_replace_contents requires a Cpanel::SafeFileLock object";
        }
    }

    my $locked_path = $safelock->get_path_to_file_being_locked();
    die "locked_path must be valid" if !length $locked_path;
    my ( $temp_file, $temp_fh, $created_temp_file, $attempts );
    my $current_perms = ( stat($fh) )[2] & 07777;

    while ( !$created_temp_file && ++$attempts < 100 ) {
        $temp_file = sprintf(
            '%s-%x-%x-%x',
            $locked_path,
            substr( rand, 2 ),
            scalar( reverse time ),
            scalar( reverse $$ ),
        );

        my ( $basename, $dirname );
        $basename = File::Basename::basename($temp_file);
        if ( length $basename >= 255 ) {
            $basename  = substr( $basename, 255 );
            $dirname   = File::Basename::dirname($temp_file);
            $temp_file = "$dirname/$basename";
        }

        $created_temp_file = Cpanel::FileUtils::Open::sysopen_with_real_perms( $temp_fh, $temp_file, WRONLY_CREAT_EXCL, $current_perms ) or do {
            last if $! != _EEXIST;
        };
    }
    if ( !$created_temp_file ) {
        my $lasterr = $!;
        die Cpanel::Exception::create( 'TempFileCreateError', [ path => $temp_file, error => $lasterr ] );
    }

    if ( !flock $temp_fh, $Cpanel::Fcntl::Constants::LOCK_EX ) {
        my $err = $!;
        require Cpanel::Exception;
        die Cpanel::Exception::create( 'IO::FlockError', [ path => $temp_file, error => $err, operation => $Cpanel::Fcntl::Constants::LOCK_EX ] );
    }

    select( ( select($temp_fh), $| = 1 )[0] );    ##no critic qw(ProhibitOneArgSelect Variables::RequireLocalizedPunctuationVars)  #aka $fd->autoflush(1);
    if ( $coderef->( $temp_fh, $temp_file, $current_perms ) ) {
        rename( $temp_file, $locked_path );
        return $temp_fh;
    }
    local $!;
    close $temp_fh;
    unlink $temp_file;
    die "locked_atomic_replace_contents coderef returns false";
}

1;

} # --- END Cpanel/SafeFile/Replace.pm


{ # --- BEGIN Cpanel/Config/CpUserGuard.pm
package Cpanel::Config::CpUserGuard;


use strict;
use warnings;



# use Cpanel::Destruct               ();
# use Cpanel::Config::CpUser         ();
# use Cpanel::Config::CpUser::Write  ();
# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::Debug                  ();



sub new {
    my ( $class, $user ) = @_;

    my ( $data, $file, $lock, $is_locked ) = ( undef, undef, undef, 0 );

    my $cpuser = Cpanel::Config::LoadCpUserFile::_load_locked($user);
    if ( $cpuser && ref $cpuser eq 'HASH' ) {
        $data      = $cpuser->{'data'};
        $file      = $cpuser->{'file'};
        $lock      = $cpuser->{'lock'};
        $is_locked = defined $lock;
    }
    else {
        Cpanel::Debug::log_warn("Failed to load user file for '$user': $!");
        return;
    }

    my $path = "$Cpanel::Config::CpUser::cpuser_dir/$user";

    return bless {
        user      => $user,
        data      => $data,
        path      => $path,
        _file     => $file,
        _lock     => $lock,
        _pid      => $$,
        is_locked => $is_locked,
    };
}


sub set_worker_node {
    my ( $self, $worker_type, $worker_alias, $token ) = @_;

    require Cpanel::LinkedNode::Worker::Storage;
    Cpanel::LinkedNode::Worker::Storage::set( $self->{'data'}, $worker_type, $worker_alias, $token );

    return $self;
}


sub unset_worker_node {
    my ( $self, $worker_type ) = @_;

    require Cpanel::LinkedNode::Worker::Storage;
    return Cpanel::LinkedNode::Worker::Storage::unset( $self->{'data'}, $worker_type );
}

sub save {
    my ($self) = @_;

    my $user = $self->{'user'};
    my $data = $self->{'data'};

    if ( $self->{'_pid'} != $$ ) {
        Cpanel::Debug::log_die('Locked in parent, cannot save');
        return;
    }

    if ( !UNIVERSAL::isa( $data, 'HASH' ) ) {
        Cpanel::Debug::log_die( __PACKAGE__ . ': hash reference required' );
        return;
    }

    my $clean_data = Cpanel::Config::CpUser::clean_cpuser_hash( $self->{'data'}, $user );
    if ( !$clean_data ) {
        Cpanel::Debug::log_warn("Data for user '$user' was not saved.");
        return;
    }

    if ( !$self->{'_file'} || !$self->{'_lock'} ) {
        Cpanel::Debug::log_warn("Unable to save user file for '$user': file not open and locked for writing");
        return;
    }

    require Cpanel::SafeFile::Replace;

    require Cpanel::Autodie;

    my $newfh = Cpanel::SafeFile::Replace::locked_atomic_replace_contents(
        $self->{'_file'}, $self->{'_lock'},

        sub {
            my ($fh) = @_;

            chmod( 0640, $fh ) or do {
                warn sprintf( "Failed to set permissions on “%s” to 0%o: %s", $self->{'path'}, 0640, $! );
            };

            return Cpanel::Autodie::syswrite_sigguard(
                $fh,
                Cpanel::Config::CpUser::Write::serialize($clean_data),
            );
        }

      )
      or do {
        Cpanel::Debug::log_warn("Failed to save user file for “$user”: $!");
      };

    $self->{'_file'} = $newfh;

    my $cpgid = Cpanel::Config::CpUser::get_cpgid($user);

    if ($cpgid) {
        chown 0, $cpgid, $self->{'path'} or do {
            Cpanel::Debug::log_warn("Failed to chown( 0, $cpgid, $self->{'path'}): $!");
        };
    }

    if ( $INC{'Cpanel/Locale/Utils/User.pm'} ) {
        Cpanel::Locale::Utils::User::clear_user_cache($user);
    }

    Cpanel::Config::CpUser::recache( $data, $user, $cpgid );

    require Cpanel::SafeFile;
    Cpanel::SafeFile::safeclose( $self->{'_file'}, $self->{'_lock'} ) or do {
        Cpanel::Debug::log_warn("Failed to safeclose $self->{'path'}: $!");
    };

    $self->{'_file'}     = $self->{'_lock'} = undef;
    $self->{'is_locked'} = 0;

    return 1;
}

sub abort {
    my ($self) = @_;

    my $user = $self->{'user'};
    my $data = $self->{'data'};

    if ( $self->{'_pid'} != $$ ) {
        Cpanel::Debug::log_die('Locked in parent, cannot save');
        return;
    }

    require Cpanel::SafeFile;
    Cpanel::SafeFile::safeclose( $self->{'_file'}, $self->{'_lock'} );
    $self->{'_file'}     = $self->{'_lock'} = undef;
    $self->{'is_locked'} = 0;

    return 1;
}

sub DESTROY {
    my ($self) = @_;

    return unless $self->{'is_locked'};
    return if Cpanel::Destruct::in_dangerous_global_destruction();
    return unless $self->{'_pid'} == $$;

    Cpanel::SafeFile::safeclose( $self->{'_file'}, $self->{'_lock'} );

    $self->{'is_locked'} = 0;
    return;
}

1;

} # --- END Cpanel/Config/CpUserGuard.pm


{ # --- BEGIN Cpanel/Locale/Utils/User/Modify.pm
package Cpanel::Locale::Utils::User::Modify;



use strict;
use warnings;

# use Cpanel::PwCache ();

sub save_user_locale {
    my ( $locale, undef, $user ) = @_;
    $locale ||= 'en';
    $user   ||= $Cpanel::user || $ENV{'REMOTE_USER'} || ( $> == 0 ? 'root' : ( Cpanel::PwCache::getpwuid_noshadow($>) )[0] );

    if ( $user eq 'root' ) {
        require Cpanel::LoadModule;

        Cpanel::LoadModule::load_perl_module('Cpanel::DataStore');

        my $root_conf_yaml = Cpanel::PwCache::gethomedir('root') . '/.cpanel_config';
        my $hr             = Cpanel::DataStore::fetch_ref($root_conf_yaml);

        return 2 if exists $hr->{'locale'} && $hr->{'locale'} eq $locale;

        $hr->{'locale'} = $locale;

        return 1 if Cpanel::DataStore::store_ref( $root_conf_yaml, $hr );
        return;
    }
    elsif ( $> == 0 ) {
        require Cpanel::Config::CpUserGuard;
        my $cpuser_guard = Cpanel::Config::CpUserGuard->new($user) or return;
        $cpuser_guard->{'data'}->{'LOCALE'} = $locale;
        delete $cpuser_guard->{'data'}->{'LANG'};
        delete $cpuser_guard->{'data'}{'__LOCALE_MISSING'};
        return $cpuser_guard->save();
    }
    else {
        require Cpanel::LoadModule;

        Cpanel::LoadModule::load_perl_module('Cpanel::AdminBin');
        return Cpanel::AdminBin::run_adminbin_with_status( 'lang', 'SAVEUSERSETTINGS', $locale, 0, $user )->{'status'};
    }
    return 1;
}

1;

} # --- END Cpanel/Locale/Utils/User/Modify.pm


{ # --- BEGIN Cpanel/Version/Tiny.pm
package Cpanel::Version::Tiny;


use strict;

our $VERSION         = '11.110.0';
our $VERSION_BUILD   = '11.110.0.48';
our $VERSION_TEXT    = '110.0 (build 48)';
our $VERSION_DISPLAY = '110.0.48';

our $parent_version = 11;
our $major_version  = 110;
our $minor_version  = 0;
our $build_number   = 48;

our $build_time_text = 'Mon Nov  4 11:53:39 2024';
our $buildtime       = 1730742819;

1;

} # --- END Cpanel/Version/Tiny.pm


{ # --- BEGIN Cpanel/Version/Full.pm
package Cpanel::Version::Full;


use strict;


my $full_version;

our $VERSION_FILE = '/usr/local/cpanel/version';


sub getversion {
    if ( !$full_version ) {

        if ( open my $ver_fh, '<', $VERSION_FILE ) {
            if ( read $ver_fh, $full_version, 32 ) {
                chomp($full_version);
            }
            elsif ($!) {
                warn "read($VERSION_FILE): $!";
            }
        }
        else {
            warn "open($VERSION_FILE): $!";
        }

        if ( !$full_version || $full_version =~ tr{.}{} < 3 ) {
            require Cpanel::Version::Tiny;
            $full_version = $Cpanel::Version::Tiny::VERSION_BUILD;
        }
    }

    return $full_version;
}

sub _clear_cache {
    undef $full_version;
    return;
}

1;

} # --- END Cpanel/Version/Full.pm


{ # --- BEGIN Cpanel/Version/Compare.pm
package Cpanel::Version::Compare;


use cPstrict;



my %modes = (
    '>' => sub ( $check, $against ) {
        return if $check eq $against;    # no need to continue if they are the same

        return ( cmp_versions( $check, $against ) > 0 );
    },
    '<' => sub ( $check, $against ) {
        return if $check eq $against;    # no need to continue if they are the same

        return ( cmp_versions( $check, $against ) < 0 );
    },
    '==' => sub ( $check, $against ) {
        return ( $check eq $against || cmp_versions( $check, $against ) == 0 );
    },
    '!=' => sub ( $check, $against ) {
        return ( $check ne $against && cmp_versions( $check, $against ) != 0 );
    },
    '>=' => sub ( $check, $against ) {
        return 1 if $check eq $against;    # no need to continue if they are the same
        return ( cmp_versions( $check, $against ) >= 0 );
    },
    '<=' => sub ( $check, $against ) {
        return 1 if $check eq $against;    # no need to continue if they are the same
        return ( cmp_versions( $check, $against ) <= 0 );
    },
    '<=>' => sub ( $check, $against ) {
        return cmp_versions( $check, $against );
    },
);

sub compare ( $check, $mode, $against ) {

    if ( !defined $mode || !exists $modes{$mode} ) {

        return;
    }
    foreach my $ver ( $check, $against ) {

        $ver //= '';
        if ( $ver !~ m{ ^((?:\d+[._]){0,}\d+[a-z]?).*?$ }axms ) {

            return;
        }

        $ver = $1;
    }

    $check   =~ s/_/\./g;
    $against =~ s/_/\./g;

    $check   =~ s/([a-z])$/'.' . ord($1)/e;
    $against =~ s/([a-z])$/'.' . ord($1)/e;

    my @check_len   = split( /[_\.]/, $check );
    my @against_len = split( /[_\.]/, $against );

    if ( @check_len > 4 ) {

        return;
    }
    elsif ( @check_len < 4 ) {
        for ( 1 .. 4 - @check_len ) {
            $check .= '.0';
        }
    }

    if ( @against_len > 4 ) {

        return;
    }
    elsif ( @against_len < 4 ) {
        for ( 1 .. 4 - @against_len ) {
            $against .= '.0';
        }
    }

    return if $check   !~ m { \A \d+\.\d+\.\d+\.\d+ \z }axms;
    return if $against !~ m { \A \d+\.\d+\.\d+\.\d+ \z }axms;

    return $modes{$mode}->( $check, $against );
}


sub cmp_versions ( $left, $right ) {
    my ( $maj, $min, $rev, $sup ) = split /[\._]/, $left;
    my ( $mj,  $mn,  $rv,  $sp )  = split /[\._]/, $right;

    return $maj <=> $mj || $min <=> $mn || $rev <=> $rv || $sup <=> $sp;
}


sub get_major_release ( $version = '' ) {
    $version =~ s/\s*//g;
    my ( $major, $minor );
    if ( $version =~ m/^([0-9]+)\.([0-9]+)/ ) {
        $major = int $1;
        $minor = int $2;
    }
    else {
        return;
    }
    $minor++ if $minor % 2;
    return "$major.$minor";
}


sub compare_major_release ( $check, $mode, $against ) {

    return unless defined $check && defined $mode && defined $against;
    my $maj1 = get_major_release($check);
    return unless defined $maj1;
    my $maj2 = get_major_release($against);
    return unless defined $maj2;
    return $modes{$mode}->( $maj1, $maj2 );
}


1;

} # --- END Cpanel/Version/Compare.pm


{ # --- BEGIN Cpanel/Version.pm
package Cpanel::Version;


use strict;
use warnings;
# use Cpanel::Version::Full ();

our ( $VERSION, $MAJORVERSION, $LTS ) = ( '4.0', '11.110', '11.110' );

sub get_version_text {
    return sprintf( "%d.%d (build %d)", ( split( m{\.}, Cpanel::Version::Full::getversion() ) )[ 1, 2, 3 ] );
}

sub get_version_parent {
    return _ver_key('parent_version');
}

sub get_version_display {
    return sprintf( "%d.%d.%d", ( split( m{\.}, Cpanel::Version::Full::getversion() ) )[ 1, 2, 3 ] );
}

{
    no warnings 'once';    # for updatenow
    *get_version_full = *Cpanel::Version::Full::getversion;
}

sub getversionnumber {
    return sprintf( "%d.%d.%d", ( split( m{\.}, Cpanel::Version::Full::getversion() ) )[ 0, 1, 2 ] );
}

sub get_lts {
    return $LTS;
}

sub get_short_release_number {
    my $current_ver = ( split( m{\.}, Cpanel::Version::Full::getversion() ) )[1];
    if ( $current_ver % 2 == 0 ) {
        return $current_ver;
    }
    return $current_ver + 1;
}

sub _ver_key {
    require Cpanel::Version::Tiny if !$INC{'Cpanel/Version/Tiny.pm'};
    return ${ $Cpanel::Version::Tiny::{ $_[0] } };
}

sub compare {
    require Cpanel::Version::Compare;
    goto &Cpanel::Version::Compare::compare;
}

sub is_major_version {
    my ( $ver, $major ) = @_;

    require Cpanel::Version::Compare;

    return ( $ver eq $major || Cpanel::Version::Compare::get_major_release($ver) eq $major ) ? 1 : 0;
}

sub is_development_version {
    return substr( $MAJORVERSION, -1 ) % 2 ? 1 : 0;
}

sub display_version {
    my ($ver) = @_;
    if ( defined $ver && $ver =~ tr{\.}{} >= 2 ) {
        my @v = split( m{\.}, $ver );
        if ( $v[0] == 11 && $v[1] >= 54 ) {
            return join( '.', (@v)[ 1, 2, 3 ] );
        }
        return $ver;
    }
    return;
}

1;

} # --- END Cpanel/Version.pm


{ # --- BEGIN Cpanel/Locale.pm
package Cpanel::Locale;



use strict;

BEGIN {

    $ENV{'IGNORE_WIN32_LOCALE'} = 1;
}

# use Cpanel::CPAN::Locale::Maketext::Utils();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::CPAN::Locale::Maketext::Utils); }

# use Cpanel::Locale::Utils          ();    # Individual Locale modules depend on this being brought in here, if it is removed they will all need updated. Same for cpanel.pl
# use Cpanel::Locale::Utils::Paths   ();
# use Cpanel::CPAN::Locale::Maketext ();
# use Cpanel::Exception              ();

use constant _ENOENT => 2;

BEGIN {
    local $^H = 0;    # cheap no warnings without importing it
    local $^W = 0;

    *Cpanel::CPAN::Locale::Maketext::Utils::remove_key_from_lexicons = sub { };    # PPI NO PARSE - loaded above - disabled
}

our $SERVER_LOCALE_FILE = '/var/cpanel/server_locale';

our $LTR = 1;
our $RTL = 2;
our %known_locales_character_orientation = (
    ar               => $RTL,
    bn               => $LTR,
    bg               => $LTR,
    cs               => $LTR,
    da               => $LTR,
    de               => $LTR,
    el               => $LTR,
    en               => $LTR,
    en_US            => $LTR,
    en_GB            => $LTR,
    es_419           => $LTR,
    es               => $LTR,
    es_es            => $LTR,
    fi               => $LTR,
    fil              => $LTR,
    fr               => $LTR,
    he               => $RTL,
    hi               => $LTR,
    hu               => $LTR,
    i_cpanel_snowmen => $LTR,
    i_cp_qa          => $LTR,
    id               => $LTR,
    it               => $LTR,
    ja               => $LTR,
    ko               => $LTR,
    ms               => $LTR,
    nb               => $LTR,
    nl               => $LTR,
    no               => $LTR,
    pl               => $LTR,
    pt_br            => $LTR,
    pt               => $LTR,
    ro               => $LTR,
    ru               => $LTR,
    sl               => $LTR,
    sv               => $LTR,
    th               => $LTR,
    tr               => $LTR,
    uk               => $LTR,
    vi               => $LTR,
    zh               => $LTR,
    zh_tw            => $LTR,
    zh_cn            => $LTR,
);


my $logger;

sub _logger {
    require Cpanel::Logger;
    return ( $logger ||= Cpanel::Logger->new() );
}

*get_lookup_hash_of_mutli_epoch_datetime = *get_lookup_hash_of_multi_epoch_datetime;

sub preinit {
    if ( exists $INC{'Cpanel.pm'} && !$Cpanel::CPDATA{'LOCALE'} ) {
        require Cpanel::Locale::Utils::User if !exists $INC{'Cpanel/Locale/Utils/User.pm'};
        Cpanel::Locale::Utils::User::init_cpdata_keys();
    }

    if ( $ENV{'HTTP_COOKIE'} ) {
        require Cpanel::Cookies unless $INC{'Cpanel/Cookies.pm'};

        if ( !keys %Cpanel::Cookies ) {
            %Cpanel::Cookies = %{ Cpanel::Cookies::get_cookie_hashref() };
        }
    }

    %Cpanel::Grapheme = %{ Cpanel::Locale->get_grapheme_helper_hashref() };
    return 1;
}


sub makevar {
    return $_[0]->maketext( ref $_[1] ? @{ $_[1] } : @_[ 1 .. $#_ ] );    ## no extract maketext
}

*maketext = *Cpanel::CPAN::Locale::Maketext::maketext;                    ## no extract maketext

my %singleton_stash = ();


BEGIN {
    no warnings;    ## no critic(ProhibitNoWarnings)
    CHECK {
        if ( ( $INC{'O.pm'} || $INC{'Cpanel/BinCheck.pm'} || $INC{'Cpanel/BinCheck/Lite.pm'} ) && %singleton_stash ) {
            die("If you use a locale at begin time, you are responsible for deleting it too. Try calling _reset_singleton_stash\n");
        }
    }
}

sub _reset_singleton_stash {
    foreach my $class ( keys %singleton_stash ) {
        foreach my $args_sig ( keys %{ $singleton_stash{$class} } ) {
            $singleton_stash{$class}{$args_sig}->cpanel_detach_lexicon();
        }
    }
    %singleton_stash = ();
    return 1;
}

sub get_handle {
    preinit();
    no warnings 'redefine';
    *get_handle = *_real_get_handle;
    goto &_real_get_handle;
}

sub _map_any_old_style_to_new_style {
    my (@locales) = @_;
    if ( grep { !$known_locales_character_orientation{$_} && index( $_, 'i_' ) != 0 } @locales ) {
        require Cpanel::Locale::Utils::Legacy;
        goto \&Cpanel::Locale::Utils::Legacy::map_any_old_style_to_new_style;
    }
    return @locales;
}

our $IN_REAL_GET_HANDLE = 0;

sub _setup_for_real_get_handle {    ## no critic qw(RequireArgUnpacking)

    if ($IN_REAL_GET_HANDLE) {
        _load_carp();
        if ( $IN_REAL_GET_HANDLE > 1 ) {
            die 'Cpanel::Carp'->can('safe_longmess')->("Attempted to call _setup_for_real_get_handle from _setup_for_real_get_handle");
        }
        warn 'Cpanel::Carp'->can('safe_longmess')->("Attempted to call _setup_for_real_get_handle from _setup_for_real_get_handle");
        if ($Cpanel::Exception::IN_EXCEPTION_CREATION) {    # PPI NO PARSE - Only care about this check if the module is loaded
            $Cpanel::Exception::LOCALIZE_STRINGS = 0;       # PPI NO PARSE - Only care about this check if the module is loaded
        }
    }
    local $IN_REAL_GET_HANDLE = $IN_REAL_GET_HANDLE + 1;

    if ( defined $Cpanel::App::appname && defined $ENV{'REMOTE_USER'} ) {    # PPI NO PARSE - Only care about this check if the module is loaded
        if (
            $Cpanel::App::appname eq 'whostmgr'                              # PPI NO PARSE - Only care about this check if the module is loaded
            && $ENV{'REMOTE_USER'} ne 'root'
        ) {

            require Cpanel::Config::HasCpUserFile;
            if ( Cpanel::Config::HasCpUserFile::has_readable_cpuser_file( $ENV{'REMOTE_USER'} ) ) {
                require Cpanel::Config::LoadCpUserFile::CurrentUser;
                my $cpdata_ref = Cpanel::Config::LoadCpUserFile::CurrentUser::load( $ENV{'REMOTE_USER'} );

                if ( scalar keys %{$cpdata_ref} ) {
                    *Cpanel::CPDATA = $cpdata_ref;
                }
            }
        }
    }

    my ( $class, @langtags ) = (
        $_[0],
        (
              defined $_[1]                                                                   ? _map_any_old_style_to_new_style( (@_)[ 1 .. $#_ ] )
            : exists $Cpanel::Cookies{'session_locale'} && $Cpanel::Cookies{'session_locale'} ? _map_any_old_style_to_new_style( $Cpanel::Cookies{'session_locale'} )
            : ( exists $Cpanel::CPDATA{'LOCALE'} && $Cpanel::CPDATA{'LOCALE'} )               ? ( $Cpanel::CPDATA{'LOCALE'} )
            : ( exists $Cpanel::CPDATA{'LANG'} && $Cpanel::CPDATA{'LANG'} )                   ? ( _map_any_old_style_to_new_style( $Cpanel::CPDATA{'LANG'} ) )
            :                                                                                   ( get_server_locale() )
        )
    );

    if ( !$Cpanel::Locale::CDB_File_Path ) {
        $Cpanel::Locale::CDB_File_Path = Cpanel::Locale::Utils::init_lexicon( 'en', \%Cpanel::Locale::Lexicon, \$Cpanel::Locale::VERSION, \$Cpanel::Locale::Encoding );
    }

    _make_alias_if_needed( @langtags ? @langtags : 'en_us' );

    return @langtags;
}

my %_made_aliases;

sub _make_alias_if_needed {
    foreach my $tag ( grep { ( $_ eq 'en' || $_ eq 'i_default' || $_ eq 'en_us' ) && !$_made_aliases{$_} } ( 'en', @_ ) ) {

        Cpanel::Locale->make_alias( [$tag], 1 );
        $_made_aliases{$tag} = 1;
    }
    return 0;
}

sub _real_get_handle {
    my ( $class, @arg_langtags ) = @_;

    my @langtags = _setup_for_real_get_handle( $class, @arg_langtags );
    @langtags = map { my $l = $_; $l = 'en' if ( $l eq 'en_us' || $l eq 'i_default' ); $l } grep { $class->cpanel_is_valid_locale($_) } @langtags;
    @langtags = ('en') unless scalar @langtags;

    my $args_sig = join( ',', @langtags ) || 'no_args';

    return (
        ( defined $singleton_stash{$class}{$args_sig} && ++$singleton_stash{$class}{$args_sig}->{'_singleton_reused'} )
        ? $singleton_stash{$class}{$args_sig}
        : ( $singleton_stash{$class}{$args_sig} = Cpanel::CPAN::Locale::Maketext::get_handle( $class, @langtags ) )
    );

}

sub get_non_singleton_handle {
    my ( $class, @arg_langtags ) = @_;

    my @langtags = _setup_for_real_get_handle( $class, @arg_langtags );

    return Cpanel::CPAN::Locale::Maketext::get_handle( $class, @langtags );
}

sub init {
    my ($lh) = @_;

    $lh->SUPER::init();

    $lh->_initialize_unknown_phrase_logging();
    $lh->_initialize_bracket_notation_whitelist();

    return $lh;
}

sub _initialize_unknown_phrase_logging {
    my $lh = shift;

    if ( defined $Cpanel::Locale::Context::DEFAULT_OUTPUT_CONTEXT ) {    # PPI NO PARSE - Only needed if loaded
        my $setter_cr = $lh->can("set_context_${Cpanel::Locale::Context::DEFAULT_OUTPUT_CONTEXT}") or do {    # PPI NO PARSE - Only needed if loaded
            die "Invalid \$Cpanel::Locale::Context::DEFAULT_OUTPUT_CONTEXT: “$Cpanel::Locale::Context::DEFAULT_OUTPUT_CONTEXT”!";    # PPI NO PARSE - Only needed if loaded
        };
        $setter_cr->($lh);
    }

    elsif ( defined $Cpanel::Carp::OUTPUT_FORMAT ) {    # issafe
        if ( $Cpanel::Carp::OUTPUT_FORMAT eq 'xml' ) {    # issafe
            $lh->set_context_plain();                     # no HTML markup or ANSI escape sequences
        }
        elsif ( $Cpanel::Carp::OUTPUT_FORMAT eq 'html' ) {    # issafe
            $lh->set_context_html();                          # HTML
        }
    }

    $lh->{'use_external_lex_cache'} = 1;

    if ( exists $Cpanel::CPDATA{'LOCALE_LOG_MISSING'} && $Cpanel::CPDATA{'LOCALE_LOG_MISSING'} ) {
        $lh->{'_log_phantom_key'} = sub {
            my ( $lh, $key ) = @_;


            my $chain      = '';
            my $base_class = $lh->get_base_class();
            foreach my $class ( $lh->get_language_class, $base_class ) {
                my $lex_path = $lh->get_cdb_file_path( $class eq $base_class ? 1 : 0 );
                next if !$lex_path;
                $chain .= "\tLOCALE: $class\n\tPATH: $lex_path\n";
                last if $class eq 'Cpanel::Locale::en' || $class eq 'Cpanel::Locale::en_us' || $class eq 'Cpanel::Locale::i_default';
            }

            my $pkg = $lh->get_language_tag();
            _logger->info( ( $Cpanel::Parser::Vars::file ? "$Cpanel::Parser::Vars::file ::" : '' ) . qq{ Could not find key via '$pkg' locale:\n\tKEY: '$key'\n$chain} );    # PPI NO PARSE -- module will already be there is we care about it

        };
    }
    return $lh;
}

our @DEFAULT_WHITELIST = qw(quant asis output current_year list_and list_or comment boolean datetime local_datetime format_bytes get_locale_name get_user_locale_name is_defined is_future join list_and_quoted list_or_quoted numerate numf);

sub _initialize_bracket_notation_whitelist {
    my $lh = shift;

    my @whitelist             = @DEFAULT_WHITELIST;
    my $custom_whitelist_file = Cpanel::Locale::Utils::Paths::get_custom_whitelist_path();

    if ( open( my $fh, '<', $custom_whitelist_file ) ) {
        while ( my $ln = readline($fh) ) {
            chomp $ln;
            push @whitelist, $ln if length($ln);
        }
        close $fh;
    }

    $lh->whitelist(@whitelist);
    return $lh;
}



sub output_cpanel_error {
    my ( $lh, $position ) = @_;

    if ( $lh->context_is_ansi() ) {
        return "\e[1;31m" if $position eq 'begin';
        return "\e[0m"    if $position eq 'end';
        return '';
    }
    elsif ( $lh->context_is_html() ) {
        return qq{<p style="color:#FF0000">} if $position eq 'begin';
        return '</p>'                        if $position eq 'end';
        return '';
    }
    else {
        return '';    # e.g. $lh->context_is_plain()
    }
}

sub cpanel_get_3rdparty_lang {
    my ( $lh, $_3rdparty ) = @_;
    require Cpanel::Locale::Utils::3rdparty;

    return Cpanel::Locale::Utils::3rdparty::get_app_setting( $lh, $_3rdparty ) || Cpanel::Locale::Utils::3rdparty::get_3rdparty_lang( $lh, $_3rdparty ) || $lh->get_language_tag() || 'en';
}

sub cpanel_is_valid_locale {
    my ( $lh, $locale ) = @_;

    my %valid_locales = map { $_ => 1 } ( qw(en en_us i_default), $lh->list_available_locales );
    return $valid_locales{$locale} ? 1 : 0;
}

sub cpanel_get_3rdparty_list {
    my ($lh) = @_;
    require Cpanel::Locale::Utils::3rdparty;
    return Cpanel::Locale::Utils::3rdparty::get_3rdparty_list($lh);
}

sub cpanel_get_lex_path {
    my ( $lh, $path, $rv ) = @_;

    return if !defined $path || $path eq '' || substr( $path, -3 ) ne '.js';

    require Cpanel::JS::Variations;

    my $query = $path;
    $query = Cpanel::JS::Variations::get_base_file( $query, '-%s.js' );

    if ( defined $rv && index( $rv, '%s' ) == -1 ) {
        substr( $rv, -3, 3, '-%s.js' );
    }

    my $asset_path = $lh->get_asset_file( $query, $rv );

    return $asset_path if $asset_path && substr( $asset_path, -3 ) eq '.js' && index( $asset_path, '-' ) > -1;    # Only return a value if there is a localized js file here
    return;
}

sub tag_is_default_locale {
    my $tag = $_[1] || $_[0]->get_language_tag();
    return 1 if $tag eq 'en' || $tag eq 'en_us' || $tag eq 'i_default';
    return;
}

sub get_cdb_file_path {
    my ( $lh, $core ) = @_;
    my $class = $core ? $lh->get_base_class() : $lh->get_language_class();
    no strict 'refs';
    return
         $class eq 'Cpanel::Locale::en'
      || $class eq 'Cpanel::Locale::en_us'
      || $class eq 'Cpanel::Locale::i_default' ? $Cpanel::Locale::CDB_File_Path : ${ $class . '::CDB_File_Path' };
}

sub _slurp_small_file_if_exists_no_exception {
    my ($path) = @_;

    local ( $!, $^E );

    open my $rfh, '<', $path or do {
        if ( $! != _ENOENT() ) {
            warn "open($path): $!";
        }

        return undef;
    };

    read $rfh, my $buf, 8192 or do {
        warn "read($path): $!";
    };

    return $buf;
}

my $_server_locale_file_contents;

sub get_server_locale {
    if ( exists $ENV{'CPANEL_SERVER_LOCALE'} ) {
        return $ENV{'CPANEL_SERVER_LOCALE'} if $ENV{'CPANEL_SERVER_LOCALE'} !~ tr{A-Za-z0-9_-}{}c;
        return undef;
    }
    if (%main::CPCONF) {
        return $main::CPCONF{'server_locale'} if exists $main::CPCONF{'server_locale'};
    }



    return ( $_server_locale_file_contents //= ( _slurp_small_file_if_exists_no_exception($SERVER_LOCALE_FILE) || '' ) );
}

sub _clear_cache {
    $_server_locale_file_contents = undef;
    return;
}

sub get_locale_for_user_cpanel {
    if (%main::CPCONF) {
        return $main::CPCONF{'cpanel_locale'} if exists $main::CPCONF{'cpanel_locale'};
        return $main::CPCONF{'server_locale'} if exists $main::CPCONF{'server_locale'};
    }
    require Cpanel::Config::LoadCpConf;
    my $cpconf = Cpanel::Config::LoadCpConf::loadcpconf_not_copy();    # safe since we do not modify cpconf

    return $cpconf->{'cpanel_locale'} if $cpconf->{'cpanel_locale'};    # will not be autovivified, 0 and "" are invalid, if the value is invalid they will get 'en'
    return $cpconf->{'server_locale'} if $cpconf->{'server_locale'};    # will not be autovivified, 0 and "" are invalid, if the value is invalid they will get 'en'
    return;
}

sub cpanel_reinit_lexicon {
    my ($lh) = @_;
    $lh->cpanel_detach_lexicon();
    $lh->cpanel_attach_lexicon();
}

my $detach_locale_lex;

sub cpanel_detach_lexicon {
    my ($lh) = @_;
    my $locale = $lh->get_language_tag();
    no strict 'refs';

    undef $Cpanel::Locale::CDB_File_Path;
    if ( $locale ne 'en' && $locale ne 'en_us' && $locale ne 'i_default' ) {
        $detach_locale_lex = ${ 'Cpanel::Locale::' . $locale . '::CDB_File_Path' };
        undef ${ 'Cpanel::Locale::' . $locale . '::CDB_File_Path' };
    }

    untie( %{ 'Cpanel::Locale::' . $locale . '::Lexicon' } );
    untie %Cpanel::Locale::Lexicon;
}

sub cpanel_attach_lexicon {
    my ($lh) = @_;
    my $locale = $lh->get_language_tag();

    $Cpanel::Locale::CDB_File_Path = Cpanel::Locale::Utils::init_lexicon( 'en', \%Cpanel::Locale::Lexicon, \$Cpanel::Locale::VERSION, \$Cpanel::Locale::Encoding );

    _make_alias_if_needed($locale);

    no strict 'refs';
    if ( defined $detach_locale_lex ) {
        ${ 'Cpanel::Locale::' . $locale . '::CDB_File_Path' } = $detach_locale_lex;
    }
    else {
        ${ 'Cpanel::Locale::' . $locale . '::CDB_File_Path' } = $Cpanel::Locale::CDB_File_Path;
    }

    my $file_path = $lh->get_cdb_file_path();
    return if !$file_path;
    return Cpanel::Locale::Utils::get_readonly_tie( $lh->get_cdb_file_path(), \%{ 'Cpanel::Locale::' . $locale . '::Lexicon' } );
}

sub is_rtl {
    my ($lh) = @_;

    return 'right-to-left' eq $lh->get_language_tag_character_orientation() ? 1 : 0;
}

sub get_language_tag_character_orientation {
    if ( my $direction = $known_locales_character_orientation{ $_[1] || $_[0]->{'fallback_locale'} || $_[0]->get_language_tag() } ) {
        return 'right-to-left' if $direction == $RTL;
        return 'left-to-right';
    }
    $_[0]->SUPER::get_language_tag_character_orientation( @_[ 1 .. $#_ ] );
}

my $menu_ar;

sub get_locale_menu_arrayref {
    return $menu_ar if $menu_ar;
    require Cpanel::Locale::Utils::Display;
    $menu_ar = [ Cpanel::Locale::Utils::Display::get_locale_menu_hashref(@_) ];    # always array context to get all structs, properly uses other args besides object
    return $menu_ar;
}

my $non_existent;

sub get_non_existent_locale_menu_arrayref {
    return $non_existent if $non_existent;
    require Cpanel::Locale::Utils::Display;
    $non_existent = [ Cpanel::Locale::Utils::Display::get_non_existent_locale_menu_hashref(@_) ];    # always array context to get all structs, properly uses other args besides object
    return $non_existent;
}

sub _api1_maketext {
    require Cpanel::Locale::Utils::Api1;
    goto \&Cpanel::Locale::Utils::Api1::_api1_maketext;                                              ## no extract maketext
}

our $api1 = {
    'maketext' => {                                                                                  ## no extract maketext
        'function'        => \&_api1_maketext,                                                       ## no extract maketext
        'internal'        => 1,
        'legacy_function' => 2,
        'modify'          => 'inherit',
    },
};

sub current_year {
    return (localtime)[5] + 1900;    # we override datetime() so we can't use the internal current_year()
}

sub local_datetime {
    my ( $lh, $epoch, $format ) = @_;
    my $timezone = $ENV{'TZ'} // do {
        require Cpanel::Timezones;
        Cpanel::Timezones::calculate_TZ_env();
    };
    return $lh->datetime( $epoch, $format, $timezone );
}

sub datetime {
    my ( $lh, $epoch, $format, $timezone ) = @_;
    require Cpanel::Locale::Utils::DateTime;

    if ( $epoch && $epoch =~ tr<0-9><>c ) {
        require    # do not include it in updatenow.static
          Cpanel::Validate::Time;
        Cpanel::Validate::Time::iso_or_die($epoch);

        require Cpanel::Time::ISO;
        $epoch = Cpanel::Time::ISO::iso2unix($epoch);
    }

    return Cpanel::Locale::Utils::DateTime::datetime( $lh, $epoch, $format, $timezone );
}

sub get_lookup_hash_of_multi_epoch_datetime {
    my ( $lh, $epochs_ar, $format, $timezone ) = @_;
    require Cpanel::Locale::Utils::DateTime;
    return Cpanel::Locale::Utils::DateTime::get_lookup_hash_of_multi_epoch_datetime( $lh, $epochs_ar, $format, $timezone );
}

sub get_locale_name_or_nothing {
    my ( $locale, $name, $in_locale_tongue ) = @_;
    $name ||= $locale->get_language_tag();

    if ( index( $name, 'i_' ) == 0 ) {
        require Cpanel::DataStore;
        my $i_locales_path = Cpanel::Locale::Utils::Paths::get_i_locales_config_path();
        my $i_conf         = Cpanel::DataStore::fetch_ref("$i_locales_path/$name.yaml");

        return $i_conf->{'display_name'} if $i_conf->{'display_name'};
    }
    else {
        my $real = $locale->get_language_tag_name( $name, $in_locale_tongue );
        return $real if $real;
    }

    return;
}

sub get_locale_name_or_tag {
    return $_[0]->get_locale_name_or_nothing( $_[1], $_[2] ) || $_[1] || $_[0]->get_language_tag();
}

*get_locale_name = *get_locale_name_or_tag;    # for shorter BN

sub get_user_locale {
    return $Cpanel::CPDATA{'LOCALE'} if $Cpanel::CPDATA{'LOCALE'};
    require Cpanel::Locale::Utils::User;       # probably a no-op but just in case since its loading is conditional
    return Cpanel::Locale::Utils::User::get_user_locale();
}

sub get_user_locale_name {
    require Cpanel::Locale::Utils::User;       # probably a no-op but just in case since its loading is conditional
    return $_[0]->get_locale_name_or_tag( Cpanel::Locale::Utils::User::get_user_locale( $_[1] ) );
}


sub set_user_locale {
    my ( $locale, $country_code ) = @_;

    if ($country_code) {
        my $language_name = $locale->lang_names_hashref();

        if ( exists $language_name->{$country_code} ) {
            require Cpanel::Locale::Utils::Legacy;
            require Cpanel::Locale::Utils::User::Modify;

            my $language = Cpanel::Locale::Utils::Legacy::get_best_guess_of_legacy_from_locale($country_code);
            if ( Cpanel::Locale::Utils::User::Modify::save_user_locale( $country_code, $language, $Cpanel::user ) ) {
                return 1;
            }

        }
    }

    die Cpanel::Exception::create_raw( "Empty", $locale->maketext("Unable to set locale, please specify a valid country code.") );
}


sub get_locales {

    my $locale = shift;
    my @listing;
    my ( $names, $local_names ) = $locale->lang_names_hashref();

    foreach ( keys %{$names} ) {
        push @listing, {
            locale     => $_,
            name       => $names->{$_},
            local_name => $local_names->{$_},
            direction  => ( !defined $known_locales_character_orientation{$_} || $known_locales_character_orientation{$_} == $LTR ) ? 'ltr' : 'rtl'
        };
    }

    return \@listing;

}

my $api2_lh;

sub api2_get_user_locale {
    $api2_lh ||= Cpanel::Locale->get_handle();
    return ( { 'locale' => $api2_lh->get_user_locale() } );
}

sub api2_get_user_locale_name {
    $api2_lh ||= Cpanel::Locale->get_handle();
    return ( { 'name' => $api2_lh->get_user_locale_name() } );
}

sub api2_get_locale_name {
    $api2_lh ||= Cpanel::Locale->get_handle();

    my $tag = ( scalar @_ > 2 ) ? {@_}->{'locale'} : $_[1];

    return ( { 'name' => $api2_lh->get_locale_name_or_tag($tag) } );
}

sub api2_get_encoding {
    $api2_lh ||= Cpanel::Locale->get_handle();
    return ( { 'encoding' => $api2_lh->encoding() } );
}

sub api2_numf {
    my %args = @_;
    $api2_lh ||= Cpanel::Locale->get_handle();
    return ( { 'numf' => $api2_lh->numf( $args{number}, $args{max_decimal_places} ) } );
}

sub api2_get_html_dir_attr {
    $api2_lh ||= Cpanel::Locale->get_handle();

    return ( { 'dir' => $api2_lh->get_html_dir_attr() } );
}

my $allow_demo = { allow_demo => 1 };

our %API = (
    get_locale_name      => $allow_demo,
    get_encoding         => $allow_demo,
    get_html_dir_attr    => $allow_demo,
    get_user_locale      => $allow_demo,
    get_user_locale_name => $allow_demo,
    numf                 => $allow_demo,
);

sub api2 {
    my ($func) = @_;
    return { %{ $API{$func} } } if $API{$func};
    return;
}

my $global_lh;


sub lh {
    return ( $global_lh ||= Cpanel::Locale->get_handle() );
}

sub import {
    my ( $package, @args ) = @_;
    my ($namespace) = caller;
    if ( @args == 1 && $args[0] eq 'lh' ) {
        no strict 'refs';    ## no critic(ProhibitNoStrict)
        my $exported_name = "${namespace}::lh";
        *$exported_name = \*lh;
    }
}

sub _load_carp {
    if ( !$INC{'Cpanel/Carp.pm'} ) {

        local $@;

        eval 'require Cpanel::Carp; 1;' or die $@;    # hide from perlcc
    }

    return;
}

sub user_feedback_text_for_more_locales {
    require Cpanel::Version;

    my $locale  = Cpanel::Locale->get_handle();
    my $version = Cpanel::Version::get_version_full();

    my $survey_url = 'https://cpanel.typeform.com/changeLng?utm_source=cpanel-changelanguage&cpanel_productversion=' . $version;

    return $locale->maketext( "Don’t see your language of choice? Take our [output,url,_1,Language Support Feedback Survey,class,externalLink,target,Language Survey] to let us know your preferences.", $survey_url );
}

1;

} # --- END Cpanel/Locale.pm


{ # --- BEGIN Cpanel/Exception/Collection.pm
package Cpanel::Exception::Collection;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

my $EXCEPTION_SEPARATOR = "\n";

sub _LINE_HEADER {
    my ($num) = @_;

    return Cpanel::LocaleString->new( 'Error #[numf,_1]:', $num );
}

sub _default_phrase {
    my ($self) = @_;

    my $excs_ar = $self->get('exceptions') or do {
        die ref($self) . ' instances must have “exceptions”!';
    };

    if ( !@$excs_ar ) {
        die "Must have at least 1 exception (or why do you need a “collection”?)";
    }

    return Cpanel::LocaleString->new(
        '[quant,_1,error,errors] occurred:',
        scalar @$excs_ar,
    );
}

sub to_en_string {
    my ($self) = @_;

    return $self->_stringify_specific('to_en_string');
}

sub to_en_string_no_id {
    my ($self) = @_;

    return $self->_stringify_specific('to_en_string_no_id');
}

sub to_locale_string {
    my ($self) = @_;

    return $self->_stringify_specific('to_locale_string');
}

sub to_locale_string_no_id {
    my ($self) = @_;

    return $self->_stringify_specific('to_locale_string_no_id');
}

my %LINE_HEADER_TRANSLATOR = qw(
  to_en_string              makethis_base
  to_locale_string          makevar
  to_en_string_no_id        makethis_base
  to_locale_string_no_id    makevar
);

sub _stringify_specific {
    my ( $self, $method ) = @_;

    my $exceptions_ar = $self->get('exceptions');

    my @lines = map { UNIVERSAL::isa( $_, 'Cpanel::Exception' ) ? $_->$method() : $_ } @$exceptions_ar;

    my $translator_name = $LINE_HEADER_TRANSLATOR{$method} or do {
        die "Invalid method: $method";
    };

    local $@;

    for my $l ( 0 .. $#lines ) {
        my $this_header = _locale()->$translator_name( _LINE_HEADER( 1 + $l )->to_list() );
        substr( $lines[$l], 0, 0, $EXCEPTION_SEPARATOR . "$this_header " );
    }

    return $self->can("SUPER::$method")->($self) . join q<>, @lines;
}

my $locale;

sub _locale {
    require Cpanel::Locale;
    return $locale ||= Cpanel::Locale->get_handle();
}

1;

} # --- END Cpanel/Exception/Collection.pm


{ # --- BEGIN Cpanel/Exception/CommandAlreadyRunning.pm
package Cpanel::Exception::CommandAlreadyRunning;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('file') ) {
        return Cpanel::LocaleString->new(
            'The command already has an active [asis,PIDFile] at “[_1]” and is running with the process [asis,ID]: [_2]',
            $self->get('file'),
            $self->get('pid'),
        );

    }
    else {
        return Cpanel::LocaleString->new(
            'The command is already running with the process [asis,ID]: [_1]',
            $self->get('pid'),
        );
    }
}

sub _spew {
    my ($self) = @_;

    if ($^S) {
        return $self->SUPER::_spew();
    }

    return $self->get_string_no_id() . "\n";
}

1;

} # --- END Cpanel/Exception/CommandAlreadyRunning.pm


{ # --- BEGIN Cpanel/Exception/ConnectionFailed.pm
package Cpanel::Exception::ConnectionFailed;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/ConnectionFailed.pm


{ # --- BEGIN Cpanel/Exception/ContextError.pm
package Cpanel::Exception::ContextError;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }


1;

} # --- END Cpanel/Exception/ContextError.pm


{ # --- BEGIN Cpanel/Exception/Database/SchemaOutdated.pm
package Cpanel::Exception::Database::SchemaOutdated;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/Database/SchemaOutdated.pm


{ # --- BEGIN Cpanel/Exception/Database/DatabaseCreationFailed.pm
package Cpanel::Exception::Database::DatabaseCreationFailed;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create the database “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(database error)},
    );
}

1;

} # --- END Cpanel/Exception/Database/DatabaseCreationFailed.pm


{ # --- BEGIN Cpanel/Exception/Database/DatabaseMissing.pm
package Cpanel::Exception::Database::DatabaseMissing;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('engine') eq 'mysql' ) {
        return Cpanel::LocaleString->new( 'Although the system’s database map includes a MySQL database named “[_1]”, the MySQL server reported that no database with this name exists. Contact your system administrator.', $self->get('name') );
    }
    elsif ( $self->get('engine') eq 'postgresql' ) {
        return Cpanel::LocaleString->new( 'Although the system’s database map includes a PostgreSQL database named “[_1]”, the PostgreSQL server reported that no database with this name exists. Contact your system administrator.', $self->get('name') );
    }

    die "Unknown DB engine: " . $self->get('engine');
}

1;

} # --- END Cpanel/Exception/Database/DatabaseMissing.pm


{ # --- BEGIN Cpanel/Exception/Database/Error.pm
package Cpanel::Exception::Database::Error;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LoadModule   ();
# use Cpanel::LocaleString ();

my %ERRCODE_MODULE = qw(
  mysql   Cpanel::Mysql::Error
  Pg      Cpanel::Postgres::Error
  SQLite  Cpanel::DBI::SQLite::Error
);

my %ERRCODE_IS_AT = qw(
  mysql   error_code
  Pg      state
  SQLite  error_code
);

my %SQL_DBMS_NAME = qw(
  mysql   MySQL
  Pg      PostgreSQL
  SQLite  SQLite
);

sub failure_is {
    my ( $self, $name ) = @_;

    my $driver = $self->get("dbi_driver");

    my $module = $ERRCODE_MODULE{$driver};
    die "Wrong driver? ($driver)" if !length $module;

    Cpanel::LoadModule::load_perl_module($module);

    my $cr = $module->can($name) or die "Invalid: $module\::$name";

    my $this_code = $self->_err_code();
    die "No code??" if !length $this_code;

    return $cr->() eq $this_code ? 1 : 0;
}

sub _err_code {
    my ($self) = @_;

    my $driver = $self->get("dbi_driver");
    my $code   = $self->get( $ERRCODE_IS_AT{$driver} );

    return $code;
}

sub _err_code_for_display {
    my ($self) = @_;

    my $err_name;

    my $err_code = $self->_err_code();

    my $driver = $self->get("dbi_driver");

    if ($err_code) {
        my $module = $ERRCODE_MODULE{$driver};
        Cpanel::LoadModule::load_perl_module($module);
        my $get_name_cr = $module->can('get_name_for_error') or die "$module has no get_name_for_error()!";
        $err_name = $get_name_cr->($err_code);
    }

    return $err_name || $err_code;
}

sub _err_message_for_display {
    my ($self) = @_;

    return $self->get('error_string') || $self->get('message') || 'Unknown';
}

sub _locale_string_with_dbname {
    return Cpanel::LocaleString->new('The system received an error from the “[_1]” database “[_2]”: [_3]');
}

sub _locale_string_without_dbname {
    return Cpanel::LocaleString->new('The system received an error from “[_1]”: [_2]');
}

sub _default_phrase {
    my ($self) = @_;

    my $err_msg = $self->_err_message_for_display();

    my $err_name = $self->_err_code_for_display();

    $err_msg = "$err_name ($err_msg)" if $err_name;

    my $dbname = $self->get('database');

    my $dbms_name = $SQL_DBMS_NAME{ $self->get('dbi_driver') };

    if ($dbname) {
        return $self->_locale_string_with_dbname()->clone_with_args( $dbms_name, $dbname, $err_msg );
    }

    return $self->_locale_string_without_dbname()->clone_with_args( $dbms_name, $err_msg );
}

1;

} # --- END Cpanel/Exception/Database/Error.pm


{ # --- BEGIN Cpanel/Exception/Database/ServerTime.pm
package Cpanel::Exception::Database::ServerTime;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new('The server time and the [asis,MySQL]® time are different.');
}

1;

} # --- END Cpanel/Exception/Database/ServerTime.pm


{ # --- BEGIN Cpanel/Exception/Database/TableCorruption.pm
package Cpanel::Exception::Database::TableCorruption;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();


sub _default_phrase {
    my ($self) = @_;

    my $reason_hr = $self->{'_metadata'}{'table_error'};

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

    return Cpanel::LocaleString->new(
        'The system detected corruption in the following [numerate,_1,table,tables]: [list_and,_2]',
        ( scalar @tables_disp ),
        \@tables_disp,
    );
}

1;

} # --- END Cpanel/Exception/Database/TableCorruption.pm


{ # --- BEGIN Cpanel/Exception/Database/TableCreationFailed.pm
package Cpanel::Exception::Database::TableCreationFailed;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create the table “[_1]” in the database “[_2]” because of an error: [_3]',
        @{ $self->{'_metadata'} }{qw(table database error)},
    );
}

1;

} # --- END Cpanel/Exception/Database/TableCreationFailed.pm


{ # --- BEGIN Cpanel/Exception/Database/TableInsertionFailed.pm
package Cpanel::Exception::Database::TableInsertionFailed;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to insert into the table “[_1]” of the database “[_2]” because of an error: [_3]',
        @{ $self->{'_metadata'} }{qw(table database error)},
    );
}

1;

} # --- END Cpanel/Exception/Database/TableInsertionFailed.pm


{ # --- BEGIN Cpanel/Exception/Database/UserMissing.pm
package Cpanel::Exception::Database::UserMissing;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('engine') eq 'mysql' ) {
        return Cpanel::LocaleString->new( 'Although the system’s database map includes a MySQL user named “[_1]”, the MySQL server reported that no user with this name exists. Contact your system administrator.', $self->get('name') );
    }
    elsif ( $self->get('engine') eq 'postgresql' ) {
        return Cpanel::LocaleString->new( 'Although the system’s database map includes a PostgreSQL user named “[_1]”, the PostgreSQL server reported that no user with this name exists. Contact your system administrator.', $self->get('name') );
    }

    die "Unknown DB engine: " . $self->get('engine');
}

1;

} # --- END Cpanel/Exception/Database/UserMissing.pm


{ # --- BEGIN Cpanel/Exception/Database/CpuserNotInMap.pm
package Cpanel::Exception::Database::CpuserNotInMap;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The [asis,cPanel] user “[_1]” does not exist in the database map.',
        $self->get('name'),
    );
}

1;

} # --- END Cpanel/Exception/Database/CpuserNotInMap.pm


{ # --- BEGIN Cpanel/Exception/Database/DatabaseCreationInProgress.pm
package Cpanel::Exception::Database::DatabaseCreationInProgress;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system cannot open the database “[_1]” because another process has created it but has not yet completed its initialization.',
        @{ $self->{'_metadata'} }{qw(database)},
    );
}

1;

} # --- END Cpanel/Exception/Database/DatabaseCreationInProgress.pm


{ # --- BEGIN Cpanel/Exception/Database/DatabaseNotFound.pm
package Cpanel::Exception::Database::DatabaseNotFound;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( length $self->get('cpuser') ) {
        my @mt_args = map { $self->get($_) } qw(cpuser name);

        if ( $self->get('engine') eq 'mysql' ) {
            return Cpanel::LocaleString->new( 'The system user “[_1]” does not control a MySQL database named “[_2]”.', @mt_args );
        }
        elsif ( $self->get('engine') eq 'postgresql' ) {
            return Cpanel::LocaleString->new( 'The system user “[_1]” does not control a PostgreSQL database named “[_2]”.', @mt_args );
        }
    }
    else {
        my @mt_args = ( $self->get('name') );

        if ( $self->get('engine') eq 'mysql' ) {
            return Cpanel::LocaleString->new( 'You do not control a MySQL database named “[_1]”.', @mt_args );
        }
        elsif ( $self->get('engine') eq 'postgresql' ) {
            return Cpanel::LocaleString->new( 'You do not control a PostgreSQL database named “[_1]”.', @mt_args );
        }
    }

    die "Unknown DB engine: " . $self->get('engine');
}

1;

} # --- END Cpanel/Exception/Database/DatabaseNotFound.pm


{ # --- BEGIN Cpanel/Exception/Database/UserNotFound.pm
package Cpanel::Exception::Database::UserNotFound;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( length $self->get('cpuser') ) {
        my @mt_args = map { $self->get($_) } qw(cpuser name);

        if ( $self->get('engine') eq 'mysql' ) {
            return Cpanel::LocaleString->new( 'The system user “[_1]” does not control a MySQL user named “[_2]”.', @mt_args );
        }
        elsif ( $self->get('engine') eq 'postgresql' ) {
            return Cpanel::LocaleString->new( 'The system user “[_1]” does not control a PostgreSQL user named “[_2]”.', @mt_args );
        }
    }
    else {
        my @mt_args = ( $self->get('name') );

        if ( $self->get('engine') eq 'mysql' ) {
            return Cpanel::LocaleString->new( 'You do not control a MySQL user named “[_1]”.', @mt_args );
        }
        elsif ( $self->get('engine') eq 'postgresql' ) {
            return Cpanel::LocaleString->new( 'You do not control a PostgreSQL user named “[_1]”.', @mt_args );
        }
    }

    die "Unknown DB engine: " . $self->get('engine');
}

1;

} # --- END Cpanel/Exception/Database/UserNotFound.pm


{ # --- BEGIN Cpanel/Exception/EntryAlreadyExists.pm
package Cpanel::Exception::EntryAlreadyExists;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/EntryAlreadyExists.pm


{ # --- BEGIN Cpanel/Exception/DnsEntryAlreadyExists.pm
package Cpanel::Exception::DnsEntryAlreadyExists;


use strict;
use warnings;

# use Cpanel::Exception::EntryAlreadyExists();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::EntryAlreadyExists); }

1;

} # --- END Cpanel/Exception/DnsEntryAlreadyExists.pm


{ # --- BEGIN Cpanel/Exception/DomainAlreadyExists.pm
package Cpanel::Exception::DomainAlreadyExists;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/DomainAlreadyExists.pm


{ # --- BEGIN Cpanel/Exception/DomainDoesNotExist.pm
package Cpanel::Exception::DomainDoesNotExist;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'This system does not have a domain named “[_1]”.',
        $self->get('name'),
    );
}

1;

1;

} # --- END Cpanel/Exception/DomainDoesNotExist.pm


{ # --- BEGIN Cpanel/Exception/DomainHasUnknownNameservers.pm
package Cpanel::Exception::DomainHasUnknownNameservers;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/DomainHasUnknownNameservers.pm


{ # --- BEGIN Cpanel/Exception/DomainNameNotAllowed.pm
package Cpanel::Exception::DomainNameNotAllowed;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $given, $why ) = map { $self->get($_) } qw(given why);

    if ( length $why ) {
        return Cpanel::LocaleString->new(
            'The system cannot accept “[_1]” as a domain name ([_2]).',
            $given,
            $why,
        );
    }

    return Cpanel::LocaleString->new(
        'The system cannot accept “[_1]” as a domain name.',
        $given,
    );
}

1;

} # --- END Cpanel/Exception/DomainNameNotAllowed.pm


{ # --- BEGIN Cpanel/Exception/DomainNameNotRfcCompliant.pm
package Cpanel::Exception::DomainNameNotRfcCompliant;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

my $RFC_1035_URL = 'http://tools.ietf.org/html/rfc1035';

sub _default_phrase {
    my ($self) = @_;

    my ( $given, $why ) = map { $self->get($_) } qw(given why);

    if ( length $why ) {
        return Cpanel::LocaleString->new(
            '“[_1]” is not a valid domain name per [output,url,_2,RFC 1035] ([_3]).',
            $given,
            $RFC_1035_URL,
            $why,
        );
    }

    return Cpanel::LocaleString->new(
        '“[_1]” is not a valid domain name per [output,url,_2,RFC 1035].',
        $given,
        $RFC_1035_URL,
    );
}

1;

} # --- END Cpanel/Exception/DomainNameNotRfcCompliant.pm


{ # --- BEGIN Cpanel/Exception/DomainNotRegistered.pm
package Cpanel::Exception::DomainNotRegistered;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/DomainNotRegistered.pm


{ # --- BEGIN Cpanel/Exception/DomainOwnership.pm
package Cpanel::Exception::DomainOwnership;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/DomainOwnership.pm


{ # --- BEGIN Cpanel/Exception/Email/AccountNotFound.pm
package Cpanel::Exception::Email::AccountNotFound;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'You do not have an email account named “[_1]”.',
        $self->get('name'),
    );
}

1;

} # --- END Cpanel/Exception/Email/AccountNotFound.pm


{ # --- BEGIN Cpanel/Exception/InvalidParameter.pm
package Cpanel::Exception::InvalidParameter;


use strict;
use warnings;



# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/InvalidParameter.pm


{ # --- BEGIN Cpanel/Exception/Empty.pm
package Cpanel::Exception::Empty;


use strict;
use warnings;

# use Cpanel::Exception::InvalidParameter();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::InvalidParameter); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( length $self->{'_metadata'}{'name'} ) {
        return Cpanel::LocaleString->new(
            'The value of “[_1]” may not be empty.',
            $self->{'_metadata'}{'name'},
        );
    }

    return Cpanel::LocaleString->new('This value may not be empty.');
}

1;

} # --- END Cpanel/Exception/Empty.pm


{ # --- BEGIN Cpanel/Exception/EntryDoesNotExist.pm
package Cpanel::Exception::EntryDoesNotExist;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/EntryDoesNotExist.pm


{ # --- BEGIN Cpanel/Exception/FeatureNotEnabled.pm
package Cpanel::Exception::FeatureNotEnabled;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'You do not have the feature “[_1]”.',
        $self->get('feature_name'),
    );
}

1;

} # --- END Cpanel/Exception/FeatureNotEnabled.pm


{ # --- BEGIN Cpanel/Exception/FeaturesNotEnabled.pm
package Cpanel::Exception::FeaturesNotEnabled;


use strict;
use warnings;


# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my $match = $self->get('match') // 'all';

    return Cpanel::LocaleString->new(
        'You do not have the [numerate,_1,feature,features] [list_and_quoted,_2].',
        scalar @{ $self->get('feature_names') },
        $self->get('feature_names'),
    ) if $match eq 'all';

    return Cpanel::LocaleString->new(
        'You do not have the [numerate,_1,feature,features] [list_or_quoted,_2].',
        scalar @{ $self->get('feature_names') },
        $self->get('feature_names'),
    );
}

1;

} # --- END Cpanel/Exception/FeaturesNotEnabled.pm


{ # --- BEGIN Cpanel/Exception/ForbiddenInDemoMode.pm
package Cpanel::Exception::ForbiddenInDemoMode;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new('This functionality is not available in demo mode.');
}

1;

} # --- END Cpanel/Exception/ForbiddenInDemoMode.pm


{ # --- BEGIN Cpanel/Exception/FunctionNotImplemented.pm
package Cpanel::Exception::FunctionNotImplemented;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The function “[_1]” has not been implemented. Override this function in a subclass.',
        $self->{'_metadata'}{'name'},
    );
}

1;

} # --- END Cpanel/Exception/FunctionNotImplemented.pm


{ # --- BEGIN Cpanel/URI/Password.pm
package Cpanel::URI::Password;



use cPstrict;

# use Cpanel::LoadModule ();

my $HIDDEN_STR = '__HIDDEN__';



sub strip_password ($url) {
    return unless defined $url;

    Cpanel::LoadModule::load_perl_module('URI::Split');

    my ( $scheme, $auth, $path, $query, $frag ) = URI::Split::uri_split($url);

    if ( length $auth && $auth =~ s[(?<=:).+(?=@)][$HIDDEN_STR] ) {
        return URI::Split::uri_join( $scheme, $auth, $path, $query, $frag );
    }

    return $url;
}


sub get_password ($url) {
    return unless defined $url;

    Cpanel::LoadModule::load_perl_module('URI::Split');

    my ( undef, $auth ) = URI::Split::uri_split($url);

    return unless defined $auth;

    $auth =~ m[(?<=:)(.+)(?=@)];

    return $1;
}

1;

} # --- END Cpanel/URI/Password.pm


{ # --- BEGIN Cpanel/Exception/Base/HasUrl.pm
package Cpanel::Exception::Base::HasUrl;



use strict;
use warnings;

our $_STACK_TRACE_SUBSTITUTION = '__CPANEL_URLPW_HIDDEN__';

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::URI::Password ();


sub get_url_without_password {
    my ($self) = @_;
    my $url = $self->get('url');

    return undef unless defined $url;
    return Cpanel::URI::Password::strip_password($url);
}


sub longmess {
    my ($self) = @_;

    my $mess = $self->SUPER::longmess();
    my $url  = $self->get('url');

    if ( defined $url && ( my $passwd = Cpanel::URI::Password::get_password($url) ) ) {
        $mess =~ s<\Q$passwd\E><$_STACK_TRACE_SUBSTITUTION>g;
    }

    return $mess;
}

1;

} # --- END Cpanel/Exception/Base/HasUrl.pm


{ # --- BEGIN Cpanel/Exception/HTTP.pm
package Cpanel::Exception::HTTP;


use strict;
use warnings;


# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/HTTP.pm


{ # --- BEGIN Cpanel/Exception/HTTP/Network.pm
package Cpanel::Exception::HTTP::Network;


use strict;
use warnings;

# use Cpanel::Exception::Base::HasUrl();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::Base::HasUrl); }
# use Cpanel::Exception::HTTP();
BEGIN { push @ISA, qw(Cpanel::Exception::HTTP); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to send an [output,abbr,HTTP,Hypertext Transfer Protocol] “[_1]” request to “[_2]” because of an error: [_3]',
        $self->get('method'),
        $self->get_url_without_password(),
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/HTTP/Network.pm


{ # --- BEGIN Cpanel/Exception/HTTP/Server.pm
package Cpanel::Exception::HTTP::Server;


use strict;
use warnings;

# use Cpanel::Exception::Base::HasUrl();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::Base::HasUrl); }
# use Cpanel::Exception::HTTP();
BEGIN { push @ISA, qw(Cpanel::Exception::HTTP); }

# use Cpanel::LocaleString ();

our $MAX_LENGTH_FOR_JSON = 512;

our $MAX_LENGTH_FOR_599 = 128;

our $MAX_LENGTH_FOR_OTHER = 32;


sub _default_phrase {
    my ($self) = @_;

    my $max_length = $MAX_LENGTH_FOR_OTHER;
    if ( '599' eq $self->get('status') ) {
        $max_length = $MAX_LENGTH_FOR_599;
    }
    elsif ( ( $self->get('content_type') || '' ) =~ m{^application/json\b} ) {
        $max_length = $MAX_LENGTH_FOR_JSON;
    }

    my $short_content = $self->get('content');
    if ( length $short_content > $max_length ) {
        $short_content = substr( $short_content, 0, $max_length - 1 ) . '…';
    }

    return Cpanel::LocaleString->new(
        'The response to the [output,abbr,HTTP,Hypertext Transfer Protocol] “[_1]” request from “[_2]” indicated an error ([_3], [_4]): [_5]',
        $self->get('method'),
        $self->get_url_without_password(),
        $self->get('status'),
        $self->get('reason'),
        $short_content,
    );
}

sub method  { return shift()->get('method') }
sub content { return shift()->get('content') }
sub url     { return shift()->get('url') }
sub status  { return shift()->get('status') }
sub reason  { return shift()->get('reason') }
sub headers { return shift()->get('headers') }

1;

} # --- END Cpanel/Exception/HTTP/Server.pm


{ # --- BEGIN Cpanel/Exception/InvalidCharacters.pm
package Cpanel::Exception::InvalidCharacters;


use strict;
use warnings;

# use Cpanel::Exception::InvalidParameter();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::InvalidParameter); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my $invalid_ar = $self->{'_metadata'}{'invalid_characters'};

    if ( @$invalid_ar == 1 ) {
        return Cpanel::LocaleString->new(
            'This value may not contain the character “[_1]”.',
            $invalid_ar->[0],
        );
    }

    return Cpanel::LocaleString->new(
        'This value may not contain any of the following [quant,_1,character,characters]: [join, ,_2]',
        scalar(@$invalid_ar),
        $invalid_ar,
    );
}

sub get_invalid_characters {
    my ($self) = @_;

    return [ @{ $self->{'_metadata'}{'invalid_characters'} } ];
}

1;

} # --- END Cpanel/Exception/InvalidCharacters.pm


{ # --- BEGIN Cpanel/Exception/InvalidParameters.pm
package Cpanel::Exception::InvalidParameters;


use strict;
use warnings;


# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/InvalidParameters.pm


{ # --- BEGIN Cpanel/Exception/InvalidUsername.pm
package Cpanel::Exception::InvalidUsername;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        '“[_1]” is not a valid username on this system.',
        $self->get('value'),
    );
}

1;

} # --- END Cpanel/Exception/InvalidUsername.pm


{ # --- BEGIN Cpanel/Exception/ErrnoBase.pm
package Cpanel::Exception::ErrnoBase;


use strict;
use warnings;


# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::Errno     ();
# use Cpanel::Exception ();

sub error_name {
    my ($self) = @_;

    return Cpanel::Errno::get_name_for_errno_number( 0 + $self->get('error') );
}

sub _default_phrase {
    die Cpanel::Exception::create( 'AbstractClass', [__PACKAGE__] );
}

1;

} # --- END Cpanel/Exception/ErrnoBase.pm


{ # --- BEGIN Cpanel/Exception/IOError.pm
package Cpanel::Exception::IOError;


use strict;
use warnings;


# use Cpanel::Exception::ErrnoBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ErrnoBase); }

sub error {
    my ($self) = @_;

    return $self->{'_metadata'}{'error'};
}

sub _default_phrase { die 'Unimplemented' }

1;

} # --- END Cpanel/Exception/IOError.pm


{ # --- BEGIN Cpanel/Exception/IO/CloseError.pm
package Cpanel::Exception::IO::CloseError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( my $filename = $self->get('filename') ) {
        return Cpanel::LocaleString->new(
            'The system failed to close a file handle for “[_1]” because of the following error: [_2]',
            $filename, $self->get('error'),
        );

    }

    return Cpanel::LocaleString->new(
        'The system failed to close a file handle because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/CloseError.pm


{ # --- BEGIN Cpanel/Exception/IO/ChdirError.pm
package Cpanel::Exception::IO::ChdirError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( length $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to change a process’s current directory to “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to change a process’s current directory because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/ChdirError.pm


{ # --- BEGIN Cpanel/Exception/IO/ChownError.pm
package Cpanel::Exception::IO::ChownError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $uid, $gid, $path, $error, $immutable, $append_only ) = @{ $self->{'_metadata'} }{qw(uid gid path error immutable append_only)};

    $path = [$path] if length($path) && !ref $path;

    if ( $uid == -1 ) {

        die "Huh? UID and GID were both -1 .. ?" if $gid == -1;

        if ($path) {
            my @args = (
                $gid,
                $path,
                $error,
            );

            if ($immutable) {
                return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on the immutable (+i) file [list_and_quoted,_2] because of an error: [_3]', @args );
            }
            elsif ($append_only) {
                return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on the append-only (+a) file [list_and_quoted,_2] because of an error: [_3]', @args );
            }

            return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on [list_and_quoted,_2] because of an error: [_3]', @args );
        }

        my @args = (
            $gid,
            $error,
        );

        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on one or more immutable (+i) filesystem nodes because of an error: [_2]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on one or more append-only (+a) filesystem nodes because of an error: [_2]', @args );
        }

        return Cpanel::LocaleString->new( 'The system failed to set the group ID to “[_1]” on one or more filesystem nodes because of an error: [_2]', @args );
    }

    if ( $gid == -1 ) {

        if ($path) {
            my @args = (
                $uid,
                $path,
                $error,
            );

            if ($immutable) {
                return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on the immutable (+i) file [list_and_quoted,_2] because of an error: [_3]', @args );

            }
            elsif ($append_only) {
                return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on the append-only (+a) file [list_and_quoted,_2] because of an error: [_3]', @args );

            }

            return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on [list_and_quoted,_2] because of an error: [_3]', @args );
        }

        my @args = (
            $uid,
            $error,
        );

        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on one or more immutable (+i) filesystem nodes because of an error: [_2]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on one or more append-only (+a) filesystem nodes because of an error: [_2]', @args );

        }

        return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” on one or more filesystem nodes because of an error: [_2]', @args );
    }

    if ($path) {
        my @args = (
            $uid,
            $gid,
            $path,
            $error,
        );

        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on the immutable (+i) file [list_and_quoted,_3] because of an error: [_4]', @args );

        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on the append-only (+a) file [list_and_quoted,_3] because of an error: [_4]', @args );

        }

        return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on [list_and_quoted,_3] because of an error: [_4]', @args );
    }

    my @args = (
        $uid,
        $gid,
        $error,
    );

    if ($immutable) {
        return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on one or more immutable (+i) filesystem nodes because of an error: [_3]', @args );
    }
    elsif ($append_only) {
        return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on one or more append-only (+a) filesystem nodes because of an error: [_3]', @args );

    }

    return Cpanel::LocaleString->new( 'The system failed to set the user ID to “[_1]” and the group ID to “[_2]” on one or more filesystem nodes because of an error: [_3]', @args );
}

1;

} # --- END Cpanel/Exception/IO/ChownError.pm


{ # --- BEGIN Cpanel/Exception/IO/ChrootError.pm
package Cpanel::Exception::IO::ChrootError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( length $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to change the root directory to “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to change the root directory because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/ChrootError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryCloseError.pm
package Cpanel::Exception::IO::DirectoryCloseError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to close the directory “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to close a directory because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryCloseError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryCreateError.pm
package Cpanel::Exception::IO::DirectoryCreateError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create the directory “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(path error)},
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryCreateError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryDeleteError.pm
package Cpanel::Exception::IO::DirectoryDeleteError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to delete the directory “[_1]” because of an error: [_2]',
        $self->get('path'),
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryDeleteError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryOpenError.pm
package Cpanel::Exception::IO::DirectoryOpenError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to open the directory “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(path error)},
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryOpenError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryReadError.pm
package Cpanel::Exception::IO::DirectoryReadError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to read the directory “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(path error)},
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryReadError.pm


{ # --- BEGIN Cpanel/Exception/IO/DirectoryRewindError.pm
package Cpanel::Exception::IO::DirectoryRewindError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to rewind its handle for the directory “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to rewind a directory handle because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/DirectoryRewindError.pm


{ # --- BEGIN Cpanel/Exception/IO/ExecError.pm
package Cpanel::Exception::IO::ExecError;



use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    die 'Need “error”!' if !$self->get('error');

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to execute the program “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to execute an unknown program because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/ExecError.pm


{ # --- BEGIN Cpanel/Exception/IO/FcntlError.pm
package Cpanel::Exception::IO::FcntlError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to manipulate a file descriptor because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/FcntlError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileCloseError.pm
package Cpanel::Exception::IO::FileCloseError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to close the file “[_1]” because of an error: [_2]',
            @{ $self->{'_metadata'} }{qw( path error )},
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to close an unknown file because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/FileCloseError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileCopyError.pm
package Cpanel::Exception::IO::FileCopyError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->{'_metadata'}{'error'} ) {
        return Cpanel::LocaleString->new(
            'The system failed to copy the file “[_1]” to “[_2]” because of an error: “[_3]”.',
            @{ $self->{'_metadata'} }{qw( source destination error )},
        );

    }
    else {
        return Cpanel::LocaleString->new(
            'The system failed to copy the file “[_1]” to “[_2]” because of an error.',
            @{ $self->{'_metadata'} }{qw( source destination )},
        );
    }
}

1;

} # --- END Cpanel/Exception/IO/FileCopyError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileNotFound.pm
package Cpanel::Exception::IO::FileNotFound;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system cannot find a file named “[_1]”.',
        $self->{'_metadata'}{'path'},
    );
}

1;

} # --- END Cpanel/Exception/IO/FileNotFound.pm


{ # --- BEGIN Cpanel/Exception/IO/FileOpenError.pm
package Cpanel::Exception::IO::FileOpenError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $mode, $immutable, $append_only ) = @{ $self->{'_metadata'} }{qw(mode immutable append_only)};

    if ( length($mode) && ( $mode =~ m<\A[0-9]+]\z> ) ) {
        return $self->_default_phrase_for_sysopen();    ## no extract maketext
    }

    my $for_reading = $mode && ( $mode =~ tr{<+}{} );
    my $for_writing = $mode && ( $mode =~ tr{>+}{} );

    my @args = @{ $self->{'_metadata'} }{qw(path error)};

    if ($for_reading) {
        if ($for_writing) {
            if ($immutable) {
                return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” for reading and writing because of an error: [_2]', @args );
            }
            elsif ($append_only) {
                return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” for reading and writing because of an error: [_2]', @args );
            }
            else {
                return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” for reading and writing because of an error: [_2]', @args );
            }
        }
        elsif ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” for reading because of an error: [_2]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” for reading because of an error: [_2]', @args );
        }

        return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” for reading because of an error: [_2]', @args );
    }
    elsif ($for_writing) {
        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” for writing because of an error: [_2]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” for writing because of an error: [_2]', @args );
        }

        return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” for writing because of an error: [_2]', @args );
    }
    elsif ($immutable) {
        return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” because of an error: [_2]', @args );
    }
    elsif ($append_only) {
        return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” because of an error: [_2]', @args );
    }

    return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” because of an error: [_2]', @args );
}

sub _default_phrase_for_sysopen {
    my ($self) = @_;

    my ( $path, $error, $mode, $permissions, $immutable, $append_only ) = @{ $self->{'_metadata'} }{qw(path error mode permissions immutable append_only)};

    my @flags;
    while ( my ( $key, $val ) = each %Cpanel::Fcntl::Constants:: ) {
        next if substr( $key, 0, 2 ) ne 'O_';
        next if ref $val ne 'SCALAR';

        push @flags, $key if $mode & $$val;
    }

    if ( length($permissions) ) {
        my $octal_permissions = sprintf( '%04o', $permissions );

        my @args = (
            $path,
            $octal_permissions,
            [ sort @flags ],
            $error,
        );

        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” with permissions “[_2]” and flags [list_and_quoted,_3] because of an error: [_4]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” with permissions “[_2]” and flags [list_and_quoted,_3] because of an error: [_4]', @args );
        }

        return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” with permissions “[_2]” and flags [list_and_quoted,_3] because of an error: [_4]', @args );
    }

    my @args = (
        $path,
        [ sort @flags ],
        $error,
    );

    if ($immutable) {
        return Cpanel::LocaleString->new( 'The system failed to open the immutable (+i) file “[_1]” with flags [list_and_quoted,_2] because of an error: [_3]', @args );
    }
    elsif ($append_only) {
        return Cpanel::LocaleString->new( 'The system failed to open the append-only (+a) file “[_1]” with flags [list_and_quoted,_2] because of an error: [_3]', @args );
    }

    return Cpanel::LocaleString->new( 'The system failed to open the file “[_1]” with flags [list_and_quoted,_2] because of an error: [_3]', @args );
}

1;

} # --- END Cpanel/Exception/IO/FileOpenError.pm


{ # --- BEGIN Cpanel/Exception/IO/ReadError.pm
package Cpanel::Exception::IO::ReadError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    die "Need “error”!" if !$self->get('error');

    if ( defined $self->get('length') ) {
        if ( $self->get('path') ) {
            return Cpanel::LocaleString->new(
                'The system failed to read up to [format_bytes,_1] from “[_2]” because of an error: [_3]',
                $self->get('length'),
                $self->get('path'),
                $self->get('error'),
            );
        }

        return Cpanel::LocaleString->new(
            'The system failed to read up to [format_bytes,_1] from a file handle because of an error: [_2]',
            $self->get('length'),
            $self->get('error'),
        );
    }

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to read from “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to read from a file handle because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/ReadError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileReadError.pm
package Cpanel::Exception::IO::FileReadError;


use strict;
use warnings;

# use Cpanel::Exception::IO::ReadError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IO::ReadError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to read from the file “[_1]” because of an error: [_2]',
            @{ $self->{'_metadata'} }{qw( path error )},
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to read from an unknown file because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/FileReadError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileSeekError.pm
package Cpanel::Exception::IO::FileSeekError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::Fcntl::Constants ();
# use Cpanel::LocaleString     ();

sub _default_phrase {
    my ($self) = @_;

    my ( $path, $position, $whence, $error ) = @{ $self->{'_metadata'} }{qw( path position whence error )};

    my $path_is_a_path_not_a_filehandle = length $path && !ref $path;

    if ( $whence == $Cpanel::Fcntl::Constants::SEEK_SET ) {
        if ($position) {
            if ($path_is_a_path_not_a_filehandle) {
                return Cpanel::LocaleString->new( 'The system failed to move the pointer for the file “[_1]” to [quant,_2,byte,bytes] after the beginning because of an error: [_3]', $path, $position, $error );
            }
            else {
                return Cpanel::LocaleString->new( 'The system failed to move the pointer for a file to [quant,_1,byte,bytes] after the beginning because of an error: [_2]', $position, $error );
            }
        }
        elsif ($path_is_a_path_not_a_filehandle) {
            return Cpanel::LocaleString->new(
                'The system failed to move the pointer for the file “[_1]” to the beginning because of an error: [_2]',
                $path,
                $error,
            );
        }

        return Cpanel::LocaleString->new(
            'The system failed to move the pointer for a file to the beginning because of an error: [_1]',
            $error,
        );
    }
    elsif ( $whence == $Cpanel::Fcntl::Constants::SEEK_CUR ) {
        if ( $position >= 0 ) {
            if ($path_is_a_path_not_a_filehandle) {
                return Cpanel::LocaleString->new( 'The system failed to advance the pointer for the file “[_1]” by [quant,_2,byte,bytes] because of an error: [_3]', $path, $position, $error );
            }
            else {
                return Cpanel::LocaleString->new( 'The system failed to advance the pointer for a file by [quant,_1,byte,bytes] because of an error: [_2]', $position, $error );
            }
        }
        elsif ($path_is_a_path_not_a_filehandle) {
            return Cpanel::LocaleString->new( 'The system failed to move the pointer for the file “[_1]” back by [quant,_2,byte,bytes] because of an error: [_3]', $path, -$position, $error );
        }

        return Cpanel::LocaleString->new( 'The system failed to move the pointer for a file back by [quant,_1,byte,bytes] because of an error: [_2]', -$position, $error );
    }
    elsif ( $whence == $Cpanel::Fcntl::Constants::SEEK_END ) {
        if ($position) {
            if ($path_is_a_path_not_a_filehandle) {
                return Cpanel::LocaleString->new( 'The system failed to move the pointer for the file “[_1]” to [quant,_2,byte,bytes] before the end because of an error: [_3]', $path, -$position, $error );
            }
            else {
                return Cpanel::LocaleString->new( 'The system failed to move the pointer for a file to [quant,_1,byte,bytes] before the end because of an error: [_2]', -$position, $error );
            }
        }
        elsif ($path_is_a_path_not_a_filehandle) {
            return Cpanel::LocaleString->new(
                'The system failed to move the pointer for the file “[_1]” to the end because of an error: [_2]',
                $path,
                $error,
            );
        }

        return Cpanel::LocaleString->new(
            'The system failed to move the pointer for a file to the end because of an error: [_1]',
            $error,
        );
    }

    return Cpanel::LocaleString->new(
        'The arguments to [asis,seek()] (“[_1]”, “[_2]”, “[_3]”) are invalid: [_4]',
        $path,
        $position,
        $whence,
        $error,
    );
}

1;

} # --- END Cpanel/Exception/IO/FileSeekError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileTruncateError.pm
package Cpanel::Exception::IO::FileTruncateError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to truncate the file “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to truncate a file because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/FileTruncateError.pm


{ # --- BEGIN Cpanel/Exception/IO/WriteError.pm
package Cpanel::Exception::IO::WriteError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to write [format_bytes,_1] to a file handle because of an error: [_2]',
        $self->get('length'),
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/WriteError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileWriteError.pm
package Cpanel::Exception::IO::FileWriteError;


use strict;
use warnings;

# use Cpanel::Exception::IO::WriteError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IO::WriteError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to write to the file “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(path error)},
    );
}

1;

} # --- END Cpanel/Exception/IO/FileWriteError.pm


{ # --- BEGIN Cpanel/Exception/IO/FlockError.pm
package Cpanel::Exception::IO::FlockError;



use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::Fcntl::Constants ();
# use Cpanel::LocaleString     ();

use constant FLAG_ORDER => qw(
  LOCK_SH
  LOCK_EX
  LOCK_UN
  LOCK_NB
);

sub _default_phrase {
    my ($self) = @_;

    my $op    = $self->get('operation');
    my @flags = _op_to_flags($op);

    if ( $op & $Cpanel::Fcntl::Constants::LOCK_UN ) {
        if ( $self->get('path') ) {
            return Cpanel::LocaleString->new(
                'The system failed to unlock ([join,~, ,_1]) the file “[_2]” because of an error: [_3]',
                \@flags,
                $self->get('path'),
                $self->get('error'),
            );
        }

        return Cpanel::LocaleString->new(
            'The system failed to unlock ([join,~, ,_1]) an unknown file because of an error: [_2]',
            \@flags,
            $self->get('error'),
        );
    }

    if ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to lock ([join,~, ,_1]) the file “[_2]” because of an error: [_3]',
            \@flags,
            $self->get('path'),
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to lock ([join,~, ,_1]) an unknown file because of an error: [_2]',
        \@flags,
        $self->get('error'),
    );
}

sub _op_to_flags {
    my ($op) = @_;

    return grep { $op & ${ *{ $Cpanel::Fcntl::Constants::{$_} }{'SCALAR'} } } FLAG_ORDER();
}

1;

} # --- END Cpanel/Exception/IO/FlockError.pm


{ # --- BEGIN Cpanel/Exception/IO/ForkError.pm
package Cpanel::Exception::IO::ForkError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to fork a new process because of an error: [_1]',
        $self->{'_metadata'}{'error'},
    );
}

1;

} # --- END Cpanel/Exception/IO/ForkError.pm


{ # --- BEGIN Cpanel/Exception/IO/LinkError.pm
package Cpanel::Exception::IO::LinkError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create a hard link “[_1]” to “[_2]” because of an error: [_3]',
        ( map { $self->get($_) } qw( newpath oldpath error ) ),
    );
}

1;

} # --- END Cpanel/Exception/IO/LinkError.pm


{ # --- BEGIN Cpanel/Exception/IO/RenameError.pm
package Cpanel::Exception::IO::RenameError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to rename “[_1]” to “[_2]” because of an error: [_3]',
        @{ $self->{'_metadata'} }{qw( oldpath newpath error )},
    );
}

1;

} # --- END Cpanel/Exception/IO/RenameError.pm


{ # --- BEGIN Cpanel/Exception/IO/SelectError.pm
package Cpanel::Exception::IO::SelectError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to multiplex filehandles because of an error: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/SelectError.pm


{ # --- BEGIN Cpanel/Exception/IO/SocketOpenError.pm
package Cpanel::Exception::IO::SocketOpenError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

use Socket ();

# use Cpanel::LocaleString ();

our @_domains_to_check = qw(
  AF_UNIX
  AF_INET
  AF_INET6
  AF_X25
  AF_APPLETALK
);

our @_types_to_check = qw(
  SOCK_STREAM
  SOCK_DGRAM
  SOCK_SEQPACKET
  SOCK_RAW
  SOCK_RDM
);

sub _default_phrase {
    my ($self) = @_;

    my ( $domain, $type, $protocol, $error ) = map { $self->get($_) } qw(
      domain
      type
      protocol
      error
    );

    return Cpanel::LocaleString->new(
        'The system failed to open a socket of domain “[_1]” and type “[_2]” using the “[_3]” protocol because of an error: [_4]',
        $self->_get_human_DOMAIN($domain),
        $self->_get_human_TYPE($type),
        $self->_get_human_PROTOCOL($protocol),
        $error,
    );
}

sub _get_human_DOMAIN {
    my ( $self, $value ) = @_;

    if ( _is_whole_number($value) ) {
        return _check_value_against_socket_masks( $value, \@_domains_to_check );
    }

    return $value;    #unrecognized
}

sub _get_human_TYPE {
    my ( $self, $value ) = @_;

    if ( _is_whole_number($value) ) {
        return _check_value_against_socket_masks( $value, \@_types_to_check );
    }

    return $value;    #unrecognized
}

sub _get_human_PROTOCOL {
    my ( $self, $value ) = @_;

    return ( getprotobynumber $value )[0] || $value;
}

sub _check_value_against_socket_masks {
    my ( $value, $masks_ar ) = @_;

    for my $checking (@$masks_ar) {
        my $mask = Socket->can($checking)->();
        return $checking if ( $value & $mask ) == $mask;
    }

    return $value;
}

sub _is_whole_number {
    my ($value) = @_;

    return length($value) && $value =~ m<\A[0-9]+\z>;
}

1;

} # --- END Cpanel/Exception/IO/SocketOpenError.pm


{ # --- BEGIN Cpanel/Exception/IO/SocketWriteError.pm
package Cpanel::Exception::IO::SocketWriteError;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/IO/SocketWriteError.pm


{ # --- BEGIN Cpanel/Exception/IO/StatError.pm
package Cpanel::Exception::IO::StatError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( defined $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to obtain filesystem information about “[_1]” because of an error: [_2]',
            ( map { $self->get($_) } qw( path error ) ),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to obtain filesystem information about the node that a file handle references because of an error: [_2]',
        ( map { $self->get($_) } qw( path error ) ),
    );
}

1;

} # --- END Cpanel/Exception/IO/StatError.pm


{ # --- BEGIN Cpanel/Exception/IO/SymlinkCreateError.pm
package Cpanel::Exception::IO::SymlinkCreateError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create a symbolic link “[_1]” to “[_2]” because of an error: [_3]',
        ( map { $self->get($_) } qw( newpath oldpath error ) ),
    );
}

1;

} # --- END Cpanel/Exception/IO/SymlinkCreateError.pm


{ # --- BEGIN Cpanel/Exception/IO/SymlinkReadError.pm
package Cpanel::Exception::IO::SymlinkReadError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to read “[_1]” as a symbolic link because of an error: [_2]',
        $self->get('path'),
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/SymlinkReadError.pm


{ # --- BEGIN Cpanel/Exception/IO/UnlinkError.pm
package Cpanel::Exception::IO::UnlinkError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my $path_ar = $self->get('path');

    $path_ar = [$path_ar] if !ref $path_ar;

    return Cpanel::LocaleString->new(
        'The system failed to unlink [list_and_quoted,_1] because of an error: [_2]',
        $path_ar,
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/UnlinkError.pm


{ # --- BEGIN Cpanel/Socket/Constants.pm
package Cpanel::Socket::Constants;


use strict;
use warnings;

our $SO_REUSEADDR = 2;

our $AF_UNIX  = 1;
our $AF_INET  = 2;
our $PF_INET  = 2;
our $AF_INET6 = 10;
our $PF_INET6 = 10;

our $PROTO_IP   = 0;
our $PROTO_ICMP = 1;
our $PROTO_TCP  = 6;
our $PROTO_UDP  = 17;

our $IPPROTO_TCP;
*IPPROTO_TCP = \$PROTO_TCP;

our $SO_PEERCRED   = 17;
our $SOL_SOCKET    = 1;
our $SOCK_STREAM   = 1;
our $SOCK_NONBLOCK = 2048;

our $SHUT_RD   = 0;
our $SHUT_WR   = 1;
our $SHUT_RDWR = 2;

our $MSG_PEEK     = 2;
our $MSG_NOSIGNAL = 16384;

1;

} # --- END Cpanel/Socket/Constants.pm


{ # --- BEGIN Cpanel/Socket/Micro.pm
package Cpanel::Socket::Micro;


use strict;

# use Cpanel::Context             ();
# use Cpanel::Socket::Constants   ();
# use Cpanel::Socket::UNIX::Micro ();

my $pack_template_AF_INET = q<
    s   #sin_family
    n   #sin_port - network order
    a4  #sin_addr
>;

my $pack_template_AF_INET6 = q<
    s   #sin6_family
    n   #sin6_port - network order
    L   #sin6_flowinfo
    a16 #sin6_addr
    L   #sin6_scope_id
>;

sub unpack_sockaddr_of_any_type {
    my ($packed) = @_;

    Cpanel::Context::must_be_list();

    my $type_constant = unpack( 's', $packed );

    my @socket_attrs;
    if ( $type_constant == $Cpanel::Socket::Constants::AF_UNIX ) {
        @socket_attrs = Cpanel::Socket::UNIX::Micro::unpack_sockaddr_un($packed);
    }
    elsif ( $type_constant == $Cpanel::Socket::Constants::AF_INET ) {
        @socket_attrs = unpack_sockaddr_in($packed);
    }
    elsif ( $type_constant == $Cpanel::Socket::Constants::AF_INET6 ) {
        @socket_attrs = unpack_sockaddr_in6($packed);
    }
    else {
        die "Unrecognized socket family: $type_constant";
    }

    return ( $type_constant, @socket_attrs );
}

sub unpack_sockaddr_in {
    my ($sockaddr) = @_;

    Cpanel::Context::must_be_list();

    return ( unpack $pack_template_AF_INET, $sockaddr )[ 1, 2 ];
}

sub unpack_sockaddr_in6 {
    my ($sockaddr) = @_;

    Cpanel::Context::must_be_list();

    return ( unpack $pack_template_AF_INET6, $sockaddr )[ 1, 3, 2, 4 ];
}

sub inet_ntoa {
    my ($binary) = @_;
    return join '.', unpack 'C4', $binary;
}

sub inet6_ntoa {
    my ($binary) = @_;

    my @doubles = unpack 'n8', $binary;


    my %zeroes;
    my @zero_sequences;

    for my $d ( 0 .. $#doubles ) {
        next if $doubles[$d] > 0;

        if ( defined $zeroes{ $d - 1 } ) {
            $zeroes{$d} = $zeroes{ $d - 1 };    #assign scalar ref
            ++$zeroes{$d}->{'length'};
        }
        else {
            $zeroes{$d} = { start => $d, length => 1 };
            push @zero_sequences, $zeroes{$d};
        }
    }

    if (@zero_sequences) {

        my $biggest_seq = ( sort { $b->{'length'} <=> $a->{'length'} || $a->{'start'} <=> $b->{'start'} } @zero_sequences )[0];

        splice(
            @doubles,
            $biggest_seq->{'start'},
            $biggest_seq->{'length'},
            (q<>) x $biggest_seq->{'length'},
        );
    }

    my $str = join ':', map { length($_) ? sprintf( '%x', $_ ) : $_ } @doubles;

    $str =~ s<:::+><::>;

    return $str;
}

1;

} # --- END Cpanel/Socket/Micro.pm


{ # --- BEGIN Cpanel/Exception/IO/SocketConnectError.pm
package Cpanel::Exception::IO::SocketConnectError;


use strict;
use warnings;

# use Cpanel::Exception::ErrnoBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ErrnoBase); }

# use Cpanel::LocaleString ();

# use Cpanel::Socket::Constants ();
# use Cpanel::Socket::Micro     ();

sub _default_phrase {
    my ($self) = @_;

    my $to;

    my ( $type, @sockdata ) = ( $self->get('type'), $self->get('socket') );
    ( $type, @sockdata ) = Cpanel::Socket::Micro::unpack_sockaddr_of_any_type( $self->get('to') )
      if !$type && $self->get('to');

    if ( $type eq $Cpanel::Socket::Constants::AF_UNIX ) {
        $to = $sockdata[0];

        return Cpanel::LocaleString->new(
            'The system failed to connect a [asis,UNIX] domain socket to “[_1]” because of an error: [_2]',
            $to,
            $self->get('error'),
        );
    }

    my $addr;
    if ( $type eq $Cpanel::Socket::Constants::AF_INET ) {
        $addr = Cpanel::Socket::Micro::inet_ntoa( $sockdata[1] );
    }
    elsif ( $type eq $Cpanel::Socket::Constants::AF_INET6 ) {
        $addr = Cpanel::Socket::Micro::inet6_ntoa( $sockdata[1] );
    }
    elsif ( $type eq $Cpanel::Socket::Constants::AF_UNIX ) {
        $addr = $sockdata[1];
    }
    else {
        $addr = "unknown address";
    }

    return Cpanel::LocaleString->new(
        'The system failed to connect an Internet socket to port “[_1]” of “[_2]” because of an error: [_3]',
        $sockdata[0],
        $addr,
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/IO/SocketConnectError.pm


{ # --- BEGIN Cpanel/Exception/IO/ChmodError.pm
package Cpanel::Exception::IO::ChmodError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $path, $error, $permissions, $immutable, $append_only ) = @{ $self->{'_metadata'} }{qw(path error permissions immutable append_only)};

    my $print_perms = sprintf( '%04o', $permissions );

    @{ $self->{'_metadata'} }{qw(euid egid)} = ( $>, $) );

    if ( length $path ) {
        $path = [$path] if !ref $path;

        my @args = (
            $path,
            $print_perms,
            @{ $self->{'_metadata'} }{qw(euid egid)},
            $error,
        );

        if ($immutable) {
            return Cpanel::LocaleString->new( 'The system failed to set the permissions on the immutable (+i) file [list_and_quoted,_1] to “[_2]” (as [asis,EUID]: [_3], [asis,EGID]: [_4]) because of the following error: [_5]', @args );
        }
        elsif ($append_only) {
            return Cpanel::LocaleString->new( 'The system failed to set the permissions on the append-only (+a) file [list_and_quoted,_1] to “[_2]” (as [asis,EUID]: [_3], [asis,EGID]: [_4]) because of the following error: [_5]', @args );
        }

        return Cpanel::LocaleString->new( 'The system failed to set the permissions on [list_and_quoted,_1] to “[_2]” (as [asis,EUID]: [_3], [asis,EGID]: [_4]) because of the following error: [_5]', @args );
    }

    my @args = (
        $print_perms,
        @{ $self->{'_metadata'} }{qw(euid egid)},
        $error,
    );

    if ($immutable) {
        return Cpanel::LocaleString->new( 'The system failed to set the permissions on one or more immutable (+i) filesystem nodes to “[_1]” (as [asis,EUID]: [_2], [asis,EGID]: [_3]) because of the following error: [_4]', @args );

    }
    elsif ($append_only) {
        return Cpanel::LocaleString->new( 'The system failed to set the permissions on one or more append-only (+a) inodes to “[_1]” (as [asis,EUID]: [_2], [asis,EGID]: [_3]) because of the following error: [_4]', @args );

    }

    return Cpanel::LocaleString->new( 'The system failed to set the permissions on one or more inodes to “[_1]” (as [asis,EUID]: [_2], [asis,EGID]: [_3]) because of the following error: [_4]', @args );
}

1;

} # --- END Cpanel/Exception/IO/ChmodError.pm


{ # --- BEGIN Cpanel/Exception/IO/FileCreateError.pm
package Cpanel::Exception::IO::FileCreateError;


use strict;
use warnings;

# use Cpanel::Exception::IOError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::IOError); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    @{ $self->{'_metadata'} }{qw(euid egid)} = ( $>, $) );

    if ( defined $self->{'_metadata'}{'permissions'} ) {
        my $octal_permissions = sprintf( '%04o', $self->{'_metadata'}{'permissions'} );
        return Cpanel::LocaleString->new(
            'The system failed to create the file “[_1]” with permissions “[_2]” (as [asis,EUID]: [_3], [asis,EGID]: [_4]) because of the following error: [_5]',
            $self->{'_metadata'}{'path'},
            $octal_permissions,
            @{ $self->{'_metadata'} }{qw(euid egid error)},
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to create the file “[_1]” (as [asis,EUID]: [_2], [asis,EGID]: [_3]) because of the following error: [_4]',
        @{ $self->{'_metadata'} }{qw( path euid egid error )},
    );
}

1;

} # --- END Cpanel/Exception/IO/FileCreateError.pm


{ # --- BEGIN Cpanel/Exception/JSONParseError.pm
package Cpanel::Exception::JSONParseError;


use strict;
use warnings;

# use Cpanel::Exception::Caller();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::Caller); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('path') && $self->get('dataref') ) {
        if ( defined ${ $self->get('dataref') } ) {
            return Cpanel::LocaleString->new(
                'The system failed to parse the [asis,JSON] stream data “[_1]” from the file “[_2]” because of an error: [_3]',
                substr( ${ $self->get('dataref') }, 0, 1024 ),
                $self->get('path'),
                $self->get('error'),
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The system tried to parse a [asis,JSON] buffer from the file “[_1]”, but the [asis,JSON] parser received no data.',
                $self->get('path'),
            );
        }
    }
    elsif ( $self->get('path') ) {
        return Cpanel::LocaleString->new(
            'The system failed to parse the [asis,JSON] stream from the file “[_1]” because of an error: [_2]',
            $self->get('path'),
            $self->get('error'),
        );
    }

    my $caller_name = $self->_get_caller_name();
    if ( $caller_name && $self->get('dataref') ) {
        if ( defined ${ $self->get('dataref') } ) {
            return Cpanel::LocaleString->new(
                'The system failed to parse the [asis,JSON] stream data “[_1]” for the caller “[_2]” because of an error: [_3]',
                substr( ${ $self->get('dataref') }, 0, 1024 ),
                $caller_name,
                $self->get('error')
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The system tried to parse a [asis,JSON] buffer from the caller “[_1]”, but the [asis,JSON] parser received no data.',
                $caller_name,
            );
        }
    }
    elsif ($caller_name) {
        return Cpanel::LocaleString->new(
            'The system failed to parse the [asis,JSON] stream for the caller “[_1]” because of an error: [_2]',
            $caller_name,
            $self->get('error')
        );

    }

    return Cpanel::LocaleString->new(
        'The system failed to parse the [asis,JSON] stream: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/JSONParseError.pm


{ # --- BEGIN Cpanel/Exception/MissingMethod.pm
package Cpanel::Exception::MissingMethod;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;
    my ( $method, $pkg ) = map { $self->get($_) } qw(method pkg);

    return Cpanel::LocaleString->new(
        'The “[_1]” method is missing in the “[_2]” class.',
        $method,
        $pkg
    );
}

1;

} # --- END Cpanel/Exception/MissingMethod.pm


{ # --- BEGIN Cpanel/Exception/MissingParameter.pm
package Cpanel::Exception::MissingParameter;


use strict;
use warnings;

# use Cpanel::Exception::Caller();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::Caller); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my $caller_name = $self->_get_caller_name();
    if ( !$caller_name ) {
        return Cpanel::LocaleString->new(
            'Provide the “[_1]” parameter.',
            $self->get('name'),
        );
    }

    return Cpanel::LocaleString->new(
        'Provide the “[_1]” parameter for the “[_2]” function.',
        $self->{'_metadata'}{'name'},
        $caller_name
    );
}

1;

} # --- END Cpanel/Exception/MissingParameter.pm


{ # --- BEGIN Cpanel/Exception/MissingParameters.pm
package Cpanel::Exception::MissingParameters;


use strict;
use warnings;

# use Cpanel::Exception::MissingParameter();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::MissingParameter); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my $caller_name = $self->_get_caller_name();
    if ( !$caller_name ) {
        return Cpanel::LocaleString->new(
            'Provide the [list_and_quoted,_1] [numerate,_2,parameter,parameters].',
            $self->get('names'),
            scalar( @{ $self->get('names') } ),
        );
    }

    return Cpanel::LocaleString->new(
        'Provide the [list_and_quoted,_1] [numerate,_2,parameter,parameters] for the “[_3]” function.',
        $self->{'_metadata'}{'names'},
        scalar( @{ $self->{'_metadata'}{'names'} } ),
        $caller_name
    );
}

1;

} # --- END Cpanel/Exception/MissingParameters.pm


{ # --- BEGIN Cpanel/Exception/ModSecurity/DuplicateQueueItem.pm


package Cpanel::Exception::ModSecurity::DuplicateQueueItem;

use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;
    return Cpanel::LocaleString->new('The requested action is a duplicate.');
}

1;

} # --- END Cpanel/Exception/ModSecurity/DuplicateQueueItem.pm


{ # --- BEGIN Cpanel/Exception/ModuleLoadError.pm
package Cpanel::Exception::ModuleLoadError;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to load the module “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(module error)},
    );
}

sub is_not_found {
    my ($self) = @_;

    my $err  = $self->get('error');
    my $path = $self->get('module');

    $path =~ s<::></>g;
    $path .= '.pm';

    return ( 0 == index( $err, "Can't locate $path" ) );
}

1;

} # --- END Cpanel/Exception/ModuleLoadError.pm


{ # --- BEGIN Cpanel/Exception/Netlink.pm
package Cpanel::Exception::Netlink;


use strict;
use warnings;


# use Cpanel::Exception::ErrnoBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ErrnoBase); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'A [asis,Netlink] error occurred: [_1]',
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/Netlink.pm


{ # --- BEGIN Cpanel/Exception/ProcessFailed.pm
package Cpanel::Exception::ProcessFailed;



use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

my $MAX_STREAM_SPEWAGE_SIZE = 10_000;

sub _spew {
    my ($self) = @_;

    return join(
        "\n",
        length( $self->get('stdout') ) ? sprintf( "STDOUT: %s\n", substr( $self->get('stdout'), 0, $MAX_STREAM_SPEWAGE_SIZE ) ) : (),
        length( $self->get('stderr') ) ? sprintf( "STDERR: %s\n", substr( $self->get('stderr'), 0, $MAX_STREAM_SPEWAGE_SIZE ) ) : (),
        $self->SUPER::_spew(),
    );
}

1;

} # --- END Cpanel/Exception/ProcessFailed.pm


{ # --- BEGIN Cpanel/Exception/ProcessFailed/Error.pm
package Cpanel::Exception::ProcessFailed::Error;



use strict;
use warnings;

# use Cpanel::Exception::ProcessFailed();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ProcessFailed); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $error_code, $name, $pid, $stdout, $stderr ) = map { $self->get($_) } qw(
      error_code
      process_name
      pid
      stdout
      stderr
    );

    $stderr ||= '';

    die "Need “error_code”!" if !length $error_code;

    if ( length $name ) {
        if ( length $pid ) {
            return Cpanel::LocaleString->new(
                '“[_1]” (process [asis,ID] [_2]) reported error code “[_3]” when it ended: [_4]',
                $name,
                $pid,
                $error_code,
                $stderr
            );
        }

        return Cpanel::LocaleString->new(
            '“[_1]” reported error code “[_2]” when it ended: [_3]',
            $name,
            $error_code,
            $stderr,
        );
    }

    if ( length $pid ) {
        return Cpanel::LocaleString->new(
            'The subprocess with [asis,ID] “[_1]” reported error code “[_2]” when it ended: [_3]',
            $pid,
            $error_code,
            $stderr,
        );
    }

    return Cpanel::LocaleString->new(
        'A subprocess reported error code “[_1]” when it ended: [_2]',
        $error_code,
        $stderr,
    );
}

1;

} # --- END Cpanel/Exception/ProcessFailed/Error.pm


{ # --- BEGIN Cpanel/Exception/ProcessFailed/Signal.pm
package Cpanel::Exception::ProcessFailed::Signal;


use strict;
use warnings;

# use Cpanel::Exception::ProcessFailed();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ProcessFailed); }

# use Cpanel::Config::Constants::Perl ();
# use Cpanel::LocaleString            ();

sub _default_phrase {
    my ($self) = @_;

    my ( $sigcode, $name, $pid, $stdout, $stderr ) = map { $self->get($_) } qw(
      signal_code
      process_name
      pid
      stdout
      stderr
    );

    $stderr ||= '';

    die "Need “signal_code”!" if !length $sigcode;

    my $signame = $Cpanel::Config::Constants::Perl::SIGNAL_NAME{$sigcode};

    if ( length $name ) {
        if ( length $pid ) {
            return Cpanel::LocaleString->new(
                '“[_1]” (process [asis,ID] [_2]) ended prematurely because it received the “[_3]” ([_4]) signal: [_5]',
                $name,
                $pid,
                $signame,
                $sigcode,
                $stderr,
            );
        }

        return Cpanel::LocaleString->new(
            '“[_1]” ended prematurely because it received the “[_2]” ([_3]) signal: [_4]',
            $name,
            $signame,
            $sigcode,
            $stderr
        );
    }

    if ( length $pid ) {
        return Cpanel::LocaleString->new(
            'The subprocess with [asis,ID] “[_1]” ended prematurely because it received the “[_2]” ([_3]) signal: [_4]',
            $pid,
            $signame,
            $sigcode,
            $stderr
        );
    }

    return Cpanel::LocaleString->new(
        'A subprocess ended prematurely because it received the “[_1]” ([_2]) signal: [_3]',
        $signame,
        $sigcode,
        $stderr
    );
}

sub signal_name {
    my ($self) = @_;

    return $Cpanel::Config::Constants::Perl::SIGNAL_NAME{ $self->get('signal_code') };
}

1;

} # --- END Cpanel/Exception/ProcessFailed/Signal.pm


{ # --- BEGIN Cpanel/Exception/ProcessFailed/Timeout.pm
package Cpanel::Exception::ProcessFailed::Timeout;




use strict;
use warnings;

# use Cpanel::Exception::ProcessFailed();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ProcessFailed); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    my ( $timeout, $name, $pid ) = map { $self->get($_) } qw(
      timeout
      process_name
      pid
    );

    die "Need “timeout”!"               if !defined($timeout);
    die "“timeout” cannot be negative!" if $timeout < 0;

    if ( length $name ) {
        if ( length $pid ) {
            return Cpanel::LocaleString->new(
                'The system aborted the subprocess “[_1]” (process [asis,ID] “[_2]”) because it reached the timeout of [quant,_3,second,seconds].',
                $name,
                $pid,
                $timeout
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The system aborted the subprocess “[_1]” because it reached the timeout of [quant,_2,second,seconds].',
                $name,
                $timeout
            );
        }
    }
    else {
        if ( length $pid ) {
            return Cpanel::LocaleString->new(
                'The system aborted the subprocess with the [asis,ID] “[_1]” because it reached the timeout of [quant,_2,second,seconds].',
                $pid,
                $timeout
            );
        }
        else {
            return Cpanel::LocaleString->new(
                'The system aborted the subprocess because it reached the timeout of [quant,_1,second,seconds].',
                $timeout
            );
        }
    }
}

1;

} # --- END Cpanel/Exception/ProcessFailed/Timeout.pm


{ # --- BEGIN Cpanel/Exception/Reserved.pm
package Cpanel::Exception::Reserved;


use strict;
use warnings;

# use Cpanel::Exception::InvalidParameter();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::InvalidParameter); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        '“[_1]” is a reserved value.',
        $self->{'_metadata'}{'value'},
    );
}

1;

} # --- END Cpanel/Exception/Reserved.pm


{ # --- BEGIN Cpanel/Exception/ReservedSubdomain.pm
package Cpanel::Exception::ReservedSubdomain;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/ReservedSubdomain.pm


{ # --- BEGIN Cpanel/Exception/ResourceLimitReached.pm
package Cpanel::Exception::ResourceLimitReached;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/ResourceLimitReached.pm


{ # --- BEGIN Cpanel/Exception/RootProhibited.pm
package Cpanel::Exception::RootProhibited;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    return Cpanel::LocaleString->new('You cannot run this code as [asis,root].');
}

1;

} # --- END Cpanel/Exception/RootProhibited.pm


{ # --- BEGIN Cpanel/Exception/SMTP.pm
package Cpanel::Exception::SMTP;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/SMTP.pm


{ # --- BEGIN Cpanel/Exception/SMTP/FailedRecipient.pm
package Cpanel::Exception::SMTP::FailedRecipient;


use strict;
use warnings;

# use Cpanel::Exception::SMTP();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::SMTP); }

1;

} # --- END Cpanel/Exception/SMTP/FailedRecipient.pm


{ # --- BEGIN Cpanel/Exception/TempCreateError.pm
package Cpanel::Exception::TempCreateError;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/TempCreateError.pm


{ # --- BEGIN Cpanel/Exception/TempFileCreateError.pm
package Cpanel::Exception::TempFileCreateError;


use strict;
use warnings;

# use Cpanel::Exception::TempCreateError();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::TempCreateError); }
# use Cpanel::Exception::ErrnoBase();
BEGIN { push @ISA, qw(Cpanel::Exception::ErrnoBase); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The system failed to create the temporary file “[_1]” because of an error: [_2]',
        @{ $self->{'_metadata'} }{qw(path error)},
    );
}

1;

} # --- END Cpanel/Exception/TempFileCreateError.pm


{ # --- BEGIN Cpanel/Exception/Timeout.pm
package Cpanel::Exception::Timeout;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/Timeout.pm


{ # --- BEGIN Cpanel/Exception/TooManyBytes.pm
package Cpanel::Exception::TooManyBytes;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( $self->get('key') ) {
        return Cpanel::LocaleString->new(
            'The value “[_1]” for “[_2]” is too long by [quant,_3,byte,bytes]. The maximum allowed length is [quant,_4,byte,bytes].',
            $self->get('value'),
            $self->get('key'),
            $self->excess(),
            $self->{'_metadata'}{'maxlength'},
        );

    }
    return Cpanel::LocaleString->new(
        'The “[_1]” value exceeds the maximum length by [quant,_2,byte,bytes]. The maximum allowed length is [quant,_3,byte,bytes].',
        $self->get('value'),
        $self->excess(),
        $self->{'_metadata'}{'maxlength'},
    );
}

sub excess {
    my ($self) = @_;

    return length( $self->{'_metadata'}{'value'} ) - $self->{'_metadata'}{'maxlength'};
}

1;

} # --- END Cpanel/Exception/TooManyBytes.pm


{ # --- BEGIN Cpanel/Exception/Unsupported.pm
package Cpanel::Exception::Unsupported;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/Unsupported.pm


{ # --- BEGIN Cpanel/Exception/UserNotFound.pm
package Cpanel::Exception::UserNotFound;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'You do not have a user named “[_1]”.',
        $self->get('name'),
    );
}

1;

} # --- END Cpanel/Exception/UserNotFound.pm


{ # --- BEGIN Cpanel/Exception/AccessDeniedToAccount.pm
package Cpanel::Exception::AccessDeniedToAccount;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();


sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new( 'The user “[_1]” is not permitted to access the account “[_2]”.', $self->get('user'), $self->get('account') );
}

1;

} # --- END Cpanel/Exception/AccessDeniedToAccount.pm


{ # --- BEGIN Cpanel/Exception/SystemCall.pm
package Cpanel::Exception::SystemCall;



use strict;
use warnings;

# use Cpanel::Exception::ErrnoBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception::ErrnoBase); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    if ( my $args_ar = $self->get('arguments') ) {
        return Cpanel::LocaleString->new(
            'The system failed to execute the system call “[_1]” ([_2]) because of an error: [_3]',
            $self->get('name'),
            "@$args_ar",
            $self->get('error'),
        );
    }

    return Cpanel::LocaleString->new(
        'The system failed to execute the system call “[_1]” because of an error: [_2]',
        $self->get('name'),
        $self->get('error'),
    );
}

1;

} # --- END Cpanel/Exception/SystemCall.pm


{ # --- BEGIN Cpanel/Exception/Services/Unknown.pm
package Cpanel::Exception::Services::Unknown;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

# use Cpanel::LocaleString ();

sub _default_phrase {
    my ($self) = @_;

    return Cpanel::LocaleString->new(
        'The “[_1]” service is not a known service.',
        $self->get('service'),
    );
}

1;

} # --- END Cpanel/Exception/Services/Unknown.pm


{ # --- BEGIN Cpanel/Exception/UserdataLookupFailure.pm
package Cpanel::Exception::UserdataLookupFailure;


use strict;
use warnings;

# use Cpanel::Exception();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Exception); }

1;

} # --- END Cpanel/Exception/UserdataLookupFailure.pm


{ # --- BEGIN Cpanel/Exception/UpdateNow.pm
package Cpanel::Exception::UpdateNow;


use strict;
use warnings;


require Cpanel::Exception::AdminBinError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::AbstractClass;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::AttributeNotSet;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::AttributeReadOnly;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::System::RequiredRoleDisabled;            # PPI USE OK -- force load exception modules
require Cpanel::Exception::Caller;                                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::Collection;                              # PPI USE OK -- force load exception modules
require Cpanel::Exception::CommandAlreadyRunning;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::ConnectionFailed;                        # PPI USE OK -- force load exception modules
require Cpanel::Exception::ContextError;                            # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::SchemaOutdated;                # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::DatabaseCreationFailed;        # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::DatabaseMissing;               # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::Error;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::ServerTime;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::TableCorruption;               # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::TableCreationFailed;           # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::TableInsertionFailed;          # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::UserMissing;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::CpuserNotInMap;                # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::DatabaseCreationInProgress;    # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::DatabaseNotFound;              # PPI USE OK -- force load exception modules
require Cpanel::Exception::Database::UserNotFound;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::DnsEntryAlreadyExists;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainAlreadyExists;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainDoesNotExist;                      # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainHasUnknownNameservers;             # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainNameNotAllowed;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainNameNotRfcCompliant;               # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainNotRegistered;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::DomainOwnership;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::Email::AccountNotFound;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::Empty;                                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::EntryAlreadyExists;                      # PPI USE OK -- force load exception modules
require Cpanel::Exception::EntryDoesNotExist;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::FeatureNotEnabled;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::FeaturesNotEnabled;                      # PPI USE OK -- force load exception modules
require Cpanel::Exception::ForbiddenInDemoMode;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::FunctionNotImplemented;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::HTTP::Network;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::HTTP::Server;                            # PPI USE OK -- force load exception modules
require Cpanel::Exception::HTTP;                                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::InvalidCharacters;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::InvalidParameter;                        # PPI USE OK -- force load exception modules
require Cpanel::Exception::InvalidParameters;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::InvalidUsername;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::CloseError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ChdirError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ChownError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ChrootError;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryCloseError;                 # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryCreateError;                # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryDeleteError;                # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryOpenError;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryReadError;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::DirectoryRewindError;                # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ExecError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FcntlError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileCloseError;                      # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileCopyError;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileNotFound;                        # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileOpenError;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileReadError;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileSeekError;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileTruncateError;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileWriteError;                      # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FlockError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ForkError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::LinkError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::RenameError;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SelectError;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SocketOpenError;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SocketWriteError;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::StatError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SymlinkCreateError;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SymlinkReadError;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::UnlinkError;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::WriteError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ReadError;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::SocketConnectError;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::ChmodError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::IO::FileCreateError;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::IOError;                                 # PPI USE OK -- force load exception modules
require Cpanel::Exception::JSONParseError;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::MissingMethod;                           # PPI USE OK -- force load exception modules
require Cpanel::Exception::MissingParameter;                        # PPI USE OK -- force load exception modules
require Cpanel::Exception::MissingParameters;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::ModSecurity::DuplicateQueueItem;         # PPI USE OK -- force load exception modules
require Cpanel::Exception::ModuleLoadError;                         # PPI USE OK -- force load exception modules
require Cpanel::Exception::Netlink;                                 # PPI USE OK -- force load exception modules
require Cpanel::Exception::ProcessFailed::Error;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::ProcessFailed::Signal;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::ProcessFailed::Timeout;                  # PPI USE OK -- force load exception modules
require Cpanel::Exception::Reserved;                                # PPI USE OK -- force load exception modules
require Cpanel::Exception::ReservedSubdomain;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::ResourceLimitReached;                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::RootProhibited;                          # PPI USE OK -- force load exception modules
require Cpanel::Exception::SMTP;                                    # PPI USE OK -- force load exception modules
require Cpanel::Exception::SMTP::FailedRecipient;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::TempFileCreateError;                     # PPI USE OK -- force load exception modules
require Cpanel::Exception::Timeout;                                 # PPI USE OK -- force load exception modules
require Cpanel::Exception::TooManyBytes;                            # PPI USE OK -- force load exception modules
require Cpanel::Exception::Unsupported;                             # PPI USE OK -- force load exception modules
require Cpanel::Exception::UserNotFound;                            # PPI USE OK -- force load exception modules
require Cpanel::Exception::AccessDeniedToAccount;                   # PPI USE OK -- force load exception modules
require Cpanel::Exception::SystemCall;                              # PPI USE OK -- force load exception modules
require Cpanel::Exception::Services::Unknown;                       # PPI USE OK -- force load exception modules
require Cpanel::Exception::UserdataLookupFailure;                   # PPI USE OK -- force load exception modules

1;                                                                  # PPI USE OK -- force load exception modules

} # --- END Cpanel/Exception/UpdateNow.pm


{ # --- BEGIN Cpanel/Locale/Context.pm
package Cpanel::Locale::Context;


use strict;
use warnings;

our $DEFAULT_OUTPUT_CONTEXT;

1;

} # --- END Cpanel/Locale/Context.pm


{ # --- BEGIN Cpanel/SafeDir/RM.pm
package Cpanel::SafeDir::RM;


use strict;
use warnings;

sub safermdir {    ## no critic qw(Subroutines::RequireArgUnpacking)
    return   if !-d $_[0];
    return 1 if rmdir( $_[0] );
    if ( opendir( my $dh, $_[0] ) ) {
        while ( my $file = readdir($dh) ) {
            next if $file eq '.' || $file eq '..';
            unlink("$_[0]/$file") or last;
        }
    }
    return 1 if rmdir( $_[0] );
    require File::Path;
    File::Path::rmtree( $_[0] );

    if ( !-d $_[0] ) {


        $? = 0;
        return 1;
    }

    return;
}

1;

} # --- END Cpanel/SafeDir/RM.pm


{ # --- BEGIN Cpanel/Config/Sources.pm
package Cpanel::Config::Sources;


use strict;
use warnings;

# use Cpanel::Config::LoadConfig ();

use constant MY_IPV4_ENDPOINT => 'https://myip.cpanel.net/v1.0/';

our $cpsources_conf_file = '/etc/cpsources.conf';


sub get_source {
    my ($want_key) = @_;

    return unless length $want_key;
    my $conf = loadcpsources();
    return $conf->{$want_key} // '';
}

my $load_cpsources_cache;

sub set_cache {
    return $load_cpsources_cache = shift;
}

sub loadcpsources {
    if ( !$load_cpsources_cache ) {

        if ( ${^GLOBAL_PHASE} && ${^GLOBAL_PHASE} eq 'START' && lc($0) ne '-e' ) {
            die q[FATAL: loadcpsources is called during compile time. You should postpone this call.];
        }

        my $update_default = 'httpupdate.cpanel.net';
        my %sources        = (
            'NEWS'               => 'web.cpanel.net',
            'RSYNC'              => 'rsync.cpanel.net',
            'HTTPUPDATE'         => $update_default,
            'MYIP'               => MY_IPV4_ENDPOINT,               # URL to determine a local IP's public IP (1to1 NAT)
            'STORE_SERVER_URL'   => 'https://store.cpanel.net',
            'TICKETS_SERVER_URL' => 'https://account.cpanel.net',
            'VERIFY_URL'         => 'https://verify.cpanel.net',
            'MANAGE2_URL'        => 'https://manage2.cpanel.net',
        );

        if ( -e $cpsources_conf_file ) {
            Cpanel::Config::LoadConfig::loadConfig( $cpsources_conf_file, \%sources );
        }

        foreach my $key ( keys %sources ) {
            next if ( !defined $sources{$key} );
            $sources{$key} =~ s/^\s+//;
            $sources{$key} =~ s/\s+$//;
        }

        $load_cpsources_cache = \%sources;
    }

    return wantarray ? %$load_cpsources_cache : $load_cpsources_cache;
}


1;

} # --- END Cpanel/Config/Sources.pm


{ # --- BEGIN Cpanel/Crypt/GPG/Settings.pm
package Cpanel::Crypt::GPG::Settings;


use strict;

# use Cpanel::Config::CpConfGuard ();
# use Cpanel::Config::Sources     ();
# use Cpanel::Exception           ();

our $RELEASE_VALUE     = 'Release Keyring Only';
our $DEVELOPMENT_VALUE = 'Release and Development Keyrings';
our $OFF_VALUE         = 'Off';

our $OLD_DEVELOPMENT_VALUE = 'Release and Test Keyrings';

our $RELEASE_KEYRINGS     = ['release'];
our $DEVELOPMENT_KEYRINGS = [ 'release', 'development' ];
our $OFF_KEYRINGS         = [];

our $SIG_VALIDATION_CPCONF_KEY = 'signature_validation';

sub signature_validation_enabled {
    my $validation_setting = _load_cpconf_setting($SIG_VALIDATION_CPCONF_KEY);
    return ( $validation_setting eq $OFF_VALUE ) ? 0 : 1;
}

sub default_key_categories {
    my $validation_setting = shift || _load_cpconf_setting($SIG_VALIDATION_CPCONF_KEY);

    if ( $validation_setting eq $OFF_VALUE ) {
        return $OFF_KEYRINGS;
    }
    elsif ( $validation_setting eq $DEVELOPMENT_VALUE ) {
        return $DEVELOPMENT_KEYRINGS;
    }
    elsif ( $validation_setting eq $RELEASE_VALUE ) {
        return $RELEASE_KEYRINGS;
    }
    else {
        die Cpanel::Exception->create( 'Invalid signature validation setting: [_1]', [$validation_setting] );
    }
}

sub allowed_digest_algorithms {
    return ('sha512');
}

sub _load_cpconf_setting {
    my $setting = shift;

    my $conf = Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 )->config_copy;

    if ( $setting eq $SIG_VALIDATION_CPCONF_KEY ) {
        return validation_setting_fixup( $conf->{$setting} );
    }
    else {
        return $conf->{$setting};
    }
}

sub validation_setting_fixup {
    my $current_setting = shift;
    if ( defined $current_setting && $current_setting eq $OLD_DEVELOPMENT_VALUE ) {
        return $DEVELOPMENT_VALUE;
    }
    elsif ( !defined $current_setting || $current_setting !~ /^(?:\Q$OFF_VALUE\E|\Q$RELEASE_VALUE\E|\Q$DEVELOPMENT_VALUE\E)$/ ) {
        return validation_setting_for_configured_mirror();
    }
    return $current_setting;
}

sub validation_setting_for_configured_mirror {
    my $mirror = Cpanel::Config::Sources::loadcpsources();

    if ( $mirror->{'HTTPUPDATE'} =~ /^(?:.*\.dev|qa-build|next)\.cpanel\.net$/ ) {
        return $DEVELOPMENT_VALUE;
    }
    return $RELEASE_VALUE;
}

1;

} # --- END Cpanel/Crypt/GPG/Settings.pm


{ # --- BEGIN Cpanel/Update/Logger.pm
package Cpanel::Update::Logger;


use strict;
use warnings;
# use Cpanel::SafeDir::MK        ();
# use Cpanel::Time::Local        ();
# use Cpanel::FHUtils::Autoflush ();
use File::Basename             ();

use constant {
    DEBUG => 0,
    INFO  => 25,
    WARN  => 50,
    ERROR => 75,
    FATAL => 100,
};

our $VERSION = '1.2';

our $_BACKLOG_TIE_CLASS;

sub new {
    my $class = shift;
    my $self  = shift || {};
    ref($self) eq 'HASH' or CORE::die("hashref not passed to new");

    bless( $self, $class );

    $self->{'stdout'} = 1 if ( !defined $self->{'stdout'} );

    $self->{'timestamp'} = 1 if ( !defined $self->{'timestamp'} );

    if ( $self->{'to_memory'} ) {
        $self->{'backlog'} = [];

        tie @{ $self->{'backlog'} }, $_BACKLOG_TIE_CLASS if $_BACKLOG_TIE_CLASS;
    }

    eval { $self->set_logging_level( $self->{'log_level'} ); 1 }
      or CORE::die("An invalid logging level was passed to new: $self->{'log_level'}");

    $self->open_log() if $self->{'logfile'};

    if ( exists $self->{'pbar'} and defined $self->{'pbar'} ) {
        $self->{'pbar'} += 0;
        $self->update_pbar( $self->{'pbar'} );
    }

    return $self;
}

sub open_log {
    my $self = shift or CORE::die();

    my $log_file    = $self->{'logfile'};
    my $logfile_dir = File::Basename::dirname($log_file);
    my $created_dir = 0;
    if ( !-d $logfile_dir ) {
        Cpanel::SafeDir::MK::safemkdir( $logfile_dir, '0700', 2 );
        $created_dir = 1;
    }

    my $old_umask = umask(0077);    # Case 92381: Logs should not be world-readable
    open( my $fh, '>>', $log_file ) or do {
        CORE::die("Failed to open '$log_file' for append: $!");
    };

    umask($old_umask);

    Cpanel::FHUtils::Autoflush::enable($fh);
    Cpanel::FHUtils::Autoflush::enable( \*STDOUT ) if $self->{'stdout'};

    $self->{'fh'} = $fh;

    unless ( $self->{brief} ) {
        print {$fh} '-' x 100 . "\n";
        print {$fh} "=> Log opened from $0 ($$) at " . localtime(time) . "\n";
    }

    $self->warning("Had to create directory $logfile_dir before opening log") if ($created_dir);

    return;
}

sub close_log {
    my $self = shift or CORE::die();

    return if ( !$self->{'fh'} );
    my $fh = $self->{'fh'};

    unless ( $self->{brief} ) {
        print {$fh} "=> Log closed " . localtime(time) . "\n";
    }

    warn("Failed to close file handle for $self->{'logfile'}") if ( !close $fh );
    delete $self->{'fh'};

    return;
}

sub DESTROY {
    my $self = shift or CORE::die("DESTROY called without an object");
    $self->close_log if ( $self->{'fh'} );

    return;
}

sub log {
    my $self = shift         or CORE::die("log called as a class");
    ref $self eq __PACKAGE__ or CORE::die("log called as a class");

    my $msg = shift or return;

    my $stdout = shift;
    $stdout = $self->{'stdout'} if ( !defined $stdout );

    my $to_memory = $self->{'to_memory'};
    my $fh        = $self->{'fh'};

    foreach my $line ( split( /[\r\n]+/, $msg ) ) {
        if ( $self->{'timestamp'} ) {
            substr( $line, 0, 0, '[' . Cpanel::Time::Local::localtime2timestamp() . '] ' );
        }

        chomp $line;
        print STDOUT "$line\n" if $stdout;
        print {$fh} "$line\n"  if $fh;
        push @{ $self->{'backlog'} }, "$line" if ($to_memory);
    }

    return;
}

sub _die {
    my $self    = shift or CORE::die();
    my $message = shift || '';

    $self->log("***** DIE: $message");
    return CORE::die( "exit level [die] [pid=$$] ($message) " . join ' ', caller() );
}

sub fatal {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > FATAL );

    my $message = shift || '';

    $self->log("***** FATAL: $message");
    $self->set_need_notify();

    return;
}

sub error {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > ERROR );

    my $message = shift || '';

    $self->log("E $message");

    return;
}

sub warning {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > WARN );

    my $message = shift || '';

    $self->log("W $message");

    return;
}

sub panic {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > ERROR );

    my $message = shift || '';

    $self->log("***** PANIC!");
    $self->log("E $message");
    $self->log("***** PANIC!");
    $self->set_need_notify();

    return;
}

sub info {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > INFO );

    my $message = shift || '';

    $self->log("  $message");

    return;
}

sub debug {
    my $self = shift or CORE::die();
    return if ( $self->{'log_level_numeric'} > DEBUG );

    my $message = shift || '';

    $self->log("D $message");

    return;
}

sub get_logging_level { return shift->{'log_level'} }

sub set_logging_level {
    my $self = shift or CORE::die();

    my $log_level = shift;
    $log_level = 'info' if ( !defined $log_level );

    my $old_log_level = $self->get_logging_level();

    if ( $log_level =~ m/^fatal/i ) {
        $self->{'log_level'}         = 'fatal';
        $self->{'log_level_numeric'} = FATAL;
    }
    elsif ( $log_level =~ m/^error/i ) {
        $self->{'log_level'}         = 'error';
        $self->{'log_level_numeric'} = ERROR;
    }
    elsif ( $log_level =~ m/^warn/i ) {
        $self->{'log_level'}         = 'warning';
        $self->{'log_level_numeric'} = WARN;
    }
    elsif ( $log_level =~ m/^info/i ) {
        $self->{'log_level'}         = 'info';
        $self->{'log_level_numeric'} = INFO;
    }
    elsif ( $log_level =~ m/^debug/i ) {
        $self->{'log_level'}         = 'debug';
        $self->{'log_level_numeric'} = DEBUG;
    }
    else {
        CORE::die("Unknown logging level '$log_level' passed to set_logging_level");
    }

    return $old_log_level;
}

sub get_pbar { return shift->{'pbar'} }

sub increment_pbar {
    my $self = shift or CORE::die();
    return if ( !exists $self->{'pbar'} );

    my $amount    = shift || 1;
    my $new_value = $self->{'pbar'} + $amount;

    return $self->update_pbar($new_value);
}

sub update_pbar {
    my $self = shift or CORE::die();
    return if ( !exists $self->{'pbar'} );

    my $new_value = shift || 0;
    if ( $new_value > 100 ) {
        $self->debug("Pbar set to > 100 ($new_value)");
        $new_value = 100;
    }

    return if $new_value == $self->{'pbar'};
    $self->{'pbar'} = $new_value;

    $self->info( $new_value . '% complete' );

    return;
}

sub set_need_notify {
    my $self = shift;
    ref $self eq __PACKAGE__ or CORE::die("log called as a class");
    $self->info("The Administrator will be notified to review this output when this script completes");

    return $self->{'need_notify'} = 1;
}

sub get_need_notify {
    my $self = shift;
    ref $self eq __PACKAGE__ or CORE::die("log called as a class");
    return $self->{'need_notify'};
}

sub get_stored_log {
    my $self = shift;
    ref $self eq __PACKAGE__ or CORE::die("log called as a class");

    return if ( !$self->{'to_memory'} );

    return $self->{'backlog'};
}

sub get_next_log_message {
    my $self = shift;
    ref $self eq __PACKAGE__ or CORE::die("log called as a class");

    return if ( !$self->{'to_memory'} );

    return shift @{ $self->{'backlog'} };
}

sub success { goto \&info; }
sub out     { goto \&info; }
sub warn    { goto \&warning; }
sub die     { goto \&_die; }

1;

} # --- END Cpanel/Update/Logger.pm


{ # --- BEGIN Cpanel/Config/Merge.pm
package Cpanel::Config::Merge;


use strict;
use warnings;

# use Cpanel::Config::LoadConfig   ();
# use Cpanel::Config::FlushConfig  ();
# use Cpanel::Crypt::GPG::Settings ();
# use Cpanel::Update::Logger       ();


sub files {
    my (%opts) = @_;

    my $config_defaults_file = $opts{defaults_file} or die q[Missing required 'defaults_file' argument];    # a.k.a. source
    my $config_file          = $opts{config_file}   or die q[Missing required 'config_file' argument];      # a.k.a. destination
    my $logger               = $opts{logger} // Cpanel::Update::Logger->new;

    my $cpanel_config = {};                                                                                 # hash used to load config in memory

    Cpanel::Config::LoadConfig::loadConfig( $config_defaults_file, $cpanel_config );

    $cpanel_config->{'signature_validation'} = Cpanel::Crypt::GPG::Settings::validation_setting_for_configured_mirror();

    if ( -e $config_file ) {
        $logger->info("Merging custom cpanel.config entries provided by installer with cPanel defaults.");
        Cpanel::Config::LoadConfig::loadConfig( $config_file, $cpanel_config );
    }
    else {
        $logger->info("Installing default cpanel.config, located in etc/cpanel.config");
    }

    Cpanel::Config::FlushConfig::flushConfig( $config_file, $cpanel_config, '=', undef, { 'sort' => 1 } );

    return 1;
}


1;

} # --- END Cpanel/Config/Merge.pm


{ # --- BEGIN Cpanel/Binaries.pm
package Cpanel::Binaries;



use strict;
use warnings;

our @_OVERRIDES;
our $VERBOSE = 1;

use constant {
    PERL_MAJOR        => 536,
    PERL_LEGACY_MAJOR => 532,
    PHP_MAJOR         => 81,
    PHP_LEGACY_MAJOR  => 74,
    THIRD_PARTY       => q{/usr/local/cpanel/3rdparty},
};

use constant {
    THIRD_PARTY_BIN        => THIRD_PARTY . q{/bin},
    CPANEL_PERL            => THIRD_PARTY . q{/perl/} . PERL_MAJOR(),
    CPANEL_PERL_LEGACY     => THIRD_PARTY . q{/perl/} . PERL_LEGACY_MAJOR(),
    CPANEL_PHP             => THIRD_PARTY . q{/php/} . PHP_MAJOR(),
    CPANEL_PHP_LEGACY      => THIRD_PARTY . q{/php/} . PHP_LEGACY_MAJOR(),
    CPANEL_PHP_UNVERSIONED => THIRD_PARTY . q{/php/unversioned},
    SYSTEM_BIN             => q{/usr/bin},
    SYSTEM_SBIN            => q{/usr/sbin},
    CENTOS6_BIN            => q{/bin},
    CENTOS6_SBIN           => q{/sbin},
    LOCAL_BIN              => q{/usr/local/bin},
};

use constant {
    CPANEL_PERL_BIN       => CPANEL_PERL . q{/bin},
    CPANEL_PERL_SBIN      => CPANEL_PERL . q{/sbin},
    CPANEL_PHP_BIN        => CPANEL_PHP . q{/bin},
    CPANEL_PHP_LEGACY_BIN => CPANEL_PHP_LEGACY . q{/bin},
};

sub system_bin_locations {
    return {
        'identify' => SYSTEM_BIN,
        'convert'  => SYSTEM_BIN,
        'mogrify'  => SYSTEM_BIN,

        'firewall-cmd' => SYSTEM_BIN,
        'firewalld'    => SYSTEM_SBIN,

        'at'                 => SYSTEM_BIN,
        'atq'                => SYSTEM_BIN,
        'atrm'               => SYSTEM_BIN,
        'chattr'             => SYSTEM_BIN,
        'crontab'            => SYSTEM_BIN,
        'curl'               => SYSTEM_BIN,
        'dig'                => SYSTEM_BIN,
        'doveadm'            => SYSTEM_BIN,
        'dpkg-query'         => SYSTEM_BIN,
        'dsync'              => SYSTEM_BIN,
        'file'               => SYSTEM_BIN,
        'gcc'                => SYSTEM_BIN,
        'getfacl'            => SYSTEM_BIN,
        'gpg'                => SYSTEM_BIN,
        'gzip'               => SYSTEM_BIN,
        'host'               => SYSTEM_BIN,
        'iconv'              => SYSTEM_BIN,
        'ionice'             => SYSTEM_BIN,
        'iostat'             => SYSTEM_BIN,
        'ipcrm'              => SYSTEM_BIN,
        'ipcs'               => SYSTEM_BIN,
        'lsattr'             => SYSTEM_BIN,
        'mysql'              => SYSTEM_BIN,
        'mysql_config'       => SYSTEM_BIN,
        'mysql_upgrade'      => SYSTEM_BIN,
        'mysqladmin'         => SYSTEM_BIN,
        'mysqlcheck'         => SYSTEM_BIN,
        'mysqldump'          => SYSTEM_BIN,
        'nano'               => SYSTEM_BIN,
        'openssl'            => SYSTEM_BIN,
        'pdns_control'       => SYSTEM_BIN,
        'pdnsutil'           => SYSTEM_BIN,
        'perl'               => SYSTEM_BIN,
        'python2'            => THIRD_PARTY_BIN,
        'quota'              => SYSTEM_BIN,
        'repoquery'          => SYSTEM_BIN,
        'rsync'              => SYSTEM_BIN,
        'setfacl'            => SYSTEM_BIN,
        'ssh-keygen'         => SYSTEM_BIN,
        'ssh-keyscan'        => SYSTEM_BIN,
        'strace'             => SYSTEM_BIN,
        'sudo'               => SYSTEM_BIN,
        'systemctl'          => SYSTEM_BIN,
        'tail'               => SYSTEM_BIN,
        'test'               => SYSTEM_BIN,
        'unzip'              => SYSTEM_BIN,
        'vim'                => SYSTEM_BIN,
        'wall'               => SYSTEM_BIN,
        'xmlwf'              => SYSTEM_BIN,
        'yum'                => SYSTEM_BIN,
        'yum-config-manager' => SYSTEM_BIN,
        'zip'                => SYSTEM_BIN,

        'atd'            => SYSTEM_SBIN,
        'convertquota'   => SYSTEM_SBIN,
        'edquota'        => SYSTEM_SBIN,
        'exim'           => SYSTEM_SBIN,
        'exim_dbmbuild'  => SYSTEM_SBIN,
        'exim_tidydb'    => SYSTEM_SBIN,
        'grubby'         => CENTOS6_SBIN,
        'ifconfig'       => CENTOS6_SBIN,
        'ip'             => CENTOS6_SBIN,
        'ip6tables'      => CENTOS6_SBIN,
        'ip6tables-save' => CENTOS6_SBIN,
        'iptables'       => CENTOS6_SBIN,
        'iptables-save'  => CENTOS6_SBIN,
        'logrotate'      => SYSTEM_SBIN,
        'losetup'        => CENTOS6_SBIN,
        'mysqld'         => SYSTEM_SBIN,
        'named'          => SYSTEM_SBIN,
        'nft'            => SYSTEM_SBIN,
        'nscd'           => SYSTEM_SBIN,
        'pdns_server'    => SYSTEM_SBIN,
        'quotacheck'     => CENTOS6_SBIN,
        'quotaoff'       => CENTOS6_SBIN,
        'quotaon'        => CENTOS6_SBIN,
        'repquota'       => SYSTEM_SBIN,
        'rndc-confgen'   => SYSTEM_SBIN,
        'rsyslogd'       => CENTOS6_SBIN,
        'service'        => CENTOS6_SBIN,
        'sshd'           => SYSTEM_SBIN,

        'pkill' => SYSTEM_BIN,

        'bash'     => CENTOS6_BIN,
        'cat'      => CENTOS6_BIN,
        'cp'       => CENTOS6_BIN,
        'date'     => CENTOS6_BIN,
        'dd'       => CENTOS6_BIN,
        'df'       => CENTOS6_BIN,
        'echo'     => CENTOS6_BIN,
        'false'    => CENTOS6_BIN,
        'grep'     => CENTOS6_BIN,
        'hostname' => CENTOS6_BIN,
        'ls'       => CENTOS6_BIN,
        'mount'    => CENTOS6_BIN,
        'netstat'  => CENTOS6_BIN,
        'pwd'      => CENTOS6_BIN,
        'rm'       => CENTOS6_BIN,
        'rpm'      => CENTOS6_BIN,
        'sh'       => CENTOS6_BIN,
        'su'       => CENTOS6_BIN,
        'tar'      => CENTOS6_BIN,
        'true'     => CENTOS6_BIN,
        'umount'   => CENTOS6_BIN,
        'zcat'     => CENTOS6_BIN,

        'rsyslogd'   => CENTOS6_SBIN,
        'ip6tables'  => CENTOS6_SBIN,
        'ifconfig'   => CENTOS6_SBIN,
        'quotaoff'   => CENTOS6_SBIN,
        'losetup'    => CENTOS6_SBIN,
        'quotacheck' => CENTOS6_SBIN,
        'ip'         => CENTOS6_SBIN,
        'quotaon'    => CENTOS6_SBIN,
        'iptables'   => CENTOS6_SBIN,
        'service'    => CENTOS6_SBIN,
    };
}

sub dynamic_bin_location {
    my $binary = shift
      or die 'dynamic_bin_location($binary)';

    if ( $binary eq 'lsof' ) {
        return -e SYSTEM_BIN() . '/lsof'
          ? SYSTEM_BIN()
          : SYSTEM_SBIN();
    }
    else {
        return;
    }
}

sub thirdparty_binary_locations {
    return {
        %{ _get_thirdparty_binary_locations_static() },
        %{ _get_thirdparty_binary_locations_dynamic() },
    };
}

our %dynamic_vars = (

    'pear'       => 1,
    'peardev'    => 1,
    'pecl'       => 1,
    'phar'       => 1,
    'php'        => 1,
    'php-cgi'    => 1,
    'php-config' => 1,
    'phpize'     => 1,
);

our $cached_cleanup;    # Don't do these checks more than once.

sub _remove_server_type_specific_binaries {
    return if $cached_cleanup;
    return $cached_cleanup = 1;
}

sub _get_thirdparty_binary_location {
    my ($binary) = @_;

    _remove_server_type_specific_binaries();

    return ( exists( $dynamic_vars{$binary} ) ) ? _get_thirdparty_binary_locations_dynamic()->{$binary} : _get_thirdparty_binary_locations_static()->{$binary};
}

my $php_dir;

sub _get_thirdparty_binary_locations_dynamic {
    if ( !defined($php_dir) ) {
        $php_dir = Cpanel::Binaries::get_php_3rdparty_dir() . "bin";
    }

    _remove_server_type_specific_binaries();

    return { map { $_ => $php_dir } keys(%dynamic_vars) };
}

sub _get_thirdparty_binary_locations_static {
    return {
        'spamd'        => CPANEL_PERL_BIN,
        'spamc'        => CPANEL_PERL_BIN,
        'spamassassin' => CPANEL_PERL_BIN,
        'sa-compile'   => CPANEL_PERL_BIN,
        'sa-learn'     => CPANEL_PERL_BIN,
        'sa-update'    => CPANEL_PERL_BIN,

        'clamd'     => THIRD_PARTY_BIN,
        'clamdscan' => THIRD_PARTY_BIN,
        'freshclam' => THIRD_PARTY_BIN,

        'puttygen' => THIRD_PARTY_BIN,

        'pigz' => THIRD_PARTY_BIN,


        're2c' => THIRD_PARTY_BIN,

        'perl'       => CPANEL_PERL_BIN,
        'perlcc'     => CPANEL_PERL_BIN,
        'mysqldiff'  => CPANEL_PERL_BIN,
        'munin-cron' => CPANEL_PERL_BIN,

        'munin-node'           => CPANEL_PERL_SBIN,
        'munin-node-configure' => CPANEL_PERL_SBIN,

        'psql'       => THIRD_PARTY_BIN,
        'pg_dump'    => THIRD_PARTY_BIN,
        'pg_restore' => THIRD_PARTY_BIN,

        'python' => THIRD_PARTY_BIN,

        'git'                => THIRD_PARTY_BIN,
        'git-receive-pack'   => THIRD_PARTY_BIN,
        'git-shell'          => THIRD_PARTY_BIN,
        'git-upload-archive' => THIRD_PARTY_BIN,
        'git-upload-pack'    => THIRD_PARTY_BIN,

        'imunify360-agent' => SYSTEM_BIN,

        'wp-toolkit' => LOCAL_BIN,

        @_OVERRIDES,
    };
}


sub thirdparty_binary_names {
    return {};
}

sub LOG {
    my ($msg) = @_;
    return unless $VERBOSE && defined $msg;
    print "$msg\n";
    return;
}

sub optional_binaries {
    return qw/munin-cron munin-node munin-node-configure perlcc/;
}


sub path {
    my $binary = shift or return;

    if ( my $path = _get_thirdparty_binary_location($binary) ) {
        return $path . '/' . $binary;
    }

    my $bin_hash = system_bin_locations();
    if ( $bin_hash->{$binary} ) {
        return $bin_hash->{$binary} . '/' . $binary;
    }

    if ( my $dynamic_location = dynamic_bin_location($binary) ) {
        return $dynamic_location . '/' . $binary;
    }

    require Carp;
    Carp::confess("Unkonwn binary: '$binary', possible typo?");
}

sub get_prefix {
    my $binary = shift or return;

    my $binloc = _get_thirdparty_binary_location($binary);
    return unless $binloc;
    $binloc =~ s{/bin$}{};
    return $binloc;
}


sub get_php_version {
    my %args = @_;

    my $target_ver = _get_php_ver_only_for_testing('MAJOR');
    if ( !-x CPANEL_PHP_BIN . "/php" ) {
        $target_ver = _get_php_ver_only_for_testing('LEGACY');
    }

    return $target_ver if $args{flat};
    return join '.', split( '', $target_ver, 2 );
}

sub _get_php_ver_only_for_testing {
    return $_[0] eq 'MAJOR' ? PHP_MAJOR : PHP_LEGACY_MAJOR;
}


sub get_php_3rdparty_dir {
    my $ver = Cpanel::Binaries::get_php_version( 'flat' => 1 );
    return THIRD_PARTY . "/php/$ver/";
}


sub symlink_into_3rdparty_bin {
    my $bin_loc_hash = thirdparty_binary_locations();
    my $optional     = { map { $_ => 1 } optional_binaries() };
    my $third_bin    = THIRD_PARTY_BIN;

    my $ok = 1;

    foreach my $binary ( keys %$bin_loc_hash ) {
        next if ( $bin_loc_hash->{$binary} eq $third_bin );
        next if ( $bin_loc_hash->{$binary} eq SYSTEM_BIN );

        my $third_bin_names = thirdparty_binary_names();
        my $real_binary     = $third_bin_names->{$binary};
        $real_binary ||= $binary;
        my $real_location = $bin_loc_hash->{$binary} . '/' . $real_binary;
        if ( !-e $real_location ) {
            LOG("WARNING: Unexpectedly missing $binary") unless $optional->{$binary};
            next;
        }

        my $third_bin_loc = "$third_bin/$binary";
        if ( -e $third_bin_loc || -l $third_bin_loc ) {
            my $points_to = readlink($third_bin_loc);
            next if ( $points_to && $points_to eq $real_location );
            LOG( "Removing $third_bin_loc, which " . ( $points_to ? "unexpectedly pointed to $points_to" : "was not a symlink" ) );
            unlink $third_bin_loc;
        }

        LOG("Linking $third_bin_loc -> $real_location");
        $ok = 0 unless symlink( $real_location, $third_bin_loc );
    }

    return $ok;
}


sub binaries_to_symlink_into_system_bin {
    return [qw/git git-receive-pack git-shell git-upload-archive git-upload-pack/];
}


sub symlink_thirdparty_into_system_bin {
    my $ok           = 1;
    my $to_link_ref  = binaries_to_symlink_into_system_bin();
    my $bin_loc_hash = thirdparty_binary_locations();

    foreach my $binary (@$to_link_ref) {
        my $third_bin_loc = SYSTEM_BIN . qq{/$binary};
        my $real_location = $bin_loc_hash->{$binary} . '/' . $binary;

        if ( !-e $third_bin_loc && -x $real_location ) {
            LOG("Linking $third_bin_loc -> $real_location");
            $ok = 0 unless symlink( $real_location, $third_bin_loc );
        }
    }

    return $ok;
}

1;

} # --- END Cpanel/Binaries.pm


{ # --- BEGIN Cpanel/Crypt/GPG/Base.pm
package Cpanel::Crypt::GPG::Base;


use strict;
use warnings;


# use Cpanel::Binaries  ();
# use Cpanel::Exception ();


sub new {
    my ( $class, $opts_hr ) = @_;

    $opts_hr = {} if !( $opts_hr && 'HASH' eq ref $opts_hr );

    my $bin = _find_gpg_or_die();

    my $obj = {
        'bin' => $bin,
        %{$opts_hr},
    };

    return bless $obj, $class;
}


sub get_gpg_bin {
    my $self = shift;
    return $self->{bin};
}


sub _find_gpg_or_die {
    my $bin = Cpanel::Binaries::path('gpg');
    -x $bin or die Cpanel::Exception::create( 'Unsupported', 'Only servers with [asis,GPG] support this module.' );
    return $bin;
}

1;

} # --- END Cpanel/Crypt/GPG/Base.pm


{ # --- BEGIN Cpanel/Env.pm
package Cpanel::Env;


use strict;
use warnings;

our $VERSION = '1.7';

my $SAFE_ENV_VARS;

BEGIN {
    $SAFE_ENV_VARS = q<
        ALLUSERSPROFILE
        APPDATA
        BUNDLE_PATH
        CLIENTNAME
        COMMONPROGRAMFILES
        COMPUTERNAME
        COMSPEC
        CPANEL_BASE_INSTALL
        CPANEL_IS_CRON
        CPBACKUP
        DEBIAN_FRONTEND
        DEBIAN_PRIORITY
        DOCUMENT_ROOT
        FORCEDCPUPDATE
        FP_NO_HOST_CHECK
        HOMEDRIVE
        HOMEPATH
        LANG
        LANGUAGE
        LC_ALL
        LC_MESSAGES
        LC_CTYPE
        LOGONSERVER
        NEWWHMUPDATE
        NOTIFY_SOCKET
        NUMBER_OF_PROCESSORS
        OPENSSL_NO_DEFAULT_ZLIB
        OS
        PATH
        PATHEXT
        PROCESSOR_ARCHITECTURE
        PROCESSOR_IDENTIFIER
        PROCESSOR_LEVEL
        PROCESSOR_REVISION
        PROGRAMFILES
        PROMPT
        PYTHONIOENCODING
        SERVER_SOFTWARE
        SESSIONNAME
        SKIP_DEFERRAL_CHECK
        SSH_CLIENT
        SYSTEMDRIVE
        SYSTEMROOT
        TEMP
        TERM
        TMP
        UPDATENOW_NO_RETRY
        UPDATENOW_PRESERVE_FAILED_FILES
        USERDOMAIN
        USERNAME
        USERPROFILE
        WINDIR
    >;

    $SAFE_ENV_VARS =~ tr<\n >< >s;
    $SAFE_ENV_VARS =~ s<\A\s+><>;
}



{
    no warnings 'once';
    *cleanenv = *clean_env;
}

sub clean_env {
    my %OPTS = @_;

    my %SAFE_ENV_VARS = map { $_ => undef } split( m{ }, $SAFE_ENV_VARS );

    if ( defined $OPTS{'keep'} && ref $OPTS{'keep'} eq 'ARRAY' ) {
        @SAFE_ENV_VARS{ @{ $OPTS{'keep'} } } = undef;
    }

    if ( defined $OPTS{'delete'} && ref $OPTS{'delete'} eq 'ARRAY' ) {
        delete @SAFE_ENV_VARS{ @{ $OPTS{'delete'} } };
    }

    delete @ENV{ grep { !exists $SAFE_ENV_VARS{$_} } keys %ENV };
    if ( $OPTS{'http_purge'} ) {
        delete @ENV{ 'SERVER_SOFTWARE', 'DOCUMENT_ROOT' };
    }

    return;
}

sub get_safe_env_vars {
    return $SAFE_ENV_VARS;
}

sub get_safe_path {
    return '/usr/local/jdk/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/X11R6/bin:/root/bin:/opt/bin';
}

sub set_safe_path {
    return ( $ENV{'PATH'} = get_safe_path() );
}

1;

} # --- END Cpanel/Env.pm


{ # --- BEGIN Cpanel/FHUtils/OS.pm
package Cpanel::FHUtils::OS;


use strict;
use warnings;


my $fileno;

sub is_os_filehandle {
    local $@;
    $fileno = eval { fileno $_[0] };
    return ( defined $fileno ) && ( $fileno != -1 );
}

1;

} # --- END Cpanel/FHUtils/OS.pm


{ # --- BEGIN Cpanel/FHUtils/Blocking.pm
package Cpanel::FHUtils::Blocking;


use strict;
use warnings;

# use Cpanel::Fcntl::Constants ();
# use Cpanel::Autodie          qw(fcntl);
INIT { Cpanel::Autodie->import(qw{fcntl}); }

sub set_non_blocking {
    return Cpanel::Autodie::fcntl( $_[0], $Cpanel::Fcntl::Constants::F_SETFL, _get_fl_flags( $_[0] ) | $Cpanel::Fcntl::Constants::O_NONBLOCK ) && 1;
}

sub set_blocking {
    return Cpanel::Autodie::fcntl( $_[0], $Cpanel::Fcntl::Constants::F_SETFL, _get_fl_flags( $_[0] ) & ~$Cpanel::Fcntl::Constants::O_NONBLOCK ) && 1;
}

sub is_set_to_block {
    return !( _get_fl_flags( $_[0] ) & $Cpanel::Fcntl::Constants::O_NONBLOCK ) ? 1 : 0;
}

sub _get_fl_flags {

    return int Cpanel::Autodie::fcntl( $_[0], $Cpanel::Fcntl::Constants::F_GETFL, 0 );
}

1;

} # --- END Cpanel/FHUtils/Blocking.pm


{ # --- BEGIN Cpanel/IO/Flush.pm
package Cpanel::IO::Flush;


use strict;
use warnings;


use constant {
    _EAGAIN => 11,
    _EINTR  => 4,
};

# use Cpanel::Exception ();
use IO::SigGuard      ();


sub write_all {    ##no critic qw( RequireArgUnpacking )
    my ( $fh, $timeout ) = @_;    # $_[2] = payload

    local ( $!, $^E );

    my $offset = 0;

    {
        my $this_time = IO::SigGuard::syswrite( $fh, $_[2], length( $_[2] ), $offset );
        if ($this_time) {
            $offset += $this_time;
        }
        elsif ( $! == _EAGAIN() ) {
            _wait_until_ready( $fh, $timeout );
        }
        else {
            die Cpanel::Exception::create( 'IO::WriteError', [ error => $!, length => length( $_[2] ) - $offset ] );
        }

        redo if $offset < length( $_[2] );
    }

    return;
}

sub _wait_until_ready {
    my ( $fh, $timeout ) = @_;

    my $win;
    vec( $win, fileno($fh), 1 ) = 1;

    my $ready = select( undef, my $wout = $win, undef, $timeout );

    if ( $ready == -1 ) {
        redo if $! == _EINTR();
        die Cpanel::Exception::create( 'IO::SelectError', [ error => $! ] );
    }
    elsif ( !$ready ) {

        die Cpanel::Exception::create_raw( 'Timeout', 'write timeout!' );
    }

    return;
}

1;

} # --- END Cpanel/IO/Flush.pm


{ # --- BEGIN Cpanel/ReadMultipleFH.pm
package Cpanel::ReadMultipleFH;


use strict;
use warnings;

# use Cpanel::FHUtils::Blocking  ();
# use Cpanel::FHUtils::OS        ();
# use Cpanel::IO::Flush          ();
# use Cpanel::LoadFile::ReadFast ();

my $CHUNK_SIZE = 2 << 16;

my $DEFAULT_TIMEOUT      = 600;    #10 minutes
my $DEFAULT_READ_TIMEOUT = 0;

sub new {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $class, %opts ) = @_;

    my %fh_buffer;
    my %output;

    my @fhs = @{ $opts{'filehandles'} };

    my $read_input  = '';
    my $read_output = '';
    my %fhmap;

    my %is_os_filehandle;

    for my $fh_buf_ar (@fhs) {
        if ( UNIVERSAL::isa( $fh_buf_ar, 'GLOB' ) ) {
            $fh_buf_ar = [$fh_buf_ar];
        }
        elsif ( !UNIVERSAL::isa( $fh_buf_ar, 'ARRAY' ) ) {
            die 'items in “filehandles” must be either a filehandle or ARRAY';
        }

        my $fh = $fh_buf_ar->[0];

        Cpanel::FHUtils::Blocking::set_non_blocking($fh);

        $fhmap{ fileno($fh) } = $fh;
        vec( $read_input, fileno($fh), 1 ) = 1;

        if ( defined $fh_buf_ar->[1] && UNIVERSAL::isa( $fh_buf_ar->[1], 'SCALAR' ) ) {
            $fh_buffer{$fh} = $fh_buf_ar->[1];
        }
        else {
            my $buf = q{};
            $fh_buffer{$fh} = \$buf;

            if ( defined $fh_buf_ar->[1] && UNIVERSAL::isa( $fh_buf_ar->[1], 'GLOB' ) ) {
                $output{$fh} = $fh_buf_ar->[1];

                $is_os_filehandle{$fh} = Cpanel::FHUtils::OS::is_os_filehandle( $fh_buf_ar->[1] );
            }
            elsif ( defined $fh_buf_ar->[1] ) {
                die '2nd value in “filehandles” array member must be undef, SCALAR, or GLOB!';
            }
        }
    }

    my $finished;

    my $self = {
        _fh_buffer => \%fh_buffer,
        _finished  => 0,
    };

    bless $self, $class;

    my ( $nfound, $select_time_left, $select_timeout );

    my $overall_timeout = defined $opts{'timeout'}      ? $opts{'timeout'}      : $DEFAULT_TIMEOUT;
    my $read_timeout    = defined $opts{'read_timeout'} ? $opts{'read_timeout'} : $DEFAULT_READ_TIMEOUT;

    my $has_overall_timeout = $overall_timeout ? 1 : 0;

    my $overall_time_left = $overall_timeout || undef;

  READ_LOOP:
    while (
        !$finished &&                                          # has not finished
        ( !$has_overall_timeout || $overall_time_left > 0 )    # has not reached overall timeout
    ) {
        $select_timeout = _get_shortest_timeout( $overall_time_left, $read_timeout );

        ( $nfound, $select_time_left ) = select( $read_output = $read_input, undef, undef, $select_timeout );

        if ( !$nfound ) {

            $self->{'_timed_out'} = ( $select_timeout == $read_timeout ) ? $read_timeout : $overall_timeout;
            last;
        }
        elsif ( $nfound != -1 ) {    # case 47309: If we get -1 it probably means we got interrupted by a signal
            for my $fileno ( grep { vec( $read_output, $_, 1 ) } keys %fhmap ) {
                my $fh = $fhmap{$fileno};

                Cpanel::LoadFile::ReadFast::read_fast( $fh, ${ $fh_buffer{$fh} }, $CHUNK_SIZE, length ${ $fh_buffer{$fh} } ) or do {
                    delete $fhmap{$fileno};

                    $finished = !( scalar keys %fhmap );

                    last READ_LOOP if $finished;

                    vec( $read_input, $fileno, 1 ) = 0;

                    next;
                };

                if ( $output{$fh} ) {
                    my $payload_sr = \substr( ${ $fh_buffer{$fh} }, 0, length ${ $fh_buffer{$fh} }, q<> );

                    if ( $is_os_filehandle{$fh} ) {

                        Cpanel::IO::Flush::write_all( $output{$fh}, $read_timeout, $$payload_sr );
                    }
                    else {

                        print { $output{$fh} } $$payload_sr;
                    }
                }
            }
        }

        $overall_time_left -= ( $select_timeout - $select_time_left ) if $has_overall_timeout;
    }

    delete $fh_buffer{$_} for keys %output;

    %fhmap = ();

    $self->{'_finished'} = $finished;
    if ( !$finished && defined $overall_time_left && $overall_time_left <= 0 ) {

        $self->{'_timed_out'} = $overall_timeout;
    }

    return $self;
}

sub _get_shortest_timeout {
    my ( $overall_time_left, $read_timeout ) = @_;

    return undef if ( !$overall_time_left && !$read_timeout );

    return $read_timeout if !defined $overall_time_left;

    return ( !$read_timeout || $overall_time_left <= $read_timeout )
      ?

      $overall_time_left
      :

      $read_timeout;
}

sub get_buffer {
    return $_[0]->{'_fh_buffer'}{ $_[1] };
}

sub did_finish {
    return $_[0]->{'_finished'} ? 1 : 0;
}

sub timed_out {
    return defined $_[0]->{'_timed_out'} ? $_[0]->{'_timed_out'} : 0;
}

1;

} # --- END Cpanel/ReadMultipleFH.pm


{ # --- BEGIN Cpanel/ForkAsync.pm
package Cpanel::ForkAsync;


use strict;
use warnings;

# use Cpanel::Exception ();

my $DEFAULT_ERROR_CODE = 127;    #EKEYEXPIRED

our $quiet   = 0;
our $no_warn = 0;


sub do_in_child {
    my ( $code, @args ) = @_;

    local ( $!, $^E );
    my $pid = fork();

    die Cpanel::Exception::create( 'IO::ForkError', [ error => $! ] ) if !defined $pid;

    if ( !$pid ) {
        local $@;

        if ( !eval { $code->(@args); 1 } ) {
            my $err    = $@;
            my $io_err = 0 + $!;
            _print($err) unless $quiet;
            exit( $io_err || $DEFAULT_ERROR_CODE );
        }

        exit 0;
    }

    return $pid;
}


sub do_in_child_quiet {
    my ( $code, @args ) = @_;
    local $quiet = 1;
    return do_in_child( $code, @args );
}


sub _print {
    my ($msg) = @_;

    warn $msg unless $no_warn;
    print STDERR $msg;

    return;
}

1;

} # --- END Cpanel/ForkAsync.pm


{ # --- BEGIN Cpanel/SafeRun/Object.pm
package Cpanel::SafeRun::Object;


use cPstrict;

# use Cpanel::ChildErrorStringifier();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::ChildErrorStringifier); }

BEGIN {
    eval { require Proc::FastSpawn; };
}

use IO::SigGuard ();

# use Cpanel::Env                ();
# use Cpanel::Exception          ();
# use Cpanel::FHUtils::Autoflush ();
# use Cpanel::FHUtils::OS        ();
# use Cpanel::ReadMultipleFH     ();
# use Cpanel::LoadModule         ();
# use Cpanel::LocaleString       ();

use constant _ENOENT => 2;

my $CHUNK_SIZE = 2 << 16;

my $DEFAULT_TIMEOUT      = 3600;    # 1 hour
my $DEFAULT_READ_TIMEOUT = 0;

our $SAFEKILL_TIMEOUT = 1;


my @_allowed_env_vars_cache;

sub new {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $class, %OPTS ) = @_;

    die "No “program”!" if !length $OPTS{'program'};

    if ( !defined $OPTS{'timeout'} ) {
        $OPTS{'timeout'} = $DEFAULT_TIMEOUT;
    }

    if ( !defined $OPTS{'read_timeout'} ) {
        $OPTS{'read_timeout'} = $DEFAULT_READ_TIMEOUT;
    }

    if ( $OPTS{'program'} =~ tr{><*?[]`$()|;&#$\\\r\n\t }{} && !-e $OPTS{'program'} ) {
        die Cpanel::Exception::create( 'InvalidParameter', 'A value of “[_1]” is invalid for “[_2]” as it does not permit the following characters: “[_3]”', [ $OPTS{'program'}, 'program', '><*?[]`$()|;&#$\\\\\r\\n\\t' ] );
    }

    my $args_ar = $OPTS{'args'} || [];
    die "“args” must be an arrayref" if defined $args_ar && ref $args_ar ne 'ARRAY';

    die "Undefined value given as argument! (@$args_ar)" if grep { !defined } @$args_ar;

    my $pump_stdin_filehandle_into_child;

    my ( %parent_read_fh, %child_write_fh );

    my $merge_output_yn = $OPTS{'stdout'} && $OPTS{'stderr'} && ( $OPTS{'stdout'} eq $OPTS{'stderr'} );

    local $!;

    for my $handle_name (qw(stdout stderr)) {
        my $custom_fh = $OPTS{$handle_name} && UNIVERSAL::isa( $OPTS{$handle_name}, 'GLOB' ) && $OPTS{$handle_name};

        my $dupe_filehandle_will_work = $custom_fh && !tied(*$custom_fh) && ( fileno($custom_fh) > -1 );

        if ( !$custom_fh && $OPTS{$handle_name} ) {
            die "“$handle_name” must be a filehandle or undef, not $OPTS{$handle_name}";
        }

        if ($dupe_filehandle_will_work) {

            if ( fileno($custom_fh) < 3 ) {
                open my $copy, '>&', $custom_fh or die "dup($handle_name): $!";
                $child_write_fh{$handle_name} = $copy;
            }
            else {
                $child_write_fh{$handle_name} = $custom_fh;
            }
        }

        elsif ( $merge_output_yn && $handle_name eq 'stderr' ) {
            $parent_read_fh{'stderr'} = $parent_read_fh{'stdout'};
            $child_write_fh{'stderr'} = $child_write_fh{'stdout'};
        }

        else {
            pipe $parent_read_fh{$handle_name}, $child_write_fh{$handle_name}    #
              or die "pipe() failed: $!";
        }
    }

    my ( $child_reads, $parent_writes );
    my $close_child_reads = 0;

    if ( !defined $OPTS{'stdin'} || !length $OPTS{'stdin'} ) {
        open $child_reads, '<', '/dev/null' or die "open(<, /dev/null) failed: $!";
        $close_child_reads = 1;
    }
    elsif ( UNIVERSAL::isa( $OPTS{'stdin'}, 'GLOB' ) ) {
        my $fileno = fileno $OPTS{'stdin'};

        if ( !defined $fileno || $fileno == -1 ) {
            $pump_stdin_filehandle_into_child = 1;
        }
        else {
            $child_reads = $OPTS{'stdin'};
        }
    }

    if ( !$child_reads ) {
        $close_child_reads = 1;
        pipe( $child_reads, $parent_writes ) or die "pipe() failed: $!";
    }

    my $self = bless {
        _program => $OPTS{'program'},
        _args    => $OPTS{'args'} || [],
    }, $class;

    local $SIG{'CHLD'} = 'DEFAULT';

    my $exec_failed_message = "exec($OPTS{'program'}) failed:";
    my $used_fastspawn      = 0;
    if (
        $INC{'Proc/FastSpawn.pm'}                                   # may not be available yet due to upcp.static or updatenow.static
        && !$OPTS{'before_exec'}
        && !$Cpanel::AccessIds::ReducedPrivileges::PRIVS_REDUCED    # PPI NO PARSE - We not ever be set if its not loaded
    ) {
        $used_fastspawn = 1;
        my @env;

        if ( !$OPTS{'keep_env'} ) {
            if ( !@_allowed_env_vars_cache ) {
                @_allowed_env_vars_cache = ( split( m{ }, Cpanel::Env::get_safe_env_vars() ) );
            }
            @env = map { exists $ENV{$_} ? ( $_ . '=' . ( $ENV{$_} // '' ) ) : () } @_allowed_env_vars_cache;
        }
        my $user    = $OPTS{'user'};
        my $homedir = $OPTS{'homedir'};
        if ( !$user || !$homedir ) {
            my ( $pw_user, $pw_homedir ) = ( getpwuid $> )[ 0, 7 ];
            $user    ||= $pw_user;
            $homedir ||= $pw_homedir;
        }
        die "Invalid EUID: $>" if !$user || !$homedir;

        push @env, "HOME=$homedir",    "USER=$user";                                  # need to always be set since we start clean and don't have before_exec
        push @env, "TMP=$homedir/tmp", "TEMP=$homedir/tmp" if !defined $ENV{'TMP'};

        $self->{'_child_pid'} = Proc::FastSpawn::spawn_open3(
            fileno($child_reads),                                                            # stdin
            defined $child_write_fh{'stdout'} ? fileno( $child_write_fh{'stdout'} ) : -1,    # stdout
            defined $child_write_fh{'stderr'} ? fileno( $child_write_fh{'stderr'} ) : -1,    # stderr
            $OPTS{'program'},                                                                # program
            [ $OPTS{'program'}, @$args_ar ],                                                 # args
            $OPTS{'keep_env'} ? () : \@env                                                   # env
        );
    }
    else {
        require Cpanel::ForkAsync;
        $self->{'_child_pid'} = Cpanel::ForkAsync::do_in_child(
            sub {
                $SIG{'__DIE__'} = 'DEFAULT';    ## no critic qw(Variables::RequireLocalizedPunctuationVars) -- will never be unset

                if ( $parent_read_fh{'stdout'} ) {
                    close $parent_read_fh{'stdout'} or die "child close parent stdout failed: $!";
                }

                if ( $parent_read_fh{'stderr'} && !$merge_output_yn ) {
                    close $parent_read_fh{'stderr'} or die "child close parent stderr failed: $!";
                }

                if ($parent_writes) {
                    close $parent_writes or die "close() failed: $!";
                }

                open( *STDIN, '<&=' . fileno $child_reads ) or die "open(STDIN) failed: $!";    ##no critic qw(ProhibitTwoArgOpen)

                my $fileno_stdout = fileno \*STDOUT;
                if ( $fileno_stdout != fileno( $child_write_fh{'stdout'} ) ) {

                    if ( $fileno_stdout != 1 ) {
                        close *STDOUT            or die "close(STDOUT) failed: $!";
                        open( *STDOUT, '>>&=1' ) or die "open(STDOUT, '>>&=1') failed: $!";    ##no critic qw(ProhibitTwoArgOpen)
                    }

                    open( *STDOUT, '>>&=' . fileno $child_write_fh{'stdout'} ) or die "open(STDOUT) failed: $!";    ##no critic qw(ProhibitTwoArgOpen)
                }

                my $fileno_stderr = fileno \*STDERR;
                if ( $fileno_stderr != fileno( $child_write_fh{'stderr'} ) ) {

                    if ( $fileno_stderr != 2 ) {
                        close *STDERR            or die "close(STDOUT) failed: $!";
                        open( *STDERR, '>>&=2' ) or die "open(STDERR, '>>&=2') failed: $!";    ##no critic qw(ProhibitTwoArgOpen)
                    }

                    open( *STDERR, '>>&=' . fileno $child_write_fh{'stderr'} ) or die "open(STDERR) failed: $!";    ##no critic qw(ProhibitTwoArgOpen)
                }

                if ( !$OPTS{'keep_env'} ) {
                    Cpanel::Env::clean_env();
                }

                if ($Cpanel::AccessIds::ReducedPrivileges::PRIVS_REDUCED) {    # PPI NO PARSE --  can't be reduced if the module isn't loaded
                    my $target_euid = "$>";
                    my $target_egid = ( split( m{ }, "$)" ) )[0];
                    Cpanel::AccessIds::ReducedPrivileges::_restore_privileges( 0, 0 );    # PPI NO PARSE -- we will never get here if ReducedPrivileges wasn't loaded
                    Cpanel::LoadModule::load_perl_module('Cpanel::Sys::Setsid::Fast') if !$INC{'Cpanel/Sys/Setsid/Fast.pm'};
                    Cpanel::Sys::Setsid::Fast::fast_setsid();
                    Cpanel::LoadModule::load_perl_module('Cpanel::AccessIds::SetUids') if !$INC{'Cpanel/AccessIds/SetUids.pm'};
                    Cpanel::AccessIds::SetUids::setuids( $target_euid, $target_egid );
                }

                if ( $OPTS{'before_exec'} ) {
                    $OPTS{'before_exec'}->();
                }

                my $user    = $OPTS{'user'};
                my $homedir = $OPTS{'homedir'};
                if ( !$user || !$homedir ) {
                    Cpanel::LoadModule::load_perl_module('Cpanel::PwCache') if !$INC{'Cpanel/PwCache.pm'};
                    my ( $pw_user, $pw_homedir ) = ( Cpanel::PwCache::getpwuid_noshadow($>) )[ 0, 7 ];
                    $user    ||= $pw_user;
                    $homedir ||= $pw_homedir;
                }
                die "Invalid EUID: $>" if !$user || !$homedir;

                $ENV{'HOME'} = $homedir       if !defined $ENV{'HOME'};    # always cleared by clean_env, but may be reset in before_exec
                $ENV{'USER'} = $user          if !defined $ENV{'USER'};    # always cleared by clean_env, but may be reset in before_exec
                $ENV{'TMP'}  = "$homedir/tmp" if !defined $ENV{'TMP'};
                $ENV{'TEMP'} = "$homedir/tmp" if !defined $ENV{'TEMP'};

                exec( $OPTS{'program'}, @$args_ar ) or die "$exec_failed_message $!";
            }
        );
    }

    if ( $OPTS{'after_fork'} ) {
        $OPTS{'after_fork'}->( $self->{'_child_pid'} );
    }

    if ($close_child_reads) {    #only close it if we opened it
        close $child_reads or die "close() failed: $!";
    }

    if ( $parent_read_fh{'stdout'} ) {
        close $child_write_fh{'stdout'} or die "close() failed: $!";
    }

    if ( !$merge_output_yn && $parent_read_fh{'stderr'} ) {
        close $child_write_fh{'stderr'} or die "close() failed: $!";
    }

    if ($parent_writes) {
        if ( ref $OPTS{'stdin'} eq 'CODE' ) {

            $OPTS{'stdin'}->($parent_writes);
        }
        else {

            local $SIG{'PIPE'} = 'IGNORE';
            Cpanel::FHUtils::Autoflush::enable($parent_writes);

            if ($pump_stdin_filehandle_into_child) {
                my $buffer;

                my $is_os_stdin = Cpanel::FHUtils::OS::is_os_filehandle( $OPTS{'stdin'} );

                local $!;

                if ($is_os_stdin) {
                    while ( IO::SigGuard::sysread( $OPTS{'stdin'}, $buffer, $CHUNK_SIZE ) ) {
                        $self->_write_buffer_to_fh( $buffer, $parent_writes );
                    }
                }
                else {
                    while ( read $OPTS{'stdin'}, $buffer, $CHUNK_SIZE ) {
                        $self->_write_buffer_to_fh( $buffer, $parent_writes );
                    }
                }

                if ($!) {
                    die Cpanel::Exception::create( 'IO::ReadError', 'The system failed to read up to [format_bytes,_1] from the filehandle that contains standard input for the process that is running the command “[_2]”. This failure happened because of an error: [_3]', [ $CHUNK_SIZE, "$OPTS{'program'} @$args_ar", "$!" ] );
                }
            }
            else {
                my $to_print_r = ( ref $OPTS{'stdin'} eq 'SCALAR' ) ? $OPTS{'stdin'} : \$OPTS{'stdin'};

                if ( length $$to_print_r ) {
                    $self->_write_buffer_to_fh( $$to_print_r, $parent_writes );
                }
            }
        }

        close $parent_writes or warn "close() failed: $!";
    }

    my $reader;
    my $err_obj;

    my @filehandles = map { $parent_read_fh{$_} ? [ $parent_read_fh{$_}, $OPTS{$_} ] : () } qw( stdout stderr );

    if (@filehandles) {
        local $@;
        eval {
            $reader = Cpanel::ReadMultipleFH->new(
                filehandles  => \@filehandles,
                timeout      => $OPTS{'timeout'},
                read_timeout => $OPTS{'read_timeout'},
            );
        };
        $err_obj = $@;
    }

    if ( $parent_read_fh{'stdout'} ) {
        close $parent_read_fh{'stdout'} or warn "parent close(stdout) failed: $!";
    }

    if ( $parent_read_fh{'stderr'} && !$merge_output_yn ) {
        close $parent_read_fh{'stderr'} or warn "parent close(stderr) failed: $!";
    }

    if ($err_obj) {
        $self->{'_CHILD_ERROR'} = $self->_safe_kill_child();
        die $err_obj;
    }
    elsif ($reader) {
        if ( !$reader->did_finish() ) {
            $self->{'_timed_out_after'} = $reader->timed_out();
            $self->{'_CHILD_ERROR'}     = $self->_safe_kill_child();
        }

        $self->{"_stdout"} = $parent_read_fh{stdout} && $reader->get_buffer( $parent_read_fh{stdout} );
        $self->{"_stderr"} = $parent_read_fh{stderr} && $reader->get_buffer( $parent_read_fh{stderr} );
    }

    if ( !defined $self->{'_CHILD_ERROR'} ) {

        local $?;

        waitpid( $self->{'_child_pid'}, 0 ) if defined $self->{'_child_pid'};
        $self->{'_CHILD_ERROR'} = $?;

    }

    if ( $used_fastspawn && $self->{'_CHILD_ERROR'} == 32512 ) {
        $self->{'_CHILD_ERROR'} = _ENOENT() << 8;
        $self->{'_exec_failed'} = 1;
        ${ $self->{'_stderr'} } .= "$exec_failed_message $!";

    }
    elsif ( !$used_fastspawn && $self->{'_stderr'} && $self->{'_CHILD_ERROR'} && ( $self->{'_CHILD_ERROR'} >> 8 ) == 2 && index( ${ $self->{'_stderr'} }, $exec_failed_message ) > -1 ) {
        $self->{'_exec_failed'} = 1;
    }

    return $self;
}

sub _write_buffer_to_fh ( $self, $buffer, $fh ) {
    while ( length $buffer ) {
        my $wrote = IO::SigGuard::syswrite( $fh, $buffer ) or die $self->_write_error( \$buffer, $! );
        substr( $buffer, 0, $wrote, q<> );
    }

    return;
}

sub new_or_die {
    my ( $class, @args ) = @_;
    return $class->new(@args)->die_if_error();
}

sub to_exception {
    my ($self) = @_;

    if ( $self->timed_out() ) {
        return Cpanel::Exception::create(
            'ProcessFailed::Timeout',
            [
                process_name => $self->program(),
                ( $self->child_pid() ? ( pid => $self->child_pid() ) : () ),
                timeout => $self->timed_out(),
                $self->_extra_error_args_for_die_if_error(),
            ],
        );
    }

    return $self->SUPER::to_exception();
}

sub _extra_error_args_for_die_if_error {
    my ($self) = @_;
    return (
        stdout => $self->{'_stdout'} ? $self->stdout() : '',
        stderr => $self->{'_stderr'} ? $self->stderr() : '',
    );
}

sub _safe_kill_child {
    my ($self) = @_;
    Cpanel::LoadModule::load_perl_module('Cpanel::Kill::Single');
    return 'Cpanel::Kill::Single'->can('safekill_single_pid')->( $self->{'_child_pid'}, $SAFEKILL_TIMEOUT );    # One second to die
}

sub stdout_r {
    if ( !$_[0]->{'_stdout'} ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Carp');
        die 'Cpanel::Carp'->can('safe_longmess')->("STDOUT output went to filehandle!");
    }

    return $_[0]->{'_stdout'};
}

sub _additional_phrases_for_autopsy {
    if ( $_[0]->timed_out() ) {
        return Cpanel::LocaleString->new( 'The system aborted the subprocess because it reached the timeout of [quant,_1,second,seconds].', $_[0]->timed_out() );
    }

    return;
}

sub stdout {
    return ${ $_[0]->stdout_r() };
}

sub stderr_r {
    if ( !$_[0]->{'_stderr'} ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Carp');
        die 'Cpanel::Carp'->can('safe_longmess')->("STDERR output went to filehandle!");
    }

    return $_[0]->{'_stderr'};
}

sub stderr {
    return ${ $_[0]->stderr_r() };
}

sub child_pid {
    return $_[0]->{'_child_pid'};
}

sub timed_out {
    return $_[0]->{'_timed_out_after'};
}

sub program {
    return $_[0]->{'_program'};
}

sub _program_with_args_str {
    my $args_ar = $_[0]->{'_args'};
    return $_[0]->{'_program'} . ( ( $args_ar && ref $args_ar && scalar @$args_ar ) ? " @$args_ar" : '' );
}


sub _ERROR_PHRASE {
    my ($self) = @_;

    return Cpanel::LocaleString->new( 'The “[_1]” command (process [_2]) reported error number [_3] when it ended.', $self->_program_with_args_str(), $self->{'_child_pid'}, $self->error_code() );
}

sub _SIGNAL_PHRASE {
    my ($self) = @_;

    return Cpanel::LocaleString->new( 'The “[_1]” command (process [_2]) ended prematurely because it received the “[_3]” ([_4]) signal.', $self->_program_with_args_str(), $self->{'_child_pid'}, $self->signal_name(), $self->signal_code() );
}


sub _write_error {
    my ( $self, $buffer_sr, $OS_ERROR ) = @_;

    my @cmd = ( $self->{'_program'}, @{ $self->{'_args'} } );

    return Cpanel::Exception::create( 'IO::WriteError', 'The system failed to send [format_bytes,_1] to the process that is running the command “[_2]” because of an error: [_3]', [ length($$buffer_sr), "@cmd", $OS_ERROR ], { length => length($$buffer_sr), error => $OS_ERROR } );
}



1;

} # --- END Cpanel/SafeRun/Object.pm


{ # --- BEGIN Cpanel/Rand/Get.pm
package Cpanel::Rand::Get;


use strict;

# use Cpanel::FHUtils::Blocking ();
# use Cpanel::FHUtils::Tiny     ();

our $random_source = '/dev/urandom';

our %entropy_pool;

our $getrandom_syscall_is_usable;
my $last_entropy_pool_owner = $$;

my %TR_CODE_CACHE_NUM_ACCEPTABLE;
my %TR_CODE_CACHE_BAD_CHARS;

my $DEFAULT_LENGTH = 10;

my @DEFAULT_CHARACTERS = (
    0 .. 9,
    'A' .. 'Z',
    'a' .. 'z',
    '_',
);

my $_default_want_chars_string;    # a cache

my $DEFAULT_PRELOAD_16TH = 200;

my $MAX_READ_ATTEMPTS = 50;

my $NUMBER_OF_ASCII_CHARS = 256;

my $_EINTR = 4;

my $_ENOSYS = 38;

my $SYS_GETRANDOM = 318;

my $GRND_NONBLOCK = 0x0001;

my $srand_initialized = '';    # Used by _assemble_random_data_collection_without_random_device()

sub getranddata {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $bytes_of_random_data_wanted, $my_chars_ar, $preloadcount ) = @_;

    use bytes;       #will go away when we leave this context

    my $pid = $$;
    if ( $last_entropy_pool_owner != $pid ) {
        %entropy_pool            = ();
        $last_entropy_pool_owner = $pid;
    }

    $preloadcount ||= $DEFAULT_PRELOAD_16TH;

    my $bytes_of_data_to_preload_into_entropy_pool = $preloadcount * 16;

    if ($bytes_of_random_data_wanted) {
        if ( $bytes_of_random_data_wanted =~ tr{0-9}{}c ) {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'InvalidParameter', '“[_1]” is not a valid number of bytes.', [$bytes_of_random_data_wanted] );
        }
    }
    else {
        $bytes_of_random_data_wanted = $DEFAULT_LENGTH;
    }

    my $number_of_acceptable_characters;
    my $want_chars;
    if ( !$my_chars_ar ) {
        $my_chars_ar = \@DEFAULT_CHARACTERS;
        $want_chars  = ( $_default_want_chars_string ||= join( '', @DEFAULT_CHARACTERS ) );
    }

    if ( !ref $my_chars_ar && $my_chars_ar eq 'binary' ) {
        $number_of_acceptable_characters = $NUMBER_OF_ASCII_CHARS;
        $want_chars                      = '';
    }
    else {
        $number_of_acceptable_characters = scalar @{$my_chars_ar};
        if ( $number_of_acceptable_characters < 1 || $number_of_acceptable_characters > $NUMBER_OF_ASCII_CHARS ) {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'InvalidParameter', 'The number of desired characters must be at least 1 and at most 256.' );
        }
        $want_chars ||= join( '', @{$my_chars_ar} );
    }
    $entropy_pool{$want_chars} ||= '';
    my $cur_entropy_pool_sr = \$entropy_pool{$want_chars};

    my ( $code_ref_to_remove_chars_above_upper_limit, $code_ref_to_translate_acceptable_chars ) = _generate_random_data_code_refs( $want_chars, $my_chars_ar );

    my ( $dummy, $failed_read_attempts, $rand_chars, $random_data_remaining, $entropy_pool_remaining );

    my $random_data_collected = '';

    my ( $rand_fh, $rand_fh_bitmask );

    my $random_source_is_usable = 1;

    while ( length($random_data_collected) < $bytes_of_random_data_wanted ) {

      READ_FROM_RANDOM_SOURCE:
        while (1) {

            $random_data_remaining = $bytes_of_random_data_wanted - length($random_data_collected);

            last READ_FROM_RANDOM_SOURCE if !$random_source_is_usable;

            last READ_FROM_RANDOM_SOURCE if ( length($$cur_entropy_pool_sr) + length($random_data_collected) ) >= $bytes_of_random_data_wanted;

            $entropy_pool_remaining = $bytes_of_data_to_preload_into_entropy_pool - length($$cur_entropy_pool_sr);

            if ( !defined $getrandom_syscall_is_usable || $getrandom_syscall_is_usable > 0 ) {
                my $rand_count = $entropy_pool_remaining > $random_data_remaining ? $entropy_pool_remaining : $random_data_remaining;

                my $getrandom = _getrandom( $rand_count, \$rand_chars );

                if ( $getrandom == -1 ) {
                    if ( $! == $_EINTR ) {
                        next READ_FROM_RANDOM_SOURCE;
                    }
                    else {

                        $getrandom_syscall_is_usable = 0;

                        if ( $! != $_ENOSYS ) {
                            warn "getrandom() failed: $! - falling back to $random_source";
                        }
                    }
                }
                else {
                    $getrandom_syscall_is_usable = $getrandom ? 1 : 0;
                }
            }

            if ( !$getrandom_syscall_is_usable ) {
                if ( !$rand_fh ) {
                    if ( open $rand_fh, '<:stdio', $random_source ) {
                        $random_source_is_usable = -c $rand_fh ? 1 : 0;
                        if ($random_source_is_usable) {
                            Cpanel::FHUtils::Blocking::set_non_blocking($rand_fh);
                        }
                        else {
                            warn "“$random_source” is unusable because it is not a character device!";
                        }
                    }
                    else {
                        warn "Failed to open($random_source): $!";
                        $random_source_is_usable = 0;
                    }

                    last READ_FROM_RANDOM_SOURCE if !$random_source_is_usable;
                }

                sysread( $rand_fh, $rand_chars, $entropy_pool_remaining > $random_data_remaining ? $entropy_pool_remaining : $random_data_remaining ) or do {
                    if ( ++$failed_read_attempts > $MAX_READ_ATTEMPTS ) {
                        warn "Failed $MAX_READ_ATTEMPTS times to read from “$random_source”! Last failure was: $!";
                        $random_source_is_usable = 0;
                        last READ_FROM_RANDOM_SOURCE;
                    }

                    $rand_fh_bitmask ||= Cpanel::FHUtils::Tiny::to_bitmask($rand_fh);


                    select( $dummy = $rand_fh_bitmask, undef, undef, 0.0125 );

                    next READ_FROM_RANDOM_SOURCE;
                };
            }

            $code_ref_to_remove_chars_above_upper_limit->( \$rand_chars ) if $code_ref_to_remove_chars_above_upper_limit;

            $code_ref_to_translate_acceptable_chars->( \$rand_chars ) if $code_ref_to_translate_acceptable_chars;

            $$cur_entropy_pool_sr .= $rand_chars;
        }

        if ( length $$cur_entropy_pool_sr ) {
            $random_data_collected .= substr( $$cur_entropy_pool_sr, 0, $random_data_remaining, '' );    # just take what we need
        }
        else {
            warn "Using slow randomization logic!";

            $random_data_collected .= _assemble_random_data_collection_without_random_device(
                $number_of_acceptable_characters == $NUMBER_OF_ASCII_CHARS ? [ map { chr } 0 .. 255 ] : $my_chars_ar,

                $bytes_of_random_data_wanted - length($random_data_collected),
            );
        }
    }

    close($rand_fh) if ref $rand_fh;

    return substr( $random_data_collected, 0, $bytes_of_random_data_wanted );
}

sub _assemble_random_data_collection_without_random_device {
    my ( $my_chars_ar, $bytes_of_random_data_wanted ) = @_;


    my $process_fingerprint = "$>:$<:$):$$";
    unless ( $srand_initialized eq $process_fingerprint ) {
        $srand_initialized = $process_fingerprint;
        srand();
    }

    my $num_chars = @$my_chars_ar;

    my $random_data_collected = q<>;
    $random_data_collected .= $my_chars_ar->[ rand $num_chars ] for ( 1 .. $bytes_of_random_data_wanted );

    return $random_data_collected;
}

sub clear_pool {
    %entropy_pool = ();
    return;
}

sub _generate_random_data_code_refs {
    my ( $want_chars, $my_chars_ar ) = @_;

    if ( !ref $my_chars_ar ) {

        return ();
    }

    my ( $code_ref_to_remove_chars_above_upper_limit, $code_ref_to_translate_acceptable_chars );


    my $number_of_acceptable_characters = scalar @$my_chars_ar;
    my ( $last_good_value_hex, $last_good_value );
    my $first_bad_value = $NUMBER_OF_ASCII_CHARS - ( $NUMBER_OF_ASCII_CHARS % $number_of_acceptable_characters );
    if ( $first_bad_value != $NUMBER_OF_ASCII_CHARS ) {

        my $first_bad_value_hex = sprintf( '%02x', $first_bad_value );
        $last_good_value                            = $first_bad_value - 1;
        $last_good_value_hex                        = sprintf( '%02x', $last_good_value );
        $code_ref_to_remove_chars_above_upper_limit = $TR_CODE_CACHE_BAD_CHARS{$first_bad_value_hex} ||= eval 'sub { ${$_[0]} =~ tr/\x' . $first_bad_value_hex . '-\xff//d; }';    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
    }
    else {
        $last_good_value_hex = 'ff';
        $last_good_value     = 255;
    }

    $code_ref_to_translate_acceptable_chars = $TR_CODE_CACHE_NUM_ACCEPTABLE{$want_chars} ||= eval 'sub { ${$_[0]} =~ tr/\x{0}-\x{' . $last_good_value_hex . '}/' . join( '', map { quotemeta( $my_chars_ar->[ $_ % $number_of_acceptable_characters ] ) } ( 0 .. $last_good_value ) ) . '/; }';    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)

    return ( $code_ref_to_remove_chars_above_upper_limit, $code_ref_to_translate_acceptable_chars );

}

sub _getrandom {
    my ( $rand_count, $rand_chars_sr ) = @_;
    return syscall( 0 + $SYS_GETRANDOM, ( $$rand_chars_sr = "\0" x $rand_count ), 0 + $rand_count, 0 + $GRND_NONBLOCK );
}
1;

} # --- END Cpanel/Rand/Get.pm


{ # --- BEGIN Cpanel/Rand.pm
package Cpanel::Rand;


use strict;
use warnings;

# use Cpanel::Exception        ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::Hash             ();
# use Cpanel::SV               ();

my $MAX_TMPFILE_CREATE_ATTEMPTS = 50;

use constant WRONLY_CREAT_EXCL => $Cpanel::Fcntl::Constants::O_WRONLY | $Cpanel::Fcntl::Constants::O_CREAT | $Cpanel::Fcntl::Constants::O_EXCL;

our ( $DO_OPEN, $SKIP_OPEN, $TYPE_FILE, $TYPE_DIR ) = ( 0, 1, 0, 1 );

sub getranddata {
    require Cpanel::Rand::Get;
    goto \&Cpanel::Rand::Get::getranddata;
}

sub gettmpfile {
    return get_tmp_file_by_name('/tmp/cpanel.TMP');
}

sub gettmpdir {
    return get_tmp_dir_by_name('/tmp/cpanel.TMP');
}

sub api2_getranddata {
    my %CFG = @_;
    require Cpanel::Rand::Get;
    return { 'random' => Cpanel::Rand::Get::getranddata( $CFG{'length'} || 16 ) };
}

our %API = (
    getranddata => { allow_demo => 1 },
);

sub api2 {
    my ($func) = @_;
    return { %{ $API{$func} } } if $API{$func};
    return;
}

sub get_tmp_dir_by_name {
    my $templatefile = shift;
    my $suffix       = shift || '.work';
    return get_tmp_file_by_name( $templatefile, $suffix, $TYPE_DIR, $DO_OPEN );
}

sub get_tmp_file_by_name {
    my $templatefile = shift;
    my $suffix       = shift || '.work';
    my $type         = shift || $TYPE_FILE;
    my $open         = shift || $DO_OPEN;
    if ( index( $suffix, '.' ) != 0 ) {
        substr( $suffix, 0, 0, '.' );
    }
    my $last_error;
    my $fh;
    my $randlength = 8;
    my $maxlength  = 255 - $randlength - 1;
    my $root       = $templatefile . $suffix;
    my (@path)     = split( m{/+}, $root );
    my $file       = substr( pop @path, -$maxlength, $maxlength );
    my $tmpfile    = join( '/', @path, $file ) . '.' . _rand_trailer($randlength);
    Cpanel::SV::untaint($tmpfile);

    local $!;
    my $attempts = 0;
    {
        my $old = umask(0);    # Cpanel::Umask was too slow here when creating many zone file
        while (
            ++$attempts < $MAX_TMPFILE_CREATE_ATTEMPTS
            && (
                ( $open != $DO_OPEN && -e $tmpfile )
                || (
                    $open == $DO_OPEN
                    ? (
                        $type == $TYPE_DIR
                        ? !mkdir( $tmpfile, 0700 )
                        : !sysopen( $fh, $tmpfile, WRONLY_CREAT_EXCL, 0600 )
                    )
                    : 0
                )
            )
        ) {
            $last_error = $!;
            my (@path)  = split( m{/+}, $root );
            my $file    = substr( pop @path, -$maxlength, $maxlength );
            my $tmpfile = join( '/', @path, $file ) . '.' . _rand_trailer($randlength);
            Cpanel::SV::untaint($tmpfile);
        }
        umask($old);
    }

    if ( $attempts == $MAX_TMPFILE_CREATE_ATTEMPTS ) {
        die Cpanel::Exception::create( 'TempFileCreateError', [ path => $tmpfile, error => $last_error ] );
    }

    return ( $tmpfile, $fh ) if wantarray && $type == $TYPE_FILE;
    return $tmpfile;    # file will close when $fh leaves context
}

sub _rand_trailer {
    return substr( sprintf( '%08x', Cpanel::Hash::get_fastest_hash( join( '-', substr( rand, 2 ), $$, time ) ) ), 0, $_[0] );
}

1;

} # --- END Cpanel/Rand.pm


{ # --- BEGIN Cpanel/TempFile.pm
package Cpanel::TempFile;



use strict;
use warnings;

# use Cpanel::Rand        ();
# use Cpanel::Debug       ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeDir::RM ();
# use Cpanel::Fcntl       ();
# use Cpanel::Debug       ();
# use Cpanel::Destruct    ();
use Cwd                 ();

my $DO_OPEN   = $Cpanel::Rand::DO_OPEN;
my $SKIP_OPEN = $Cpanel::Rand::SKIP_OPEN;
my $TYPE_DIR  = $Cpanel::Rand::TYPE_DIR;
my $TYPE_FILE = $Cpanel::Rand::TYPE_FILE;

our $DEFAULT_PATH = '/var/tmp';
my $DEFAULT_SUFFIX = 'tmp';

sub get_safe_tmpfile {
    return get_safe_tmp_file_or_dir( $Cpanel::Rand::TYPE_FILE, @_ );
}

sub get_safe_tmpdir {
    return get_safe_tmp_file_or_dir( $Cpanel::Rand::TYPE_DIR, @_ );
}

sub get_safe_tmp_file_or_dir {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $file_or_dir = shift;
    my $homedir     = $Cpanel::homedir;
    if ( !$homedir ) {
        require Cpanel::PwCache;
        $homedir = Cpanel::PwCache::gethomedir();
    }
    if ( !-d $homedir . '/tmp' ) {
        if ( !mkdir( $homedir . '/tmp', 0755 ) ) {
            Cpanel::Debug::log_warn("Failed to create $homedir/tmp");
            return;
        }
    }
    return Cpanel::Rand::get_tmp_file_by_name( $homedir . '/tmp/Cpanel::TempFile', '.tmp', $file_or_dir, @_ );    # audit case 46806 ok
}

sub new {
    my ( $what, $opts ) = @_;
    my $class = ref $what || $what;
    my $self  = {};
    bless $self, $class;

    $self->set_opts($opts);
    $self->{"needunlink_$$"} = [];

    return $self;
}

sub dir {
    my ( $self, @other_args ) = @_;
    return $self->_dir_or_file( $TYPE_DIR, @other_args );
}

sub file {
    my ( $self, @other_args ) = @_;
    return $self->_dir_or_file( $TYPE_FILE, @other_args );
}

sub file_in_dir {
    my ( $self, @other_args ) = @_;
    my $dir  = $self->dir(@other_args);
    my $opts = pop @other_args || {};
    return $self->_dir_or_file( $TYPE_FILE, @other_args, { %$opts, 'path' => $dir } );
}

sub file_readwrite {


    my ( $self, @other_args ) = @_;

    if ( !wantarray ) {
        $self->_warn("Calling file_readwrite() in scalar context makes no sense, since you will only get back a filename but no filehandle");
        return;
    }

    my ( $fname, $fh ) = $self->file(@other_args);

    close $fh;
    undef $fh;

    my $mode = Cpanel::Fcntl::or_flags(qw( O_RDWR O_EXCL ));

    sysopen( $fh, $fname, $mode, 0600 )
      or $self->_die("Could not sysopen $fname: $!\n");

    return ( $fname, $fh );
}

sub filename_only {
    my $self = shift;

    my $die_msg = "You must not call filename_only() to get a unique temp file name not backed by an actual";
    $die_msg .= " file on disk. The subroutine is not implemented and with good reason; see case 48668";
    $self->_die($die_msg);

}

sub set_opts {
    my ( $self, $opts ) = @_;

    my @valid_keys = qw( suffix prefix path debug mkdirs );
    my $err;
    foreach my $key ( sort keys %{$opts} ) {
        next if grep { $key eq $_ } @valid_keys;
        $self->_warn("Disallowing invalid opt '$key' passed in opts hash");
        $err = 1;
    }

    return if $err;

    $opts //= {};
    $self->{'opts'} //= {};

    my @debug;
    foreach my $k ( sort keys %{$opts} ) {
        my $v = $opts->{$k} // '';
        $self->{'opts'}->{$k} = $v;
        push @debug, "Set opt $k = $v";
    }

    $Cpanel::Debug::level = $self->{'opts'}->{'debug'} ? 1 : 0;
    $self->_debug($_) for (@debug);
    return 1;
}

sub _get_opt {
    my ( $self, $name, $opts ) = @_;

    return $opts->{$name} || $self->{'opts'}->{$name};
}

sub _dir_or_file {    # Main workhorse of this module
    my ( $self, $dir_or_file, @other_args ) = @_;

    my $opts     = {};
    my $last_arg = $other_args[$#other_args];
    if ( ref $last_arg eq "HASH" ) {
        pop @other_args;
        $opts = $last_arg;
    }

    my $open = $DO_OPEN;

    my $prefix = $self->_get_opt( 'prefix', $opts ) || "";
    if ( length $prefix ) {


        if ( $prefix =~ m{/} ) {
#             $self->_warn("You must not specify a prefix containing '/' ; instead, use the 'path' option for that purpose");
INIT { the->import(qw{path' option for that purpose}); }
            return;
        }

        if ( $prefix =~ m{[^-.\w]} ) {
            $self->_warn("Bad prefix '$prefix', prefix must contain only '.', '-', and \\w characters");
            return;
        }
    }

    my $caller = _callername();
    substr $prefix, 0, 0, substr( $caller, length $caller > 40 ? -40 : 0 ) . '__' if $caller;
    substr $prefix, 0, 0, "$$" . '.';

    my $path   = $self->_get_opt( 'path',   $opts ) || $DEFAULT_PATH;
    my $suffix = $self->_get_opt( 'suffix', $opts ) || $DEFAULT_SUFFIX;

    substr $prefix, 0, 0, "$path/";

    if ( !-e $path ) {
        if ( $self->_get_opt( 'mkdirs', $opts ) ) {
            my @created;
            if ( Cpanel::SafeDir::MK::safemkdir( $path, undef, undef, \@created ) && -e $path ) {
                $self->_info("Have created path '$path'");
                push @{ $self->{"needunlink_$$"} }, @created;
            }
            else {
                $self->_warn("Non-existent path '$path', could not create");
            }
        }
        else {
            $self->_warn("Non-existent path '$path', will not create, because mkdirs option is not set");
        }
    }

    my ( $fname, $fh ) = Cpanel::Rand::get_tmp_file_by_name( $prefix, $suffix, $dir_or_file, $open );
    undef $fname if defined $fname && $fname eq "/dev/null";

    $fname = $self->_make_suffix_rightmost( $fname, $suffix );

    push @{ $self->{"needunlink_$$"} }, $fname if defined $fname;
    return ( $fname, $fh ) if wantarray;
    return $fname;
}

sub _make_suffix_rightmost {


    my ( $self, $fname, $suffix ) = @_;
    if ( defined $fname ) {
        my $orig = $fname;
        if ( $fname =~ s{ ^ (.*) [.] ($suffix) [.] (.*) }{ "$1.$3.$2" }ex ) {
            if ( -e $orig ) {
                if ( !rename $orig, $fname ) {
                    $self->_warn("Could not rename '$orig' to '$fname' to shift suffix ('$suffix') to rightmost position, leaving as is");
                    $fname = $orig;
                }
            }
        }
        else {
            print STDERR "Regular expression substitution failed to adjust '$orig' to shift suffix ('$suffix') to rightmost position\n";
        }
    }
    return $fname;
}

sub _info {
    my ( $self, $msg ) = @_;
    return Cpanel::Debug::log_info($msg);
}

sub _warn {
    my ( $self, $msg ) = @_;
    return Cpanel::Debug::log_warn($msg);
}

sub _debug {
    my ( $self, $msg ) = @_;
    return unless $Cpanel::Debug::level;
    return Cpanel::Debug::log_debug($msg);
}

sub _die {
    my ( $self, $msg ) = @_;
    return Cpanel::Debug::log_die($msg);
}

{
    my $caller;

    sub _callername {
        return $caller if defined $caller;
        ( $caller = $0 ) =~ s{\W}{_}g;
        $caller = uc $caller;
        return $caller;
    }

    BEGIN { _callername() }
}

sub cleanup {
    my $self = shift;

    return unless defined $self->{"needunlink_$$"} && ref $self->{"needunlink_$$"};

    my @needunlink = reverse @{ $self->{"needunlink_$$"} };

    for my $file (@needunlink) {
        if ( ( $file =~ tr/\/// ) < 1 ) {
            $self->_warn("Not removed: $file, as a temp file cannot be at top level");    # ok to not remove because invalid
        }
        elsif ( $file eq '/dev/null' ) {                                                  # at this writing we need this, unfortunately
            $self->_warn("Not removed: /dev/null, I flatly refuse to remove it");
        }
        else {
            my $file_or_dir = -d $file ? "directory" : "file";
            my $existed     = -e _;
            if ( !$existed ) {
                $self->_debug("Not removing $file_or_dir $file, does not exist; perhaps already removed in a recursive dir cleanup, or by some other removal agent");
            }
            else {
                if ( $file_or_dir eq 'directory' ) {

                    local $?;
                    my $old_dir  = Cwd::abs_path( Cwd::getcwd($file) );
                    my $abs_path = Cwd::abs_path($file);
                    if ( $old_dir eq $abs_path ) {
                        $self->_warn("The cwd is temporary directory “$file”. The cwd was changed to “$file/..” in order to remove the temporary directory.");
                        chdir("$file/..") or die "Failed to chdir('$file/..'): $!";
                    }
                    Cpanel::SafeDir::RM::safermdir($file);
                }
                else {
                    unlink($file);
                }

                my $intro = $existed && !-e $file ? "R" : "Not r";
                $self->_debug("${intro}emoved: $file_or_dir $file");
            }
        }
    }

    @{ $self->{"needunlink_$$"} } = ();
    return;
}

sub needunlink {
    my ( $self, $item ) = @_;
    push @{ $self->{"needunlink_$$"} }, $item;
    return;
}

sub DESTROY {
    my $self = shift;

    return if Cpanel::Destruct::in_dangerous_global_destruction();

    $self->cleanup();

    return;
}

1;

} # --- END Cpanel/TempFile.pm


{ # --- BEGIN Cpanel/Crypt/GPG/Import.pm
package Cpanel::Crypt::GPG::Import;



use strict;

# use Cpanel::Crypt::GPG::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Crypt::GPG::Base); }

# use Cpanel::SafeRun::Object ();
# use Cpanel::TempFile        ();


sub new {
    my ( $class, $opts_hr ) = @_;

    $opts_hr = {} if !( $opts_hr && 'HASH' eq ref $opts_hr );

    my $self = eval { $class->SUPER::new($opts_hr) };

    if ( !$self ) {
        return wantarray ? ( undef, "Failed to find the GnuPG binary." ) : undef;
    }

    my $tmp = ( $opts_hr->{tmp} ) ? $opts_hr->{tmp} : Cpanel::TempFile->new();
    $self->{tmp} = $tmp;

    return $self;
}


sub verify {
    my ( $self, %args ) = @_;
    my ( $sig, @files );

    if ( $args{sig} ) {
        $sig = $args{sig};
    }
    elsif ( $args{sig_data} ) {
        $sig = $self->_write_data_to_temp_file( $args{sig_data}, $self->{tmp} );
    }
    else {
        return wantarray ? ( undef, "Arguments 'sig' or 'sig_data' must be provided." ) : undef;
    }


    if ( $args{files} ) {
        @files = ( ref( $args{files} ) eq 'ARRAY' ) ? @{ $args{files} } : ( $args{files} );
    }
    elsif ( defined( $args{files_data} ) ) {
        for my $file ( ( ref( $args{files_data} ) eq 'ARRAY' ) ? @{ $args{files_data} } : ( $args{files_data} ) ) {
            push @files, $self->_write_data_to_temp_file( $file, $self->{tmp} );
        }
    }
    else {
        return wantarray ? ( undef, "Arguments 'files' or 'files_data' must be provided." ) : undef;
    }

    my @args = (
        '--logger-fd', '1',
        '--status-fd', '1',
        $self->{homedir} ? ( '--homedir' => $self->{homedir} ) : (),
        '--verify', $sig,
        @files,
    );

    my $run = Cpanel::SafeRun::Object->new(
        program => $self->{bin},
        args    => \@args,
        timeout => _gpg_timeout(),
    );

    if ( !$run ) {
        return wantarray ? ( undef, "Failed to invoke gpg." ) : undef;
    }

    my $sig_data = undef;
    my $status   = "Failed to validate signature due to some unknown error.";

    my %notes;
    my $curnote;


    for my $l ( split /\n/, $run->stdout() ) {
        if ( $l =~ /^\[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]+)$/ ) {
            $sig_data = {
                id          => substr( $1, -16 ),
                create_time => $3,
                expire_time => $4,
            };

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


    if ($sig_data) {
        $sig_data->{notations} = \%notes;
    }

    return wantarray ? ( $sig_data, "$status (@files)" ) : $sig_data;
}


sub add_pub_key {
    my ( $self, %args ) = @_;

    if ( !$args{key} ) {
        return wantarray ? ( undef, "No key provided." ) : undef;
    }

    my @args = (
        '--logger-fd', '1',
        '--status-fd', '1',
        $self->{homedir} ? ( '--homedir' => $self->{homedir} ) : (),
        '--import'
    );

    my $run = Cpanel::SafeRun::Object->new(
        program => $self->{bin},
        args    => \@args,
        stdin   => $args{key},
        timeout => _gpg_timeout(),
    );

    if ( !$run ) {
        return wantarray ? ( undef, "Failed to invoke gpg." ) : undef;
    }

    my @r = ( undef, "Failed to import key." );

    for my $l ( split /\n/, $run->stdout() ) {
        if ( $l =~ /^\[GNUPG:\] IMPORT_OK \d+ ([A-F0-9]+)$/ ) {
            my $id = substr( $1, -16 );
            @r = ( $id, "Successfully imported key." );
        }
    }

    return wantarray ? @r : shift @r;
}


sub get_key_id {
    my ( $self, %args ) = @_;

    if ( !$args{key} ) {
        return wantarray ? ( undef, "No key provided." ) : undef;
    }

    my @r = ( undef, "Failed to parse key id." );

    if ( my $id = $self->add_pub_key(%args) ) {
        @r = ( $id, "Successfully parsed key id." );
    }

    return wantarray ? @r : shift @r;
}


sub _write_data_to_temp_file {
    my ( $self, $data )   = @_;
    my ( $name, $handle ) = $self->{tmp}->file();

    binmode $handle;    # We may be opening binary OpenPGP data.
    print {$handle} $data;
    close($handle);

    return $name;
}


sub _gpg_timeout {
    return 60;
}

1;

} # --- END Cpanel/Crypt/GPG/Import.pm


{ # --- BEGIN Cpanel/Crypt/GPG/Import/Temp.pm
package Cpanel::Crypt::GPG::Import::Temp;



use strict;
use warnings;

# use Cpanel::Crypt::GPG::Import();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Crypt::GPG::Import); }

# use Cpanel::TempFile ();


sub new {
    my ( $class, $opts_hr ) = @_;

    $opts_hr = {} if !( $opts_hr && 'HASH' eq ref $opts_hr );

    my $tmp  = Cpanel::TempFile->new;
    my $path = $tmp->dir();

    $opts_hr->{tmp}     = $tmp;
    $opts_hr->{homedir} = $path;

    my $self = $class->SUPER::new($opts_hr);

    return $self;
}

1;

} # --- END Cpanel/Crypt/GPG/Import/Temp.pm


{ # --- BEGIN Cpanel/YAML.pm
package Cpanel::YAML;


use strict;

use YAML::Syck         ();
# use Cpanel::YAML::Syck ();

BEGIN {
    *Dump     = *YAML::Syck::Dump;
    *Load     = *YAML::Syck::Load;
    *SafeDump = *YAML::Syck::Dump;
    *DumpFile = *YAML::Syck::DumpFile;
}

our $MAX_LOAD_LENGTH      = 65535;
our $MAX_PRIV_LOAD_LENGTH = 4194304;    # four megs

sub _is_openhandle {
    my $h = shift;

    return 1 if ( ref($h) eq 'GLOB' );
    return 1 if ( ref( \$h ) eq 'GLOB' );
    return 1 if ( ref($h) =~ m/^IO::/ );

    return;
}

sub SafeLoadFile {    # only allow a small bit of data to be loaded
    LoadFile( $_[0], $MAX_LOAD_LENGTH );
}

sub LoadFile {
    my $file = shift;
    my $max  = shift;

    my $str_r;
    if ( _is_openhandle($file) ) {
        if ($max) {
            my $togo   = $max;
            my $buffer = '';
            my $bytes_read;
            while ( $bytes_read = read( $file, $buffer, $togo, length $buffer ) && length $buffer < $max ) {
                $togo -= $bytes_read;
            }
            $str_r = \$buffer;
        }
        else {
            $str_r = \do { local $/; <$file> };
        }
    }
    else {
        if ( !-e $file || -z $file ) {
            require Carp;
            Carp::croak("'$file' is non-existent or empty");
        }
        open( my $fh, '<', $file ) or do {
            require Carp;
            Carp::croak("Cannot read from $file: $!");
        };
        $str_r = \do { local $/; <$fh> };
    }

    return YAML::Syck::LoadYAML($$str_r);
}

1;

} # --- END Cpanel/YAML.pm


{ # --- BEGIN Cpanel/CachedDataStore.pm
package Cpanel::CachedDataStore;


use strict;


use Try::Tiny;

# use Cpanel::AdminBin::Serializer ();
# use Cpanel::LoadFile::ReadFast   ();
# use Cpanel::Fcntl::Constants     ();
# use Cpanel::Debug                ();
# use Cpanel::Exception            ();

use Time::HiRes ();

use constant {
    WRONLY_CREAT_EXCL => ( $Cpanel::Fcntl::Constants::O_WRONLY | $Cpanel::Fcntl::Constants::O_CREAT | $Cpanel::Fcntl::Constants::O_EXCL ),
    _EEXIST           => 17,
};

our $LOCK = 1;    #const
our $LAST_WRITE_CACHE_SERIALIZATION_ERROR;

our $MAX_CACHE_ELEMENTS = 32768 + 1;

my $MAX_CACHE_OBJECT_SIZE = 1024 * 512;    # do not cache objects larger than 512k

my $_iterations_since_last_cache_cleanup = 0;

my %DATASTORE_CACHE;

*_time  = *Time::HiRes::time;
*_utime = *Time::HiRes::utime;
*_stat  = *Time::HiRes::stat;

sub store_ref {
    return savedatastore( $_[0], { 'data' => $_[1], ( ref $_[2] ? %{ $_[2] } : () ) } );
}

sub fetch_ref {
    my ( $file, $is_array ) = @_;

    my $fetch_ref = loaddatastore($file);

    my $data_type = ref $fetch_ref->{'data'};
    my $data = $data_type ? top_level_clone( $fetch_ref->{'data'} ) : undef;
    $data_type ||= 'UNDEF';

    if ( $is_array && $data_type ne 'ARRAY' ) {
        return [];
    }
    elsif ( !$is_array && $data_type ne 'HASH' ) {
        return {};
    }

    return $data;
}

sub load_ref {
    my ( $file, $into_ref, $opts_ref ) = @_;
    my $fetch_ref = loaddatastore( $file, 0, $into_ref, $opts_ref );
    return $fetch_ref->{'data'};
}

sub savedatastore {
    my ( $file, $opts ) = @_;

    require Cpanel::SafeFile;
    my $use_cache_file = !defined $opts->{'cache_file'} || $opts->{'cache_file'};

    if ( !exists $opts->{'data'} || !defined $opts->{'data'} ) {
        Cpanel::Debug::log_warn("Expected data to be saved. \$opts->{'data'} was empty. $file has been left untouched.");
        if ( $opts->{'fh'} && $opts->{'safefile_lock'} ) {
            Cpanel::SafeFile::safeclose( $opts->{'fh'}, $opts->{'safefile_lock'} );
        }
        elsif ( $opts->{'fh'} ) {
            close( $opts->{'fh'} );
        }
        return;
    }

    my $use_memory_cache = !defined $opts->{'enable_memory_cache'} || $opts->{'enable_memory_cache'};

    my $original_file = $file;

    substr( $file, -5, 5, '' ) if rindex( $file, '.yaml' ) == length($file) - 5;

    require Cpanel::YAML;
    my $output = Cpanel::YAML::Dump( $opts->{'data'} );

    my $perms = exists $opts->{'mode'} ? $opts->{'mode'} & 00777 : undef;

    if ( !defined($perms) ) {
        if ( $opts->{'fh'} ) {
            die "Filehandle already closed!" if !defined fileno $opts->{'fh'};
            $perms = ( stat $opts->{'fh'} )[2] & 0777;
        }
        elsif ( -e $original_file ) {
            $perms = ( stat _ )[2] & 0777;
        }
        else {
            $perms = 0644;
        }
    }

    require Cpanel::FileUtils::Write;
    my $fh = Cpanel::FileUtils::Write::overwrite( $original_file, $output, $perms );
    @{$opts}{ 'inode', 'size', 'mtime' } = ( _stat($fh) )[ 1, 7, 9 ];
    close $fh;

    if ($use_cache_file) {

        _write_cache_file( "$file.cache", $opts->{'data'}, $perms );

        _utime( $opts->{'mtime'}, $opts->{'mtime'}, "$file.cache" );

    }

    if ($use_memory_cache) {

        if ( $opts->{'size'} < $MAX_CACHE_OBJECT_SIZE ) {
            _cleanup_cache() if ++$_iterations_since_last_cache_cleanup > $MAX_CACHE_ELEMENTS && scalar keys %DATASTORE_CACHE >= $MAX_CACHE_ELEMENTS;
            @{ $DATASTORE_CACHE{$original_file} }{ 'cache', 'inode', 'mtime', 'size' } = @{$opts}{ 'data', 'inode', 'mtime', 'size' };
        }
        else {
            delete $DATASTORE_CACHE{$original_file};
        }
    }

    my $ok;
    if ( $opts->{'fh'} ) {
        if ( $opts->{'safefile_lock'} ) {
            $ok = Cpanel::SafeFile::safeclose( $opts->{'fh'}, $opts->{'safefile_lock'} );
        }
        else {
            $ok = close( $opts->{'fh'} );
        }
    }
    else {
        $ok = 1;
    }

    return $ok;
}

sub loaddatastore {    ## no critic(Subroutines::ProhibitExcessComplexity)  -- Refactoring this function is a project, not a bug fix
    my ( $datastore_file, $lock_required, $copy_data_ref, $opts ) = @_;

    my ( $loaded_data, $filesys_inode, $filesys_perms, $filesys_mtime, $filesys_size, $filesys_cache_mtime, $cache, $datastore_cache_file );

    if ( !$datastore_file ) {
        Cpanel::Debug::log_warn('No datastore file specified');
        return;
    }

    my $use_memory_cache = !defined $opts->{'enable_memory_cache'} || $opts->{'enable_memory_cache'};

    my $custom_perms = exists $opts->{'mode'} ? $opts->{'mode'} & 00777 : undef;

    my $lock_datastore = 0;    # default is to not lock
    if ( defined $lock_required ) {
        $lock_datastore = $lock_required ? 1 : 0;
    }
    elsif ( $opts->{'donotlock'} ) {
        $lock_datastore = 0;
    }

    if ( !$lock_datastore ) {
        ( $filesys_inode, $filesys_perms, $filesys_size, $filesys_mtime ) = ( _stat($datastore_file) )[ 1, 2, 7, 9 ];
        if ( !$filesys_mtime ) {

            return;
        }

        if (
            $use_memory_cache
            && exists $DATASTORE_CACHE{$datastore_file}    # no-auto vivify
            && $DATASTORE_CACHE{$datastore_file}->{'mtime'}
            && $DATASTORE_CACHE{$datastore_file}->{'size'}
            && $filesys_mtime == $DATASTORE_CACHE{$datastore_file}->{'mtime'}
            && $filesys_size == $DATASTORE_CACHE{$datastore_file}->{'size'}
            && $filesys_inode == $DATASTORE_CACHE{$datastore_file}->{'inode'}
        ) {
            if ($copy_data_ref) {
                _copy_ref_data( $DATASTORE_CACHE{$datastore_file}->{'cache'}, $copy_data_ref, $datastore_file );
            }

            if ( defined $custom_perms ) {
                if ( ( $filesys_perms & 0777 ) != $custom_perms ) {
                    chmod $custom_perms, $datastore_file or do {
                        warn sprintf( "chmod(0%03o, $datastore_file): $!", $custom_perms );
                    };
                }
            }

            return bless {
                'size'  => $DATASTORE_CACHE{$datastore_file}->{'size'},
                'inode' => $DATASTORE_CACHE{$datastore_file}->{'inode'},
                'mtime' => $DATASTORE_CACHE{$datastore_file}->{'mtime'},
                'data'  => $DATASTORE_CACHE{$datastore_file}->{'cache'},
                'file'  => $datastore_file,
              },
              __PACKAGE__;
        }
    }

    $datastore_cache_file = $datastore_file;


    if ( rindex( $datastore_cache_file, '.yaml' ) == length($datastore_cache_file) - 5 ) {
        substr( $datastore_cache_file, -5, 5, '.cache' );
    }
    else {
        $datastore_cache_file .= '.cache';
    }

    if ( !$lock_datastore ) {
        ( $filesys_cache_mtime, $cache ) = _load_datastore_cache_from_disk( $datastore_cache_file, $filesys_mtime, $datastore_file, $filesys_size, $filesys_inode );
        if ( $filesys_cache_mtime && $filesys_cache_mtime >= $filesys_mtime && ref $cache ) {
            $loaded_data = $cache;
        }

        if ( $copy_data_ref && $loaded_data ) {
            _copy_ref_data( $loaded_data, $copy_data_ref, $datastore_file );
        }

        if ($loaded_data) {
            if ( defined $custom_perms && ( $filesys_perms & 00777 ) != $custom_perms ) {
                chmod( $custom_perms, $datastore_file ) or do {
                    warn( sprintf "chmod(0%o, %s) failed: %s", $custom_perms, $datastore_file, $! );
                };
            }

            if ($use_memory_cache) {
                if ( $filesys_size < $MAX_CACHE_OBJECT_SIZE ) {
                    _cleanup_cache() if ++$_iterations_since_last_cache_cleanup > $MAX_CACHE_ELEMENTS && scalar keys %DATASTORE_CACHE >= $MAX_CACHE_ELEMENTS;
                    @{ $DATASTORE_CACHE{$datastore_file} }{ 'inode', 'size', 'mtime', 'cache' } = ( $filesys_inode, $filesys_size, $filesys_mtime, $loaded_data );
                }
                else {
                    delete $DATASTORE_CACHE{$datastore_file};
                }
            }

            return bless {
                'inode' => $filesys_inode,
                'size'  => $filesys_size,
                'mtime' => $filesys_mtime,
                'data'  => $loaded_data,
                'file'  => $datastore_file,
              },
              __PACKAGE__;

        }
    }


    my $datastore_not_writable;
    my $data_fh;
    my $perms = defined $custom_perms ? $custom_perms : 0644;    #0644 is the default
    my $orig_umask;
    if ( defined $perms ) {
        $orig_umask = umask( $perms ^ 07777 );
    }

    my $created_datastore_file = 0;

    if ( !-e $datastore_file ) {
        if ( sysopen my $f, $datastore_file, WRONLY_CREAT_EXCL, $perms ) {
            $created_datastore_file = 1;

        }
        elsif ( $! != _EEXIST() ) {
            warn "Failed to create “$datastore_file” (EUID=$>): $!";

        }

    }

    my $rlock;
    my $lock_failed;
    if ( !$lock_datastore ) {

        open( $data_fh, '<', $datastore_file ) or do {
            Cpanel::Debug::log_warn("Unable open $datastore_file for reading: $!");


            undef $data_fh;
        };
        $datastore_not_writable = 1;
    }
    else {
        my $open_mode = -w $datastore_file ? '+<' : '<';
        require Cpanel::SafeFile;
        $rlock = Cpanel::SafeFile::safeopen( $data_fh, $open_mode, $datastore_file );
        my $last_error = $@ || $!;
        $lock_failed = !$rlock || 1 == $rlock;

        if ($lock_failed) {
            Cpanel::Debug::log_warn("Unable get a lock on datastore $datastore_file: $last_error");


            undef $data_fh;
            $datastore_not_writable = 1;
        }
    }
    umask($orig_umask) if defined $orig_umask;

    if ( !$created_datastore_file ) {
        my $data_fh_perms = ( _stat( $data_fh // $datastore_file ) )[2] || 0600;

        if ( defined $custom_perms && ( $data_fh_perms & 00777 ) != $custom_perms ) {
            chmod( $custom_perms, $data_fh ? $data_fh : $datastore_file );
            $data_fh_perms = ( _stat( $data_fh // $datastore_file ) )[2] || 0600;
        }

        if ( $data_fh && fileno $data_fh ) {
            if ($lock_datastore) {
                ( $filesys_inode, $filesys_perms, $filesys_size, $filesys_mtime ) = ( _stat($data_fh) )[ 1, 2, 7, 9 ];
                ( $filesys_cache_mtime, $cache ) = _load_datastore_cache_from_disk( $datastore_cache_file, $filesys_mtime, $datastore_file, $filesys_size, $filesys_inode );
            }
            if ( $filesys_cache_mtime && ref $cache ) {
                $loaded_data = $cache;
            }
            else {
                $loaded_data = _load_inner_data( $datastore_file, $data_fh );
                seek( $data_fh, 0, 0 );
            }
            if ( $copy_data_ref && $loaded_data ) {
                _copy_ref_data( $loaded_data, $copy_data_ref, $datastore_file );
            }
        }

        if ( !$lock_datastore || $datastore_not_writable ) {
            my @data_dir = split( /\/+/, $datastore_cache_file );
            pop @data_dir;
            my $datastore_cache_file_dir = join( '/', @data_dir );
            if ( $loaded_data && $filesys_mtime && ( !-e $datastore_cache_file || -w _ ) && ( _stat($datastore_cache_file_dir) )[4] == $> ) {
                _write_cache_file( $datastore_cache_file, $loaded_data, $data_fh_perms ) if !$filesys_cache_mtime;
                if ($use_memory_cache) {
                    if ( $filesys_size < $MAX_CACHE_OBJECT_SIZE ) {
                        _cleanup_cache() if ++$_iterations_since_last_cache_cleanup > $MAX_CACHE_ELEMENTS && scalar keys %DATASTORE_CACHE >= $MAX_CACHE_ELEMENTS;
                        @{ $DATASTORE_CACHE{$datastore_file} }{ 'cache', 'inode', 'mtime', 'size' } = ( $loaded_data, $filesys_inode, $filesys_mtime, $filesys_size );
                    }
                    else {
                        delete $DATASTORE_CACHE{$datastore_file};
                    }
                }
            }

        }
    }

    if ( !$lock_datastore || $datastore_not_writable ) {
        if ( !$lock_datastore ) {
            close($data_fh);
        }
        else {
            require Cpanel::SafeFile;
            Cpanel::SafeFile::safeclose( $data_fh, $rlock ) unless $lock_failed;
        }
        $data_fh                = undef;    # data_fh is closed at this point
        $datastore_not_writable = 1;        # if the datastore is closed, it isn't writable.
    }

    my %self = (
        'inode' => $filesys_inode,
        'size'  => $filesys_size,
        'mtime' => $filesys_mtime,
        'data'  => $loaded_data,
        'file'  => $datastore_file,
    );

    if ( !$datastore_not_writable ) {
        @self{ 'safefile_lock', 'fh' } = ( $rlock, $data_fh );
    }

    return bless \%self, __PACKAGE__;
}

sub _load_datastore_cache_from_disk {
    my ( $datastore_cache_file, $filesys_mtime, $datastore_file, $filesys_size, $filesys_inode ) = @_;
    my $loaded_data;
    if ( open( my $datastore_cache_fh, '<:stdio', $datastore_cache_file ) ) {
        my $filesys_cache_mtime = ( _stat($datastore_cache_fh) )[9];    # stat the file handle to prevent a race condition
        if ( $filesys_size && $filesys_mtime && $filesys_cache_mtime >= $filesys_mtime && $filesys_cache_mtime <= _time() ) {
            eval {
                local $SIG{'__DIE__'};     # Suppress spewage as we may be reading an invalid cache
                local $SIG{'__WARN__'};    # and since failure is ok to throw it away
                $loaded_data = Cpanel::AdminBin::Serializer::LoadFile($datastore_cache_fh);
            };
            my ( $filesys_inode_after_read, $filesys_size_after_read, $filesys_mtime_after_read ) = ( _stat($datastore_file) )[ 1, 7, 9 ];

            if (   $filesys_mtime_after_read == $filesys_mtime
                && $filesys_size_after_read == $filesys_size
                && $filesys_inode_after_read == $filesys_inode ) {
                return ( $filesys_cache_mtime, $loaded_data ) if ref $loaded_data;
            }
        }

    }
    elsif ( $! != _ENOENT() ) {    #ok if the file does not exist
        warn "Failed to open “$datastore_cache_file” for reading: $!";
    }

    return 0;
}

sub _write_cache_file {
    my ( $path, $data, $perms ) = @_;

    $LAST_WRITE_CACHE_SERIALIZATION_ERROR = undef;

    try {
        my $serialized;

        try {
            $serialized = Cpanel::AdminBin::Serializer::Dump($data);
        }
        catch {
            $LAST_WRITE_CACHE_SERIALIZATION_ERROR = Cpanel::Exception::get_string($_);
        };

        if ($serialized) {
            require Cpanel::FileUtils::Write;
            Cpanel::FileUtils::Write::overwrite(
                $path,
                $serialized,
                $perms,
            );
        }
    }
    catch {
        my $str = Cpanel::Exception::get_string($_);
        Cpanel::Debug::log_warn("Failed to write the cache file “$path” ($str); this file will not be saved.");
    };

    return;
}

sub file {
    return $_[0]->{'file'};
}

sub fh {
    return $_[0]->{'fh'};
}

sub mtime {
    return $_[0]->{'mtime'};
}

sub size {
    return $_[0]->{'size'};
}

sub clear_data {
    $_[0]->{'data'} = undef;
    return;
}

sub data {
    if ( defined $_[1] ) {
        $_[0]->{'data'} = $_[1];
        return 1;
    }
    return $_[0]->{'data'};
}

sub save {
    return savedatastore( $_[0]->{'file'}, $_[0] );
}

sub abort {
    return unlockdatastore( $_[0] );
}

sub unlockdatastore {
    my ($datastore) = @_;

    return 0 if !$datastore->{'fh'} || !$datastore->{'safefile_lock'};

    require Cpanel::SafeFile;
    return Cpanel::SafeFile::safeclose( $datastore->{'fh'}, $datastore->{'safefile_lock'} );
}

sub _copy_ref_data {
    my ( $src_ref, $dest_ref, $file ) = @_;

    if ( ref $src_ref eq 'HASH' ) {
        local $@;
        eval { %{$dest_ref} = %{$src_ref}; };


    }
    elsif ( ref $src_ref eq 'ARRAY' ) {
        local $@;
        eval { @{$dest_ref} = @{$src_ref}; };

    }
    else {
        if ($file) {
            Cpanel::Debug::log_warn("YAML in '$file' is not a hash or array reference");
        }
        else {
            Cpanel::Debug::log_warn('Asked to duplicate a reference that is not a hash or array');
        }
        $dest_ref = $src_ref;
    }
    return;
}

sub get_cache {
    return \%DATASTORE_CACHE;
}

sub clear_cache {
    %DATASTORE_CACHE = ();
    return;
}

sub clear_one_cache {
    my ($file) = @_;

    delete $DATASTORE_CACHE{$file};
    return;
}

sub verify {
    my ($file) = @_;

    my $fh;
    open( $fh, '<', $file ) or die "Failed to open $file: $!";

    my $data = _load_inner_data( $file, $fh );

    return ref $data ? 1 : 0;
}

sub _load_inner_data {
    my ( $name, $fh ) = @_;
    my $data = '';
    Cpanel::LoadFile::ReadFast::read_all_fast( $fh, $data );
    my $loaded_data;

    if ( length $data ) {
        local $@;
        eval {
            local $SIG{'__WARN__'};
            local $SIG{'__DIE__'};
            require Cpanel::YAML;
            $loaded_data = ( Cpanel::YAML::Load($data) )[0];
        };
    }

    $loaded_data = undef unless ref $loaded_data;
    return $loaded_data;
}

sub top_level_clone {
    my ($data) = @_;

    if ( ref $data eq 'HASH' ) {
        return { %{ $_[0] } };
    }
    elsif ( ref $data eq 'ARRAY' ) {
        return [ @{ $_[0] } ];
    }

    return $data;
}

sub _cleanup_cache {
    my @oldest_keys = sort { $DATASTORE_CACHE{$b}{'mtime'} <=> $DATASTORE_CACHE{$a}{'mtime'} } keys %DATASTORE_CACHE;
    splice( @oldest_keys, -1 * int( $MAX_CACHE_ELEMENTS / 2 ) );
    delete @DATASTORE_CACHE{@oldest_keys};
    $_iterations_since_last_cache_cleanup = 0;
    return 1;
}

sub _ENOENT { return 2; }
1;

} # --- END Cpanel/CachedDataStore.pm


{ # --- BEGIN Cpanel/CachedCommand/Utils.pm
package Cpanel::CachedCommand::Utils;


# use Cpanel::SV ();

my ( $cached_datastore_myuid, $cached_datastore_dir );

sub destroy {
    my %OPTS       = @_;
    my $cache_file = _get_datastore_filename( $OPTS{'name'}, ( $OPTS{'args'} ? @{ $OPTS{'args'} } : () ) );
    if ( -e $cache_file ) {
        return unlink $cache_file;
    }
    else {
        return 1;
    }
    return;
}

*get_datastore_filename = *_get_datastore_filename;

sub _get_datastore_filename {
    my ( $bin, @args ) = @_;

    my $file = join( '_', $bin, @args );
    $file =~ tr{/}{_};
    Cpanel::SV::untaint($file);

    my $datastore_dir = _get_datastore_dir($file);
    Cpanel::SV::untaint($datastore_dir);

    return $datastore_dir . '/' . $file;
}

sub _get_datastore_dir {
    my $file  = shift;
    my $myuid = $>;

    if ( defined $cached_datastore_dir && length $cached_datastore_dir > 1 && $myuid == $cached_datastore_myuid ) {
        my $homedir = Cpanel::PwCache::gethomedir();
        $cached_datastore_dir = "$homedir/$ENV{'TEAM_USER'}/.cpanel/datastore" if $ENV{'TEAM_USER'} && $file =~ /^AVAILABLE_APPLICATIONS_CACHE/;
        return $cached_datastore_dir;
    }

    require Cpanel::PwCache;
    $cached_datastore_dir = Cpanel::SV::untaint( Cpanel::PwCache::gethomedir() );
    $cached_datastore_dir .= "/$ENV{'TEAM_USER'}" if $ENV{'TEAM_USER'} && $file =~ /^AVAILABLE_APPLICATIONS_CACHE/;

    if ( !-e $cached_datastore_dir . '/.cpanel/datastore' && $cached_datastore_dir ne '/' ) {    # nobody's homedir is /
        require Cpanel::SafeDir::MK;
        Cpanel::SafeDir::MK::safemkdir( "$cached_datastore_dir/.cpanel/datastore", 0700 ) or warn "Failed to mkdir($cached_datastore_dir/.cpanel/datastore): $!";
    }

    $cached_datastore_myuid = $myuid;
    $cached_datastore_dir .= '/.cpanel/datastore';
    return $cached_datastore_dir;
}

sub invalidate_cache {
    my $ds_file = get_datastore_filename(@_);
    unlink $ds_file;
    return $ds_file;
}

sub clearcache {
    $cached_datastore_dir   = undef;
    $cached_datastore_myuid = undef;
    return;
}

1;

} # --- END Cpanel/CachedCommand/Utils.pm


{ # --- BEGIN Cpanel/PublicSuffix.pm
package Cpanel::PublicSuffix;


use strict;
use warnings;

# use IO::Socket::SSL::PublicSuffix();
our @ISA;
BEGIN { push @ISA, qw(IO::Socket::SSL::PublicSuffix); }

# use Cpanel::AdminBin::Serializer         ();
# use Cpanel::AdminBin::Serializer::FailOK ();
our $VERSION = '1.2';    # must not end in zero for compat

our $public_suffix_db;

BEGIN {
    if ( !$INC{'Mozilla/PublicSuffix.pm'} ) {
        $INC{'Mozilla/PublicSuffix.pm'}       = __FILE__;    ## no critic qw(Variables::RequireLocalizedPunctuationVars)
        *Mozilla::PublicSuffix::public_suffix = sub {
            __PACKAGE__->get_io_socket_ssl_publicsuffix_handle()->public_suffix(@_);
        };
    }
}

my %IS_SIMPLE_TLD = (
    com            => 1,
    net            => 1,
    org            => 1,
    info           => 1,
    cloud          => 1,
    arpa           => 1,
    'in-addr.arpa' => 1,
    'ip6.arpa'     => 1,
);

sub domain_isa_tld {
    my ($domain) = @_;

    return 1 if ( $domain =~ tr/.// ) == 0;

    return 1 if $IS_SIMPLE_TLD{$domain};

    return 1 if get_io_socket_ssl_publicsuffix_handle()->public_suffix($domain) eq $domain;

    return 0;
}

sub get_io_socket_ssl_publicsuffix_handle {
    return ( $public_suffix_db ||= bless {}, __PACKAGE__ );
}

sub public_suffix {
    $_[0]->_ensure_loaded();
    return $_[0]->SUPER::public_suffix( @_[ 1 .. $#_ ] );
}

sub _ensure_loaded {
    if ( !scalar keys %{ $_[0] } ) {

        require IO::Socket::SSL::PublicSuffix;

        local $@;
        warn if !eval {    # Try::Tiny will clobber $_[0]
            my $db = _load_cached_publicsuffix_db();
            @{ $_[0] }{ keys %$db } = values %$db;
            1;
        };

        if ( scalar keys %{ $_[0] } ) {
            return;
        }

        my $db = IO::Socket::SSL::PublicSuffix->default();

        die "Cold not load IO::Socket::SSL::PublicSuffix default database" if !$db;

        warn if !eval { _write_cached_publicsuffix_db($db); 1 };

        @{ $_[0] }{ keys %$db } = values %$db;
    }
    return;

}

sub _DATASTORE_FILE {
    require Cpanel::CachedCommand::Utils;
    return Cpanel::CachedCommand::Utils::get_datastore_filename( __PACKAGE__, 'default' );
}

sub _get_publicsuffix_size_mtime {
    if ( $INC{'IO/Socket/SSL/PublicSuffix.pm'} ) {
        return ( stat( $INC{'IO/Socket/SSL/PublicSuffix.pm'} ) )[ 7, 9 ];
    }
    foreach my $path (@INC) {
        my ( $size, $mtime ) = ( stat("$path/IO/Socket/SSL/PublicSuffix.pm") )[ 7, 9 ];
        return ( $size, $mtime ) if $size;
    }
    die "Cannot locate: IO/Socket/SSL/PublicSuffix.pm";
}

sub _load_cached_publicsuffix_db {
    my $datastore_file = _DATASTORE_FILE();
    if ( -e $datastore_file ) {
        my $datastore_mtime = ( stat(_) )[9];
        my ( $public_suffix_size, $public_suffix_mtime ) = _get_publicsuffix_size_mtime();
        return undef if !$public_suffix_size || !$public_suffix_mtime || $public_suffix_mtime > $datastore_mtime;
        my $cache = Cpanel::AdminBin::Serializer::FailOK::LoadFile($datastore_file);
        if ( ref $cache eq 'HASH' && $cache->{'VERSION'} && $cache->{'size'} && $cache->{'VERSION'} == $VERSION && $cache->{'size'} == $public_suffix_size ) {
            return $cache->{'data'};
        }
    }
    return undef;
}

sub _write_cached_publicsuffix_db {
    my ($db) = @_;

    my $datastore_file = _DATASTORE_FILE();

    my ( $public_suffix_size, $public_suffix_mtime ) = _get_publicsuffix_size_mtime();
    my $unblessed = { %{$db} };

    require Cpanel::FileUtils::Write;
    Cpanel::FileUtils::Write::overwrite( $datastore_file, Cpanel::AdminBin::Serializer::Dump( { 'VERSION' => $VERSION, 'size' => $public_suffix_size, 'data' => $unblessed } ), 0640 );

    return 1;
}

sub clear_cache {
    my $datastore_file = _DATASTORE_FILE();
    unlink $datastore_file;
    return;
}

1;

} # --- END Cpanel/PublicSuffix.pm


{ # --- BEGIN Cpanel/HTTP/Tiny/FastSSLVerify.pm
package Cpanel::HTTP::Tiny::FastSSLVerify;


use strict;
use warnings;

# use HTTP::Tiny();
our @ISA;
BEGIN { push @ISA, qw(HTTP::Tiny); }

# use Cpanel::PublicSuffix ();

my $orig_handle_connect = \&HTTP::Tiny::Handle::connect;

our $VERSION = '1.0';

use constant NO_VERIFY_TOUCHFILE_PATH => '/var/cpanel/no_verify_SSL';

sub new {
    my ( $class, %opts ) = @_;

    my $connect_timeout = delete $opts{'connect_timeout'};

    my $ssl_opts_hr = $opts{'SSL_options'};
    $ssl_opts_hr &&= {%$ssl_opts_hr};

    $ssl_opts_hr->{'SSL_verifycn_publicsuffix'} = Cpanel::PublicSuffix::get_io_socket_ssl_publicsuffix_handle();

    my $verify_ssl = 1;

    if ( -f NO_VERIFY_TOUCHFILE_PATH ) {
        $verify_ssl = 0;
    }

    my $self = $class->SUPER::new(
        'verify_SSL' => $verify_ssl,
        %opts,
        'SSL_options' => $ssl_opts_hr,
    );

    $self->{'connect_timeout'} = $connect_timeout if $connect_timeout;
    return $self;
}

sub request {
    my ( $self, @args ) = @_;

    no warnings 'redefine';
    local *HTTP::Tiny::Handle::connect = sub {
        my ( $connect_self, @args ) = @_;
        local $connect_self->{'timeout'} = $self->{'connect_timeout'};
        return $orig_handle_connect->( $connect_self, @args );
      }
      if ( $self->{'connect_timeout'} );
    use warnings 'redefine';

    return $self->SUPER::request(@args);

}

1;

} # --- END Cpanel/HTTP/Tiny/FastSSLVerify.pm


{ # --- BEGIN Cpanel/HTTP/Client/Response.pm
package Cpanel::HTTP::Client::Response;


use strict;
use warnings;


# use HTTP::Tiny::UA::Response();
our @ISA;
BEGIN { push @ISA, qw(HTTP::Tiny::UA::Response); }

sub new {
    my ( $class, $opts_hr, @extra ) = @_;

    my $self = $class->SUPER::new( $opts_hr, @extra );

    $self->{'_cp_redirects'} = $opts_hr->{'redirects'};

    return $self;
}

sub redirects {
    my ($self) = @_;

    return [ map { ( ref $self )->new($_) } @{ $self->{'_cp_redirects'} } ];
}

sub TO_JSON {
    my $json = { %{ $_[0] } };

    $json->{redirects} = delete $json->{_cp_redirects};

    return $json;
}

1;

} # --- END Cpanel/HTTP/Client/Response.pm


{ # --- BEGIN Cpanel/HTTP/Client.pm
package Cpanel::HTTP::Client;



use strict;

my %MODULE_PARAMS;

# use Cpanel::HTTP::Tiny::FastSSLVerify();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::HTTP::Tiny::FastSSLVerify); }

# use Cpanel::Exception              ();
# use Cpanel::HTTP::Client::Response ();

our $VERSION = '1.0';



sub new {
    my ( $class, @args ) = @_;

    my $self = $class->SUPER::new(@args);

    $MODULE_PARAMS{$self} = {};

    return $self;
}


sub die_on_http_error {
    my ($self) = @_;

    $MODULE_PARAMS{$self}{'die_on_http_error'} = 1;

    return $self;
}


sub return_on_http_error {
    my ($self) = @_;

    $MODULE_PARAMS{$self}{'die_on_http_error'} = 0;

    return $self;
}

sub request {
    my ( $self, $method, $url, $args_hr ) = @_;

    local $@;

    my $resp = $self->SUPER::request( $method, $url, $args_hr || () );

    my $resp_obj = Cpanel::HTTP::Client::Response->new($resp);

    if ( $resp_obj->status() == 599 ) {
        my $error = $resp_obj->content();

        chomp($error) if $error && !ref $error;
        die Cpanel::Exception::create(
            'HTTP::Network',
            [
                method    => $method,
                url       => $url,
                error     => $error,
                redirects => $resp_obj->redirects(),
            ]
        );
    }

    if ( $MODULE_PARAMS{$self}{'die_on_http_error'} && $resp->{'status'} >= 400 ) {
        die Cpanel::Exception::create(
            'HTTP::Server',
            [
                method       => $method,
                content_type => scalar( $resp_obj->header('Content-Type') ),
                ( map { ( $_ => $resp_obj->$_() ) } qw( content status reason url headers redirects ) ),
            ],
        );
    }

    return $resp_obj;
}


sub set_default_header {
    my ( $self, $header, $value ) = @_;
    $header =~ tr/[A-Z]/[a-z]/;
    $self->{'default_headers'}{$header} = $value;
    return 1;
}


sub delete_default_header {
    my ( $self, $header ) = @_;

    $header =~ tr/[A-Z]/[a-z]/;
    return delete $self->{'default_headers'}{$header};
}

sub DESTROY {
    my ($self) = @_;
    delete $MODULE_PARAMS{$self};

    $self->SUPER::DESTROY() if $self->can('SUPER::DESTROY');

    return;
}


1;

} # --- END Cpanel/HTTP/Client.pm


{ # --- BEGIN Cpanel/SecureDownload.pm
package Cpanel::SecureDownload;



use strict;
use warnings;



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

    my @methods = (
        [ 'Cpanel::HTTP::Client' => \&_try_with_http_client ],
        [ 'curl'                 => \&_try_with_curl ],
        [ 'wget'                 => \&_try_with_wget ]
    );

    my $all_errors;

    foreach my $method (@methods) {
        my ( $name, $sub ) = @{$method};

        local $@;
        my $contents = eval { $sub->( $url, %opts ); };
        return ( 1, $contents ) if !$@;

        my $error = "Failed to fetch using $name: $@";
        $all_errors .= $error . "\n";
    }

    return ( 0, $all_errors );
}


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

    die "Cpanel::HTTP::Client unavailable during initial install" if $ENV{'CPANEL_BASE_INSTALL'};

    require Cpanel::HTTP::Client;

    my $http = Cpanel::HTTP::Client->new()->die_on_http_error();
    $http->timeout( $opts{'timeout'} ) if exists $opts{'timeout'};

    my $content = $http->get($url)->content();

    return $content unless exists $opts{'output-file'};

    my $temp_file = $opts{'output-file'} . '.' . time . '.temp';

    open my $fh, '>', $temp_file
      or die "Unable to open $temp_file: $!";
    print {$fh} $content;
    close $fh;

    unlink $opts{'output-file'} if -e $opts{'output-file'};
    rename $temp_file, $opts{'output-file'};

    return 1;
}


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

    my $curl_bin = _find_curl_bin();
    die "Unable to find curl" unless $curl_bin;

    my @cmd_args = _build_curl_cmd_line( $url, %opts );

    return _execute_download_tool( $curl_bin, @cmd_args );
}


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

    my $wget_bin = _find_wget_bin();
    die "Unable to find wget" unless $wget_bin;

    my @cmd_args = _build_wget_cmd_line( $url, %opts );

    return _execute_download_tool( $wget_bin, @cmd_args );
}


sub _get_mozilla_ca_file {

    my $ca_file = eval {
        require    # Cpanel::Static OK - inside an eval
          Mozilla::CA;
        Mozilla::CA::SSL_ca_file();
    };
    return if $@;
    return unless -e $ca_file;
    return $ca_file;
}


sub _find_curl_bin {

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

    return undef;
}


sub _find_wget_bin {

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

    return undef;
}


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

    my @cmd_args;

    if ( exists $opts{'tries'} ) {
        push @cmd_args, '--retry';
        push @cmd_args, $opts{'tries'};
    }

    if ( exists $opts{'retry-delay'} ) {
        push @cmd_args, '--retry-delay';
        push @cmd_args, $opts{'retry-delay'};
    }

    if ( exists $opts{'timeout'} ) {
        push @cmd_args, '--max-time';
        push @cmd_args, $opts{'timeout'};
    }

    if ( exists $opts{'no-check-certificate'} && $opts{'no-check-certificate'} ) {
        push @cmd_args, '-k';
    }
    else {
        my $ca_file = _get_mozilla_ca_file();
        if ($ca_file) {
            push @cmd_args, "--cacert";
            push @cmd_args, $ca_file;
        }
    }

    push @cmd_args, '--silent';
    push @cmd_args, '-o';
    push @cmd_args, exists $opts{'output-file'} ? $opts{'output-file'} : '-';
    push @cmd_args, $url;

    return @cmd_args;
}


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

    my @cmd_args;

    push @cmd_args, '-nv'                                     if exists $opts{'not-verbose'};
    push @cmd_args, '--no-dns-cache'                          if exists $opts{'no-dns-cache'};
    push @cmd_args, '--tries=' . $opts{'tries'}               if exists $opts{'tries'};
    push @cmd_args, '--timeout=' . $opts{'timeout'}           if exists $opts{'timeout'};
    push @cmd_args, '--dns-timeout=' . $opts{'dns-timeout'}   if exists $opts{'dns-timeout'};
    push @cmd_args, '--read-timeout=' . $opts{'read-timeout'} if exists $opts{'read-timeout'};
    push @cmd_args, '--waitretry=' . $opts{'retry-delay'}     if exists $opts{'retry-delay'};
    push @cmd_args, '--retry-connrefused'                     if exists $opts{'retry-connrefused'};

    if ( exists $opts{'no-check-certificate'} && $opts{'no-check-certificate'} ) {
        push @cmd_args, '--no-check-certificate';
    }
    else {
        my $ca_file = _get_mozilla_ca_file();
        if ($ca_file) {
            push @cmd_args, "--ca-certificate=$ca_file";
        }
    }

    push @cmd_args, '-O';
    push @cmd_args, exists $opts{'output-file'} ? $opts{'output-file'} : '-';
    push @cmd_args, $url;

    return @cmd_args;
}


sub _execute_download_tool {
    my ( $bin, @cmd_args ) = @_;

    if ( _try_load_saferun_object() ) {
        return _run_with_saferun_object( $bin, @cmd_args );
    }
    elsif ( _try_load_ipc_open3() ) {
        return _run_with_ipc_open3( $bin, @cmd_args );
    }
    else {
        die "Unable to find a suitable method to fetch the URL\n";
    }

    return;
}


sub _try_load_saferun_object {
    eval { require Cpanel::SafeRun::Object; };
    return $@ ? 0 : 1;
}


sub _try_load_ipc_open3 {
    eval { require IPC::Open3; };
    return $@ ? 0 : 1;
}


sub _run_with_saferun_object {
    my ( $bin, @cmd_args ) = @_;

    my $run = Cpanel::SafeRun::Object->new(
        program => $bin,
        args    => \@cmd_args,
    );

    if ( !$run ) {
        die "Failed to invoke $bin binary.";
    }

    my $rc = $run->CHILD_ERROR() >> 8;

    if ( $rc != 0 ) {
        my $full_command = $bin . ' ' . join ' ', @cmd_args;
        my $stderr       = "Error encountered while running $full_command command: " . $run->stderr();
        die $stderr;
    }

    my $stdout = $run->stdout();

    return $stdout;
}


sub _run_with_ipc_open3 {
    my ( $bin, @cmd_args ) = @_;

    my ( $out_fh, $err_fh );
    my $pid = IPC::Open3::open3( undef, $out_fh, $err_fh, $bin, @cmd_args );

    waitpid( $pid, 0 );

    if ($?) {
        my $full_command = $bin . ' ' . join ' ', @cmd_args;
        my $stderr       = "Error encountered while running $full_command command: ";
        while ( my $line = <$err_fh> ) {
            $stderr .= $line;
        }
        die $stderr;
    }

    my $stdout;
    while ( my $line = <$out_fh> ) {
        $stdout .= $line;
    }

    return $stdout;
}

1;

} # --- END Cpanel/SecureDownload.pm


{ # --- BEGIN Cpanel/Crypt/GPG/VendorKeys.pm
package Cpanel::Crypt::GPG::VendorKeys;



use strict;
use warnings;

# use Cpanel::Crypt::GPG::Import::Temp ();
# use Cpanel::CachedDataStore          ();
# use Cpanel::SecureDownload           ();

our $VERSION = 1;


sub _get_config_file {
    return '/var/cpanel/gpg/vendorkeys.yaml';
}


sub _get_vendor_keys {
    return Cpanel::CachedDataStore::fetch_ref( _get_config_file() );
}


sub _save_vendor_keys {
    my ($vk_ref) = @_;
    require File::Basename;
    my $keydir = File::Basename::dirname( _get_config_file() );

    if ( !-d $keydir ) {
        require Cpanel::SafeDir::MK;
        Cpanel::SafeDir::MK::safemkdir( $keydir, 0700 );
    }

    return Cpanel::CachedDataStore::savedatastore( _get_config_file(), { mode => 0600, data => $vk_ref } );
}


sub set_keys {
    my (%args) = @_;

    $args{interval} = defined( $args{interval} ) ? $args{interval} : 86400;    # 1 day, in seconds.
    $args{enabled}  = defined( $args{enabled} )  ? $args{enabled}  : 1;

    for my $a (qw{vendor category url keys}) {
        if ( !$args{$a} ) {
            return wantarray ? ( undef, "Argument '$a' is required." ) : undef;
        }
    }

    my %new_keys;
    my @ckeys = ( ref( $args{keys} ) eq 'ARRAY' ) ? @{ $args{keys} } : ( $args{keys} );

    my $gpg = Cpanel::Crypt::GPG::Import::Temp->new();

    if ( !$gpg ) {
        return wantarray ? ( undef, "Failed to create GPG object." ) : undef;
    }

    for my $ckey (@ckeys) {
        while ( $ckey =~ /(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----)/gs ) {
            my $skey = $1;
            my ( $key_id, $msg ) = $gpg->get_key_id( key => $skey );

            if ( !$key_id ) {
                return wantarray ? ( undef, $msg ) : undef;
            }

            $new_keys{$key_id} = $skey;
        }
    }

    if ( !keys %new_keys ) {
        return wantarray ? ( undef, "No valid keys found." ) : undef;
    }

    my $vk_ref = _get_vendor_keys();


    $vk_ref->{ $args{vendor} }->{ $args{category} } = {
        url          => $args{url},
        keychain     => \%new_keys,
        enabled      => $args{enabled},
        interval     => $args{interval},
        noverify     => $args{noverify},
        last_updated => _get_current_time(),
    };

    $vk_ref->{__VERSION} = $VERSION;

    if ( _save_vendor_keys($vk_ref) ) {
        return wantarray ? ( 1, 'Success' ) : 1;
    }

    return wantarray ? ( undef, "Failed to save key store." ) : undef;
}


sub _get_current_time {
    return int(time);
}


sub set_keys_from_url {
    my (%args) = @_;

    for my $a (qw{vendor category url}) {
        if ( !$args{$a} ) {
            return wantarray ? ( undef, "Argument '$a' is required." ) : undef;
        }
    }

    my $url = $args{url};

    if ( ( !$args{noverify} ) && ( $url !~ /^https:\/\//i ) ) {
        return wantarray ? ( undef, "URL must use SSL." ) : undef;
    }

    my ( $ret, $download_data ) = Cpanel::SecureDownload::fetch_url(
        $url,
        ( 'timeout' => 60, 'no-check-certificate' => $args{noverify} )
    );

    if ( !$ret ) {

        return wantarray ? ( undef, $download_data ) : undef;
    }

    my ( $success, $msg ) = set_keys(
        vendor   => $args{vendor},
        category => $args{category},
        url      => $args{url},
        keys     => $download_data,
        enabled  => $args{enabled},
        interval => $args{interval},
        noverify => $args{noverify},
    );

    if ( !$success ) {
        return wantarray ? ( undef, "Failure when adding key: $msg" ) : undef;
    }

    return wantarray ? ( 1, "Successfully added key." ) : 1;
}


sub get_keys {
    my (%args) = @_;

    if ( !$args{vendor} ) {
        return wantarray ? ( undef, "Argument 'vendor' is required." ) : undef;
    }

    if ( !( $args{category} || $args{categories} ) ) {
        return wantarray ? ( undef, "Argument 'category' or 'categories' is required." ) : undef;
    }

    if ( $args{category} && $args{categories} ) {
        return wantarray ? ( undef, "Both argument 'category' and 'categories' can not be used simultaneously." ) : undef;
    }

    my $argcat = $args{category} || $args{categories};
    my @cats   = ( ref($argcat) eq 'ARRAY' ) ? @{$argcat} : ($argcat);
    my $vk_ref = _get_vendor_keys();

    if ( !$vk_ref->{ $args{vendor} } ) {
        return wantarray ? ( undef, "Keys for vendor '" . $args{vendor} . "' not found." ) : undef;
    }

    my %keys;

    for my $cat (@cats) {
        if ( !$vk_ref->{ $args{vendor} }->{$cat} ) {
            next;    # skip over non-existent categories
        }

        if ( !$vk_ref->{ $args{vendor} }->{$cat}->{enabled} ) {
            next;    # skip over disabled keychains
        }

        for my $key ( keys %{ $vk_ref->{ $args{vendor} }->{$cat}->{keychain} } ) {
            $keys{$key} = $vk_ref->{ $args{vendor} }->{$cat}->{keychain}->{$key};
        }
    }

    return \%keys;
}


sub get_key_info {
    my ($keyid) = @_;
    my $keys = _get_vendor_keys();

    foreach my $vendor ( keys %{$keys} ) {

        if ( index( $vendor, '__' ) == 0 ) {
            next;
        }

        foreach my $type ( keys %{ $keys->{$vendor} } ) {
            return ( $vendor, $type ) if grep { $keyid eq $_ } keys %{ $keys->{$vendor}->{$type}->{keychain} };
        }
    }
    return ( 'UNKNOWN', 'UNKNOWN' );
}

sub download_public_keys {
    my %opts = @_;


    require Cpanel::Logger;
    $opts{logger} ||= Cpanel::Logger->new();
    my $warn  = $opts{logger}->can("warn")  ? 'warn'  : 'warning';
    my $error = $opts{logger}->can("error") ? 'error' : 'warn';

    if ( $opts{noverify} ) {
        $opts{logger}->info("WARNING: Hostname verification is disabled!");
        $opts{logger}->info("Can not ensure the legitimacy of downloaded keys.");
    }

    my $vk_ref = _get_vendor_keys();


    my %update_keys;

    for my $vendor ( grep { index( $_, '__' ) != 0 } keys %{$vk_ref} ) {
        for my $category ( keys %{ $vk_ref->{$vendor} } ) {
            $update_keys{$vendor}->{$category}->{url}      = $vk_ref->{$vendor}->{$category}->{url};
            $update_keys{$vendor}->{$category}->{noverify} = $vk_ref->{$vendor}->{$category}->{noverify};
        }
    }


    for my $key ( @{ _get_pubkey_defaults() } ) {
        my $vendor   = $key->{vendor};
        my $category = $key->{category};
        my $url      = $key->{url};
        my $noverify = $key->{noverify};
        $update_keys{$vendor}->{$category}->{url}      = $url;
        $update_keys{$vendor}->{$category}->{noverify} = $noverify;
    }


    my @update_keys_list;

    for my $vendor ( keys %update_keys ) {
        for my $category ( keys %{ $update_keys{$vendor} } ) {
            my $key = {
                vendor   => $vendor,
                category => $category,
                url      => $update_keys{$vendor}->{$category}->{url},
                noverify => $update_keys{$vendor}->{$category}->{noverify},
            };

            push @update_keys_list, $key;
        }
    }


    my $keys;

    if ( $opts{keys} ) {
        $keys = $opts{keys};
    }
    else {
        $keys = \@update_keys_list;
    }

    my $success = 1;

    for my $key ( @{$keys} ) {
        my $interval     = $vk_ref->{ $key->{vendor} }->{ $key->{category} }->{interval}     || 0;
        my $last_updated = $vk_ref->{ $key->{vendor} }->{ $key->{category} }->{last_updated} || 0;


        my $current_time = _get_current_time();

        next if ( !$opts{force}
            && defined $vk_ref->{__VERSION}
            && $vk_ref->{__VERSION} == $VERSION
            && $current_time <= ( $interval + $last_updated )
            && $current_time >= $last_updated );

        my ( $succ, $msg ) = set_keys_from_url(
            vendor   => $key->{vendor},
            category => $key->{category},
            url      => $key->{url},
            noverify => $key->{noverify} || $opts{noverify},
        );

        if ($succ) {
            $opts{logger}->info("Retrieved public key from vendor: $key->{vendor}, category: $key->{category}, url: $key->{url}");
        }
        else {
            $opts{logger}->$warn("Unable to download public key from vendor: $key->{vendor}, category: $key->{category}, url: $key->{url}");
            $opts{logger}->info($msg);
            $success = 0;
        }
    }

    if ( !$success ) {
        $opts{logger}->$warn("Failed to download all specified public keys.");
    }

    return $success;
}

sub _get_pubkey_defaults {
    return [
        {
            url      => 'https://securedownloads.cpanel.net/cPanelPublicKey.asc',
            vendor   => 'cpanel',
            category => 'release',
        },
        {
            url      => 'https://securedownloads.cpanel.net/cPanelDevelopmentKey.asc',
            vendor   => 'cpanel',
            category => 'development',
        },
    ];
}

1;

} # --- END Cpanel/Crypt/GPG/VendorKeys.pm


{ # --- BEGIN Cpanel/FileUtils/Copy.pm
package Cpanel::FileUtils::Copy;


use strict;
use warnings;

# use Cpanel::Fcntl            ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::LoadModule       ();
# use Cpanel::Debug            ();

our $VERSION = '1.0';

my $COPY_CHUNK_SIZE = 131072;    #2 ** 17

sub safecopy {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my $srcfile    = shift;
    my $destfile   = shift;
    my $normrfcomp = shift || 0;

    if ( !length $srcfile ) {
        Cpanel::Debug::log_warn("Source not specified for copy.");
        return 0;
    }
    if ( !length $destfile ) {
        Cpanel::Debug::log_warn("Destination not specified for copy.");
        return 0;
    }
    if ( !-r $srcfile && $srcfile !~ m/\*$/ ) {
        Cpanel::Debug::log_warn("Unable to read source for copy");
        return 0;
    }

    my $is_file        = -f $srcfile ? 1 : 0;
    my $srcfileinfo    = q{};
    my $unlinkdestsafe = 1;
    if ($is_file) {    # Logic only for src files (not dirs).
        $srcfileinfo = join( '-', ( stat(_) )[ 0, 1 ] );

        $unlinkdestsafe = 9;
    }

    my $src_lock;
    if ($is_file) {

        local $@;
        require Cpanel::SafeFile;
        $src_lock = eval { Cpanel::SafeFile::safelock_skip_dotlock_if_not_root($srcfile) };
    }

    if ( !exists $INC{'File/Copy/Recursive.pm'} ) {
        Cpanel::LoadModule::lazy_load_module('File::Copy::Recursive');
    }
    if ( !exists $INC{'Cpanel/Umask.pm'} ) {
        Cpanel::LoadModule::lazy_load_module('Cpanel::Umask');
    }

    my $usefilecopyrecursive = ( exists $INC{'File/Copy/Recursive.pm'} && exists $INC{'Cpanel/Umask.pm'} ) ? 1 : 0;

    if ( !$usefilecopyrecursive ) {
        my $val = system( 'cp', '-rf', $srcfile, $destfile );
        if ($is_file) { Cpanel::SafeFile::safeunlock($src_lock) }
        if ($val) {
            Cpanel::Debug::log_warn("Problem copying $srcfile to $destfile! : system = $val");
            return 0;
        }
        return 1;
    }

    if ( $srcfileinfo ne '' && -f $destfile ) {
        my $destfileinfo = join( '-', ( stat(_) )[ 0, 1 ] );
        if ( $srcfileinfo eq $destfileinfo ) {    # files are the same
            Cpanel::SafeFile::safeunlock($src_lock) if $is_file;
            Cpanel::Debug::log_info("safecopy for $srcfile -> $destfile skipped. Target exists and has same size and inode number.");
            return 1;
        }

        if ( $unlinkdestsafe == 9 && !unlink($destfile) ) {

            $unlinkdestsafe = 0;
        }
        else {

            $unlinkdestsafe = 1;
        }
    }
    else {

        $unlinkdestsafe = 1;
    }

    {
        no warnings;
        $File::Copy::Recursive::RMTrgFil = $unlinkdestsafe;
    }

    if ( !$normrfcomp ) {
        $File::Copy::Recursive::CPRFComp = 1;
    }
    else {
        $File::Copy::Recursive::CPRFComp = 0;
    }

    undef $!;
    my $umask_obj = Cpanel::Umask->new(077);

    if ( File::Copy::Recursive::rcopy( $srcfile, $destfile ) ) {
        if ( $is_file && $src_lock ) { Cpanel::SafeFile::safeunlock($src_lock) }
        return 1;
    }
    else {
        my $err_msg;
        my $err_no;

        if ($!) {
            $err_no  = int $!;
            $err_msg = "$!";
        }

        else {
            $err_no  = 85;
            $err_msg = 'Unknown copy failure';
        }

        if ( $is_file && $src_lock ) {
            Cpanel::SafeFile::safeunlock($src_lock);
        }

        Cpanel::Debug::log_warn(qq{rcopy('$srcfile', '$destfile') failed: $err_msg});
        $! = $err_no;    ## no critic qw(Variables::RequireLocalizedPunctuationVars)
        return wantarray ? ( 0, $err_msg ) : 0;
    }
}

sub copy {
    my ( $source, $destination ) = @_;

    local $!;

    my ( $rfh, $wfh );

    my ( $i_opened_the_source, $i_opened_the_destination );

    if ( UNIVERSAL::isa( $source, 'GLOB' ) ) {
        if ( !fileno $source ) {
            return ( 0, "The source file handle is not open." );
        }
        elsif ( fcntl( $source, $Cpanel::Fcntl::Constants::F_GETFL, 0 ) & 1 ) {
            return ( 0, "The source file handle is write-only." );
        }

        $rfh = $source;
    }
    else {
        $i_opened_the_source = 1;

        open( $rfh, '<', $source ) or do {
            return ( 0, "The system failed to open the file “$source” for reading because of an error: $!" );
        };
    }

    my $buffer;
    read $rfh, $buffer, $COPY_CHUNK_SIZE or do {
        if ( length $! ) {
            return ( 0, "The system failed to read from the file “$source” because of an error: $!" );
        }
    };

    my $mode = ( stat $source )[2] & 07777;

    my $write_lock;

    if ( UNIVERSAL::isa( $destination, 'GLOB' ) ) {
        if ( !fileno $destination ) {
            return ( 0, "The destination file handle is not open." );
        }
        elsif ( !( fcntl( $destination, $Cpanel::Fcntl::Constants::F_GETFL, 0 ) & 1 ) ) {
            return ( 0, "The destination file handle is read-only." );
        }

        $wfh = $destination;
    }
    else {
        $i_opened_the_destination = 1;

        local $!;
        local $@;
        require Cpanel::SafeFile;
        $write_lock = eval { Cpanel::SafeFile::safesysopen( $wfh, $destination, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_CREAT )), $mode ) } or do {
            return ( 0, "The system failed to open the file “$destination” for writing because of an error: " . ( $@ || $! ) );
        };
    }

    do {

        print {$wfh} $buffer or do {
            return ( 0, "The system failed to write to the file “$destination” because of an error: $!" );
        };
    } while read $rfh, $buffer, $COPY_CHUNK_SIZE;

    if ($!) {
        return ( 0, "The system failed to read from the file “$source” because of an error: $!" );
    }

    truncate( $wfh, tell($wfh) );
    if ($!) {
        return ( 0, "The system failed to truncate the file “$destination” because of an error: $!" );
    }

    if ($i_opened_the_destination) {
        Cpanel::SafeFile::safeclose( $wfh, $write_lock ) or do {
            return ( 0, "The system failed to close the file “$destination” because of an error: $!" );
        };
    }

    if ($i_opened_the_source) {
        close $rfh or do {
            return ( 0, "The system failed to close the file “$source” because of an error: $!" );
        };
    }

    return 1;
}

1;

} # --- END Cpanel/FileUtils/Copy.pm


{ # --- BEGIN Cpanel/Math.pm
package Cpanel::Math;


use strict;

our $VERSION = '2.0';

my $nonetxt;
my $locale;

*floatto            = *_floatNum;
*_toHumanSize       = *_real_toHumanSize;
*human_format_bytes = *_real_toHumanSize;

sub ceil {
    my $cval = int $_[0];

    return ( ( $_[0] - $cval ) > 0 ) ? ( $cval + 1 ) : $cval;
}

sub floor { return int $_[0]; }

sub _floatNum {
    return sprintf( "%.$_[1]f", $_[0] );
}

sub get_none_text {
    return 'None' if $Cpanel::Parser::Vars::altmode;    # WHY DO WE DO THIS? If there is a reason please update this comment to explain
    return ( $nonetxt = _locale()->maketext('None') );
}

sub _real_toHumanSize {
    if ( !$_[0] && $_[1] ) {
        return defined $nonetxt ? $nonetxt : get_none_text();
    }
    return _locale()->format_bytes( $_[0] );
}

sub roundto {

    return $_[0] >= $_[2] ? $_[2] : $_[1] * int( ( $_[0] + 0.50000000000008 * $_[1] ) / $_[1] );
}


sub divide_with_random_translation {
    my ( $range, $divisor ) = @_;    #“range”, i.e., [ 0 .. $range ]

    die 'Call in list context!' if !wantarray;

    ( $_ != int ) && die "Integers only, not “$_”!" for ( $range, $divisor );

    if ( $range % $divisor ) {
        die "Invalid divisor: “$divisor” (must be a factor of $range)!";    #XXX
    }

    my $first_tick = int rand $divisor;

    my $ticks_count = $range / $divisor;

    return map { $first_tick + $_ * $divisor } ( 0 .. ( $ticks_count - 1 ) );
}

sub _locale {
    return $locale if defined $locale;
    eval 'require Cpanel::Locale';
    return ( $locale = 'Cpanel::Locale'->get_handle() );

}

1;


} # --- END Cpanel/Math.pm


{ # --- BEGIN Cpanel/Parallelizer.pm
package Cpanel::Parallelizer;


use cPstrict;

use Try::Tiny;

use IO::Select                   ();
# use Cpanel::FHUtils::Blocking    ();
# use Cpanel::AdminBin::Serializer ();

sub new {
    my ( $class, %self ) = @_;
    $self{'process_limit'}      ||= 25;      # Number of simultaneous processes
    $self{'total_time_limit'}   ||= 3600;    # Maximum total running time: One hour by default
    $self{'process_time_limit'} ||= 1800;    # Maximum running time for a single child process: 30 minutes by default
    $self{'running'}     = 0;
    $self{'_processes_'} = {
        'running' => [],
        'queued'  => [],
    };
    $self{'start_time'} = 0;
    return bless \%self, $class;
}

sub _set_get {
    my $self = shift;
    my $key  = shift;
    my $val  = shift;
    if ( defined $val ) {
        $self->{$key} = $val;
    }
    return $self->{$key};
}

sub process_limit {
    my $self = shift;
    my $val  = shift;
    return $self->_set_get( 'process_limit', $val );
}

sub process_time_limit {
    my $self = shift;
    my $val  = shift;
    return $self->_set_get( 'process_time_limit', $val );
}

sub total_time_limit {
    my $self = shift;
    my $val  = shift;
    return $self->_set_get( 'total_time_limit', $val );
}

sub running {
    my $self = shift;

    return $self->{'running'};
}

sub start_time {
    my $self = shift;

    return $self->{'start_time'};
}

sub run {
    my $self = shift;
    return 1 unless $self->running();

    my $now             = time();
    my $total_time_left = $self->{'total_time_limit'} - ( $now - $self->{'start_time'} );
    while ( my $next_process = shift @{ $self->{'_processes_'}{'queued'} } ) {
        if ( $total_time_left > 0 ) {
            $self->_reap_one_process();
        }
        $now             = time();
        $total_time_left = $self->{'total_time_limit'} - ( $now - $self->{'start_time'} );
        if ( $total_time_left > 0 ) {
            $self->_start_process( $next_process, $now );
        }
        else {
            &{ $next_process->{'error'} }( 'Total execution time exceeded!', @{ $next_process->{'args'} } );
        }
    }
    while ( $self->_reap_one_process() ) {

    }

    $self->{'running'} = 0;
    return 1;
}

sub queue {
    my $self           = shift;
    my $run_coderef    = shift;
    my $args_ar        = shift;
    my $return_coderef = shift;
    my $error_coderef  = shift;

    my $now = time();

    my $process_data = {
        'run'          => $run_coderef,
        'args'         => $args_ar,
        'return'       => $return_coderef,
        'error'        => $error_coderef,
        'pid'          => 0,
        'spool'        => '',
        'spool_length' => 0,
        'fh'           => undef,
        'start_time'   => 0,
    };

    unless ( $self->running() ) {
        $self->{'running'}                = 1;
        $self->{'_processes_'}{'running'} = [];
        $self->{'_processes_'}{'queued'}  = [];
        $self->{'start_time'}             = $now;
    }

    if ( scalar @{ $self->{'_processes_'}{'running'} } < $self->{'process_limit'} ) {
        return $self->_start_process( $process_data, $now );
    }
    else {
        push @{ $self->{'_processes_'}{'queued'} }, $process_data;
        return 1;
    }
}

sub _start_process {
    my $self         = shift;
    my $process_data = shift;
    my $now          = shift || time();

    my ( $pid, $reader_fh, $writer_fh );

    pipe( $reader_fh, $writer_fh );

    $pid = fork();
    if ( !defined $pid ) {
        close $reader_fh;
        close $writer_fh;
        if ( defined $process_data->{'error'} ) {
            &{ $process_data->{'error'} }( 'Failed to fork!', @{ $process_data->{'args'} } );
        }
        return 0;
    }
    elsif ($pid) {

        close $writer_fh;
        Cpanel::FHUtils::Blocking::set_non_blocking($reader_fh);

        $process_data->{'start_time'} = $now;
        $process_data->{'fh'}         = $reader_fh;
        $process_data->{'pid'}        = $pid;
        my $total_time_left = $self->{'total_time_limit'} - ( $now - $self->{'start_time'} );
        my $time_left       = $self->{'process_time_limit'} < $total_time_left ? $self->{'process_time_limit'} : $total_time_left;
        $process_data->{'expires_at'} = $now + $time_left;
        push @{ $self->{'_processes_'}{'running'} }, $process_data;
        return 1;
    }
    else {

        close $reader_fh;

        if ( !$self->{'keep_stdout_open'} ) {
            open STDOUT, '>', '/dev/null' or warn "Failed to redirect STDOUT to /dev/null: $!";
        }


        eval {
            my @return = &{ $process_data->{'run'} }( @{ $process_data->{'args'} } );
            print $writer_fh Cpanel::AdminBin::Serializer::Dump( \@return );
            close $writer_fh;

            exit 0;
        };

        warn;
        exit 1;
    }
}

sub _reap_one_process {
    my $self = shift;

    my $read_count;

    return 0 unless ( $self->running() );

    my $now;

    my $select_set = IO::Select->new();
    foreach my $proc ( @{ $self->{'_processes_'}{'running'} } ) {
        $select_set->add( $proc->{'fh'} );
    }

    while ( scalar @{ $self->{'_processes_'}{'running'} } ) {

        $now = time();

        for ( my $x = 0; $x <= $#{ $self->{'_processes_'}{'running'} }; $x++ ) {
            my $process_data = $self->{'_processes_'}{'running'}[$x];

            while ( $read_count = sysread( $process_data->{'fh'}, $process_data->{'spool'}, 4096, $process_data->{'spool_length'} ) ) {
                $process_data->{'spool_length'} += $read_count;
            }

            if ( defined $read_count ) {

                local $?;
                my $reaped = waitpid( $process_data->{'pid'}, 1 );
                if ( $reaped == $process_data->{'pid'} ) {

                    close $process_data->{'fh'};
                    if ( $? != 0 ) {

                        if ( defined $process_data->{'error'} ) {
                            &{ $process_data->{'error'} }( 'Exited with code ' . ( $? >> 8 ) . ' and signal ' . ( $? & 127 ), @{ $process_data->{'args'} } );
                        }
                    }
                    else {

                        my @return;

                        eval { @return = @{ Cpanel::AdminBin::Serializer::Load( $process_data->{'spool'} ) }; };
                        if ($@) {

                            if ( defined $process_data->{'error'} ) {
                                &{ $process_data->{'error'} }( "Could not make sense of returned data ($process_data->{'spool'}) - $@", @{ $process_data->{'args'} } );
                            }
                        }
                        elsif ( defined $process_data->{'return'} ) {

                            &{ $process_data->{'return'} }(@return);
                        }

                    }

                    splice( @{ $self->{'_processes_'}{'running'} }, $x, 1 );
                    return 1;
                }
                elsif ( $reaped == -1 ) {

                    if ( defined $process_data->{'error'} ) {
                        &{ $process_data->{'error'} }( 'Child disappeared during processing', @{ $process_data->{'args'} } );
                    }

                    splice( @{ $self->{'_processes_'}{'running'} }, $x, 1 );
                    return 1;
                }
            }

            if ( $process_data->{'expires_at'} <= $now ) {
                kill 'KILL', $process_data->{'pid'};

                local $?;
                waitpid( $process_data->{'pid'}, 0 );

                if ( defined $process_data->{'error'} ) {
                    &{ $process_data->{'error'} }( 'Timed Out', @{ $process_data->{'args'} } );
                }
                splice( @{ $self->{'_processes_'}{'running'} }, $x, 1 );
                return 1;

            }
        }

        $select_set->can_read(0.2);
    }

    return 0;
}

sub jobs_count {
    my $self = shift;
    return $self->active_count() + $self->queued_count();
}

sub active_count {
    my $self = shift;
    return scalar @{ $self->{'_processes_'}{'running'} };
}

sub queued_count {
    my $self = shift;
    return scalar @{ $self->{'_processes_'}{'queued'} };
}

sub get_operations_per_process {
    my ( $self, $total_operations ) = @_;

    require Cpanel::Math;
    return Cpanel::Math::ceil( $total_operations / $self->process_limit() );
}

sub pmap ( $code, @list ) {

    my $run_cb = sub {
        local $_ = shift;
        return $code->();
    };

    my $parallelizer = Cpanel::Parallelizer->new();

    my $lim = scalar(@list);
    $lim = $lim < 20 ? $lim : 20;
    $parallelizer->process_limit($lim);

    my @ret;
    my $ret_cb = sub {
        push( @ret, @_ );
    };
    my $err_cb = sub { };

    foreach my $x (@list) {
        $parallelizer->queue( $run_cb, [$x], $ret_cb, $err_cb );
    }
    $parallelizer->run();
    return @ret;
}

1;


} # --- END Cpanel/Parallelizer.pm


{ # --- BEGIN Cpanel/FileUtils/Link.pm
package Cpanel::FileUtils::Link;


use strict;
use warnings;

# use Cpanel::Debug ();

sub safeunlink {
    my $file = shift;
    return 1 if !-l $file && !-e _;
    if ( unlink $file ) {
        return 1;
    }
    else {
        Cpanel::Debug::log_warn("Unable to unlink $file: $!");
        return;
    }
}

sub _replicate_file {
    my $orig = shift;
    my $dest = shift;

    my ( $mode, $uid, $gid, $atime, $mtime ) = ( stat($orig) )[ 2, 4, 5, 8, 9 ];
    $mode = $mode & 07777;

    return 0 if ( !-e _ );
    return 0 unless ( -r _ || -w _ || -x _ );

    require Cpanel::SafeFile;
    my $ori_fh;
    my $dest_fh;
    open( $ori_fh, '<', $orig ) || return 0;
    my $destlock = Cpanel::SafeFile::safeopen( $dest_fh, '>', $dest ) || do {
        Cpanel::Debug::log_warn("Unable to open $dest for write!");
        close($ori_fh);
        return 0;
    };
    while (<$ori_fh>) {
        print {$dest_fh} $_;
    }
    close($ori_fh);
    Cpanel::SafeFile::safeclose( $dest_fh, $destlock );
    if ( -z $orig != -z $dest ) {
        unlink($dest);
        Cpanel::Debug::log_warn("Unable to properly write $dest");
        return 0;
    }
    unless ( chown( $uid, $gid, $dest ) ) {
        Cpanel::Debug::log_warn("Unable to chown $dest to UID $uid GID $gid");
    }
    unless ( chmod( $mode, $uid, $dest ) ) {
        Cpanel::Debug::log_warn("Unable to chmod $dest for UID $uid");
    }
    unless ( utime( $atime, $mtime, $dest ) ) {
        Cpanel::Debug::log_warn("Unable to set utime on $dest for UID $uid");
    }

    return 1;
}

sub safelink {
    my $orig = shift;
    my $dest = shift;

    return 0 if ( $orig eq '' || $dest eq '' || !-e $orig );

    return 0 unless ( -r $orig || -w $orig || -x $orig );

    if ( !link( $orig, $dest ) ) {

        return _replicate_file( $orig, $dest );
    }
    return 1;
}

sub forced_symlink {
    my ( $target, $file ) = @_;

    my $current_target = readlink($file);

    if ($current_target) {
        return 1 if $current_target eq $target;
        unlink($file);
    }

    return symlink( $target, $file );
}

sub find_symlink_in_path {
    my ($path) = @_;

    my @split_path = split m{/}, $path;
    my $test_path  = q{};
    while (@split_path) {
        my $path_node = shift @split_path;
        next if !length $path_node;

        $test_path .= "/$path_node";
        return $test_path if -l $test_path;

        last if !-e _;
    }

    return;
}

1;

} # --- END Cpanel/FileUtils/Link.pm


{ # --- BEGIN Cpanel/RPM/Versions/File/YAML.pm


package Cpanel::RPM::Versions::File::YAML;

use strict;
use warnings;

use YAML::Syck ();

BEGIN {
    $YAML::Syck::LoadBlessed = 0;
    $YAML::Syck::SortKeys    = 1;
}

sub supported_file_format {
    my ($self) = @_;

    my $supported_file_format = 2;
    return $supported_file_format;
}

sub new {
    my ( $class, $args ) = @_;

    my $self = $class->init($args);

    bless $self, $class;

    $self->_loadfile();

    return $self;
}

sub init {
    my ( $class, $args ) = @_;

    my $self = {
        yaml_file => $args->{'file'},
    };

    return $self;
}

sub _loadfile {

    my ($self) = @_;

    my $file = $self->yaml_file();

    if ( !-e $file || -z _ ) {
        $self->{'data'} = {};
        return 0;
    }

    eval { $self->{'data'} = YAML::Syck::LoadFile($file) };

    if ($@) {
        die "Unable to load $file: $@";
    }

    if ( !exists $self->{'data'}->{'file_format'}{'version'} || $self->{'data'}->{'file_format'}{'version'} != $self->supported_file_format() ) {
        die( 'Incorrect file format version in ' . $file );
    }

    return scalar keys %{ $self->{'data'} };
}

sub yaml_file {
    my ($self) = @_;
    return $self->{'yaml_file'};
}

sub fetch {
    my ( $self, $args ) = @_;

    return if ( !keys %{ $self->{'data'} } );

    my $section = $args->{'section'};
    my $key     = $args->{'key'};

    if ($key) {
        return $self->{'data'}->{$section}->{$key};
    }
    else {
        return $self->{'data'}->{$section} || {};
    }
}

sub set {
    my ( $self, $args ) = @_;
    my $section = $args->{'section'};
    my $key     = $args->{'key'};
    my $value   = $args->{'value'};

    if ( ref $key eq 'ARRAY' ) {
        $self->{'data'}->{$section} = {} if ( ref $self->{'data'}->{$section} ne 'HASH' );
        _build_hash( $key, $self->{'data'}->{$section}, $value );

        return $self->{'data'}->{$section};
    }

    return $self->{'data'}->{$section}->{$key} = $value;
}

sub delete {
    my ( $self, $args ) = @_;

    return if ( !keys %{ $self->{'data'} } );

    my $section = $args->{'section'};
    my $key     = $args->{'key'};

    if ( ref $key eq 'ARRAY' ) {
        _delete_hash( $key, $self->{'data'}->{$section} );
        return;
    }

    return delete $self->{'data'}->{$section}->{$key};
}

sub visit_section {
    my ( $self, $section, $coderef ) = @_;
    foreach my $key ( keys %{ $self->{'data'}->{$section} } ) {
        $coderef->( $key, $self->{'data'}->{$section}->{$key} );
    }
}

sub visit_all {
    my ( $self, $coderef ) = @_;
    foreach my $section ( keys %{ $self->{'data'} } ) {
        foreach my $key ( keys %{ $self->{'data'}->{$section} } ) {
            $coderef->( $section, $key, $self->{'data'}->{$section}->{$key} );
        }
    }
}

sub save {
    my ($self) = @_;

    if ( !%{ $self->{'data'} } ) {
        return;
    }

    if ( !exists $self->{'data'}{'file_format'} ) {
        $self->{'data'}{'file_format'}{'version'} = $self->supported_file_format();
    }

    return YAML::Syck::DumpFile( $self->yaml_file(), $self->{'data'} );
}

sub _build_hash {
    my ( $keys, $hash_accumulator, $value ) = @_;
    while (@$keys) {
        my $key = shift @$keys;

        if ( ref $hash_accumulator->{$key} ne 'HASH' ) {
            $hash_accumulator->{$key} = @$keys ? {} : $value;
        }
        $hash_accumulator = $hash_accumulator->{$key};
    }

    return;
}

sub _delete_hash {
    my ( $keys, $hash_accumulator ) = @_;
    while (@$keys) {
        my $key = shift @$keys;

        if ( !@$keys ) {
            if ( ref $hash_accumulator eq 'HASH' ) {
                delete $hash_accumulator->{$key};
                return;
            }
        }
        $hash_accumulator = $hash_accumulator->{$key};
    }

    return;
}

1;

} # --- END Cpanel/RPM/Versions/File/YAML.pm


{ # --- BEGIN Cpanel/Update/Config.pm
package Cpanel::Update::Config;


use strict;
use warnings;

# use Cpanel::Config::LoadConfig ();

our $VERSION            = '2.1';
our $cpanel_update_conf = '/etc/cpupdate.conf';

sub _default_preferences {
    return {
        'CPANEL'      => 'release',
        'RPMUP'       => 'daily',
        'SARULESUP'   => 'daily',
        'UPDATES'     => 'daily',
        'STAGING_DIR' => '/usr/local/cpanel',
    };
}

sub valid_keys {

    return [qw/CPANEL RPMUP SARULESUP UPDATES STAGING_DIR/];
}

sub load {
    my $default_rUPCONF = _default_preferences();

    if ( ${^GLOBAL_PHASE} && ${^GLOBAL_PHASE} eq 'START' && lc($0) ne '-e' ) {
        die q[FATAL: load is called during compile time. You should postpone this call.];
    }

    if ( !-e $cpanel_update_conf ) {
        save($default_rUPCONF);
        return wantarray ? %{$default_rUPCONF} : $default_rUPCONF;
    }

    my $rUPCONF = Cpanel::Config::LoadConfig::loadConfig($cpanel_update_conf);
    my $changed = sanitize($rUPCONF);

    foreach my $key ( keys %{$default_rUPCONF} ) {
        if ( !exists $rUPCONF->{$key} ) {
            $changed++;
            $rUPCONF->{$key} = $default_rUPCONF->{$key};
        }
    }

    save($rUPCONF) if $changed;

    return wantarray ? %{$rUPCONF} : $rUPCONF;
}

sub sanitize {
    my $conf_ref       = shift;
    my $die_on_failure = shift;

    return if ref $conf_ref ne 'HASH';

    my $changed = 0;

    my $valid_keys = valid_keys();

    foreach my $key ( keys %{$conf_ref} ) {

        if ( !grep { $key eq $_ } @$valid_keys ) {
            delete $conf_ref->{$key};
            $changed++;
            next;
        }

        my $value = $conf_ref->{$key};

        if ($value) {
            $changed++ if ( $value                   =~ s/[\n\r]//g );    # Strip newline chars
            $changed++ if ( $value                   =~ s/^\s+// );       # Strip leading whitespace
            $changed++ if ( $value                   =~ s/\s+$// );       # Strip trailing whitespace
            $changed++ if ( $value ne '/' and $value =~ s{/+$}{} );       # Strip trailing slash. This is for STAGING_DIR but nothing else should have a slash in its value.

            if ( $key ne 'STAGING_DIR' ) {
                $changed++ if ( $value =~ tr/A-Z/a-z/ );
            }
        }

        if ( $key eq 'STAGING_DIR' and not validate_staging_dir( $value, $die_on_failure ) ) {
            $value = _default_preferences()->{'STAGING_DIR'};
            $changed++;                                                   # Flag for file save
        }

        if ( !defined $value ) {
            $value = '';
            $changed++;
        }

        $conf_ref->{$key} = $value;
    }

    return $changed;
}

sub _stat_directory {
    my $dir = shift;
    return stat($dir);
}

sub validate_staging_dir {

    my ( $value, $die_on_failure ) = @_;
    my $ulc     = '/usr/local/cpanel';
    my $ulc_dev = ( _stat_directory($ulc) )[0];

    return if not $value;

    if ( !_is_valid_filepath($value) ) {
        die "'$value' is not a valid directory path\n" if $die_on_failure;
        return;
    }

    my @stat = _stat_directory($value) or return 1;

    if ( -e $value && !-d $value ) {
        die "'$value' exists on the file system, but is not a directory\n" if $die_on_failure;
        return;
    }

    if ( -e $value && ( !-d $value || !( -d $value && -w $value ) ) ) {
        die "'$value' exists on the file system, but is not a writable directory\n" if $die_on_failure;
        return;
    }

    if ( 0 != $stat[4] ) {
        die "'$value' exists on the file system, but is not owned by the root user\n" if $die_on_failure;
        return;
    }

    if ( $stat[0] == $ulc_dev && $value ne $ulc ) {
        die "'$value' is on the same file system as /usr/local/cpanel. Please use /usr/local/cpanel instead.\n" if $die_on_failure;
        return;
    }

    if ( $stat[2] & 022 ) {
        die "'$value' exists on the file system, but does not have the correct permissions. Directory must not have write permissions for group and non-root users\n" if $die_on_failure;
        return;
    }

    return 1;
}

sub save {
    my $conf_ref       = shift;
    my $die_on_failure = shift;

    return if ref $conf_ref ne 'HASH';

    return if ( $> != 0 );

    sanitize( $conf_ref, $die_on_failure );

    require Cpanel::Config::FlushConfig;
    if ( my $return = Cpanel::Config::FlushConfig::flushConfig( $cpanel_update_conf, $conf_ref, '=', undef, { 'sort' => 1 } ) ) {
        return $return;
    }
    else {
        die "Unable to save file, $cpanel_update_conf: $!\n" if $die_on_failure;
        return;
    }
}

sub get_tier {
    my ($update_config_ref) = @_;

    if ( !defined $update_config_ref ) {
        $update_config_ref = load();
    }

    return if ( ref $update_config_ref ne 'HASH' );

    return $update_config_ref->{'CPANEL'};
}

sub is_permitted {
    my $key     = shift or return;
    my $up_conf = shift or return;
    ref $up_conf eq 'HASH' or return;

    $key = uc($key);    # Force key case upper.
    my $key_value = $up_conf->{$key} or return;

    return if ( $key eq 'RPMUP' && $ENV{'CPANEL_BASE_INSTALL'} );
    return if ( $key_value eq 'never' );
    return if ( $ENV{'CPANEL_IS_CRON'} && $key_value eq 'manual' );
    return 1;
}

sub get_update_type {
    my $rUPCONF = load();
    return $rUPCONF->{'UPDATES'};
}

sub _is_valid_filepath {
    my $filepath = shift;
    return 1 if index( $filepath, '/' ) == 0;    # checking for / is the same as file_name_is_absolute
    return;
}

1;

} # --- END Cpanel/Update/Config.pm


{ # --- BEGIN Cpanel/Services/AlwaysInstalled.pm
package Cpanel::Services::AlwaysInstalled;


use strict;
use warnings;


use constant SERVICES => (
    'cpanalyticsd',
    'cpanel_php_fpm',
    'cpgreylistd',
    'cphulkd',
    'cpsrvd',
    'dnsadmin',
    'ipaliases',
    'lmtp',
    'named',
    'queueprocd',
    'tailwatchd',
);

1;

} # --- END Cpanel/Services/AlwaysInstalled.pm


{ # --- BEGIN Cpanel/Validate/AnyAllMatcher.pm
package Cpanel::Validate::AnyAllMatcher;


use strict;
use warnings;



sub match {

    my ( $args, $callback ) = @_;

    if ( !defined $args ) {
        require Cpanel::Exception;
        die Cpanel::Exception::create( 'MissingParameter', 'No parameter value specified.' );
    }

    if ( !defined $callback ) {
        require Cpanel::Exception;
        die Cpanel::Exception::create( 'MissingParameter', 'No callback specified.' );
    }

    if ( !ref $args ) {
        return $callback->($args) ? 1 : 0;
    }
    elsif ( ref $args eq 'HASH' ) {

        my $match = $args->{match} || 'all';
        my $items = $args->{items};

        if ( $match ne 'any' && $match ne 'all' ) {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'InvalidParameter', 'The “[_1]” parameter must be “[_2]” or “[_3]” value.', [qw(match any all)] );
        }

        if ( !$items || ref $items ne 'ARRAY' ) {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'InvalidParameter', 'The “[_1]” parameter must be an array reference.', ["items"] );
        }

        foreach my $item (@$items) {
            my $bool = $callback->($item);
            return 1 if $bool  && $match eq 'any';
            return 0 if !$bool && $match eq 'all';
        }

        return $match eq 'any' ? 0 : 1;
    }

    require Cpanel::Exception;
    die Cpanel::Exception::create( 'InvalidParameter', 'The input parameter must be a string or a hash reference.' );
}

1;

} # --- END Cpanel/Validate/AnyAllMatcher.pm


{ # --- BEGIN Cpanel/StatCache.pm
package Cpanel::StatCache;


use strict;
use warnings;

our $VERSION = 0.4;

my %STATCACHE;


our $USE_LSTAT = 0;

sub StatCache_init { }


sub cachedmtime {
    return (
        exists $STATCACHE{ $_[0] } ? $STATCACHE{ $_[0] }->[0]
        : (
            $STATCACHE{ $_[0] } = (
                  $USE_LSTAT && -l $_[0] ? [ ( lstat(_) )[ 9, 7, 10 ] ]
                : -e $_[0]               ? [ ( stat(_) )[ 9, 7, 10 ] ]
                :                          [ 0, 0, 0 ]
            )
        )->[0]
    );
}


sub cachedmtime_size {
    return (
        exists $STATCACHE{ $_[0] } ? @{ $STATCACHE{ $_[0] } }[ 0, 1 ]
        : @{
            (
                $STATCACHE{ $_[0] } = (
                      $USE_LSTAT && -l $_[0] ? [ ( lstat(_) )[ 9, 7, 10 ] ]
                    : -e $_[0]               ? [ ( stat(_) )[ 9, 7, 10 ] ]
                    :                          [ 0, 0, 0 ]
                )
            )
        }[ 0, 1 ]
    );
}


sub cachedmtime_ctime {
    return (
        exists $STATCACHE{ $_[0] } ? @{ $STATCACHE{ $_[0] } }[ 0, 2 ]
        : @{
            (
                $STATCACHE{ $_[0] } = (
                      $USE_LSTAT && -l $_[0] ? [ ( lstat(_) )[ 9, 7, 10 ] ]
                    : -e $_[0]               ? [ ( stat(_) )[ 9, 7, 10 ] ]
                    :                          [ 0, 0, 0 ]
                )
            )
        }[ 0, 2 ]
    );
}


sub clearcache {
    %STATCACHE = ();
    return 1;
}

1;

} # --- END Cpanel/StatCache.pm


{ # --- BEGIN Cpanel/FindBin.pm
package Cpanel::FindBin;


use strict;
use warnings;

use constant _ENOENT => 2;

our $VERSION = 1.2;

my %bin_cache;
my @default_path = qw( /usr/bin /usr/local/bin /bin /sbin /usr/sbin /usr/local/sbin );

sub findbin {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $binname = shift;
    return if !$binname;

    my @lookup_path = get_path(@_);

    my $nocache = grep( /nocache/, @_ );

    if ( !$nocache && exists $bin_cache{$binname} && $bin_cache{$binname} ne '' ) {
        return $bin_cache{$binname};
    }

    foreach my $path (@lookup_path) {
        next unless -d $path;

        $path .= "/$binname";

        if ( -e $path ) {
            if ( -x _ ) {
                $bin_cache{$binname} = $path unless $nocache;
                return $path;
            }
            else {
                warn "“$path” exists but is not executable; ignoring.\n";
            }
        }
        elsif ( $! != _ENOENT() ) {
            warn "stat($path): $!\n";
        }
    }
    return;
}

sub get_path {
    if ( !$_[0] ) {
        return @default_path;
    }
    elsif ( scalar @_ > 1 ) {
        my %opts;
        %opts = @_ if ( scalar @_ % 2 == 0 );
        if ( exists $opts{'path'} && ref $opts{'path'} eq 'ARRAY' ) {
            return @{ $opts{'path'} };
        }
        else {
            return @_;
        }
    }
    elsif ( ref $_[0] eq 'ARRAY' ) {
        return @{ $_[0] };
    }
    return @default_path;
}

1;

} # --- END Cpanel/FindBin.pm


{ # --- BEGIN Cpanel/CachedCommand/Valid.pm
package Cpanel::CachedCommand::Valid;


use strict;
use warnings;
# use Cpanel::StatCache ();
# use Cpanel::Debug     ();


sub is_cache_valid {    ## no critic qw(Subroutines::ProhibitExcessComplexity) -- needs to be refactored
    my %OPTS = @_;
    my ( $datastore_file, $datastore_file_mtime, $datastore_file_size, $binary, $ttl, $mtime, $min_expire_time, $now ) = ( ( $OPTS{'datastore_file'} || '' ), ( $OPTS{'datastore_file_mtime'} || 0 ), ( $OPTS{'datastore_file_size'} || 0 ), ( $OPTS{'binary'} || '' ), ( $OPTS{'ttl'} || 0 ), ( $OPTS{'mtime'} || 0 ), ( $OPTS{'min_expire_time'} || 0 ), ( $OPTS{'now'} || 0 ) );

    if ( !$datastore_file_mtime && !-e $datastore_file ) {
        print STDERR "is_cache_valid: rejecting $datastore_file because it does not exist.\n" if $Cpanel::Debug::level;
        return 0;
    }

    if ( !$datastore_file_size || !$datastore_file_mtime ) {
        ( $datastore_file_size, $datastore_file_mtime ) = ( stat(_) )[ 7, 9 ];
    }

    if ( $datastore_file_mtime <= 0 ) {
        print STDERR "is_cache_valid: rejecting $datastore_file as mtime is zero.\n" if $Cpanel::Debug::level;
        return 0;
    }

    if ($binary) {
        if ( substr( $binary, 0, 1 ) ne '/' ) {
            require Cpanel::FindBin;
            $binary = Cpanel::FindBin::findbin( $binary, split( /:/, $ENV{'PATH'} ) );
        }
        my ( $binary_mtime, $binary_ctime ) = Cpanel::StatCache::cachedmtime_ctime($binary);
        if ( ( $binary_mtime && $binary_mtime > $datastore_file_mtime ) || ( $binary_ctime && $binary_ctime > $datastore_file_mtime ) ) {
            if ($Cpanel::Debug::level) {
                print STDERR "is_cache_valid: rejecting $datastore_file as binary ($binary) ctime or mtime is newer.\n";
                print STDERR "is_cache_valid: datastore_file:$datastore_file mtime[$datastore_file_mtime]\n";
                print STDERR "is_cache_valid: binary_file:$binary mtime[$binary_mtime] ctime[$binary_ctime]\n";
            }
            return 0;
        }
    }
    $now ||= time();
    if ( $datastore_file_mtime > $now ) {
        print STDERR "is_cache_valid: rejecting $datastore_file as it is from the future (time warp safety).\n" if $Cpanel::Debug::level;
        return 0;
    }
    elsif ( $min_expire_time && $datastore_file_mtime > ( $now - $min_expire_time ) ) {
        print STDERR "is_cache_valid: accept $datastore_file (mtime=$datastore_file_mtime) as min_expire_time ($now - $min_expire_time) is older.\n" if $Cpanel::Debug::level;
        return 1;
    }
    elsif ( $mtime > $datastore_file_mtime ) {
        print STDERR "is_cache_valid: rejecting $datastore_file because mtime ($mtime) is newer then datastore mtime ($datastore_file_mtime).\n" if $Cpanel::Debug::level;
        return 0;
    }
    elsif ( $ttl && ( $datastore_file_mtime + $ttl ) < $now ) {
        print STDERR "is_cache_valid: rejecting $datastore_file as it has reached its time to live.\n" if $Cpanel::Debug::level;
        return 0;
    }

    print STDERR "is_cache_valid: accepting $datastore_file as it passes all tests.\n" if $Cpanel::Debug::level;

    return 1;
}
1;

} # --- END Cpanel/CachedCommand/Valid.pm


{ # --- BEGIN Cpanel/CachedCommand/Save.pm
package Cpanel::CachedCommand::Save;


use strict;
use warnings;

# use Cpanel::CachedCommand::Utils ();
# use Cpanel::FileUtils::Write     ();
# use Cpanel::Debug                ();
# use Cpanel::Exception            ();

use Try::Tiny;

sub _savefile {
    my ( $filename, $content ) = @_;
    return if !defined $content;    #should be able to store 0

    $filename =~ tr{/}{}s;          # collapse //s to /
    my @path = split( /\//, $filename );
    my $file = pop(@path);
    my $dir  = join( '/', @path );

    my $dir_uid = ( stat($dir) )[4];

    if ( !defined $dir_uid ) {
        Cpanel::Debug::log_warn("Unable to write datastore file: $filename: target directory: $dir does not exist.");
        return;

    }
    elsif ( $dir_uid != $> ) {
        Cpanel::Debug::log_warn("Unable to write datastore file: $filename: target directory: $dir does not match uid $>");
        return;
    }

    local $!;
    my $ret;
    try {
        $ret = Cpanel::FileUtils::Write::overwrite( $filename, ( ref $content ? $$content : $content ), 0600 );
    }
    catch {
        my $err = $_;

        Cpanel::Debug::log_warn( Cpanel::Exception::get_string($err) );
    };

    return $ret;
}

sub store {
    my %OPTS = @_;
    _savefile( Cpanel::CachedCommand::Utils::_get_datastore_filename( $OPTS{'name'} ), $OPTS{'data'} );
}

1;

} # --- END Cpanel/CachedCommand/Save.pm


{ # --- BEGIN Cpanel/SafeRun/Env.pm
package Cpanel::SafeRun::Env;


use strict;

# use Cpanel::Env   ();
# use Cpanel::Debug ();

our $VERSION = '1.0';

sub saferun_r_cleanenv {
    return saferun_cleanenv2( { 'command' => \@_, 'return_ref' => 1, 'cleanenv' => { 'http_purge' => 1 } } );
}

sub saferun_cleanenv2 {
    my $args_hr = shift;
    return unless ( defined $args_hr->{'command'} && ref $args_hr->{'command'} eq 'ARRAY' );
    if ($Cpanel::AccessIds::ReducedPrivileges::PRIVS_REDUCED) {    # PPI NO PARSE --  can't be reduced if the module isn't loaded
        die __PACKAGE__ . " cannot be used with ReducedPrivileges. Use Cpanel::SafeRun::Object instead";
    }

    my @command                   = @{ $args_hr->{'command'} };
    my $return_reference          = $args_hr->{'return_ref'};
    my $error_output              = $args_hr->{'errors'};
    my %cleanenv_args             = defined $args_hr->{'cleanenv'} && ref $args_hr->{'cleanenv'} eq 'HASH' ? %{ $args_hr->{'cleanenv'} }             : ();
    my $check_cpanel_homedir_user = defined $args_hr->{'check_cpanel_homedir_user'}                        ? $args_hr->{'check_cpanel_homedir_user'} : 1;

    return if ( substr( $command[0], 0, 1 ) eq '/' && !-x $command[0] );
    my $output;
    if ( !@command ) {
        Cpanel::Debug::log_warn('Cannot execute a null program');
        return \$output if $return_reference;
        return $output;
    }
    require Cpanel::Env;
    local ( $/, *PROG, *RNULL );

    no strict 'refs';
    open( RNULL, '<', '/dev/null' );    ## no critic(InputOutput::ProhibitBarewordFileHandles InputOutput::RequireCheckedOpen)
    my $pid = open( PROG, "-|" );       ## no critic(InputOutput::ProhibitBarewordFileHandles)
    if ( $pid > 0 ) {
        $output = <PROG>;
    }
    elsif ( $pid == 0 ) {
        open( STDIN, '<&RNULL' );
        if ($error_output) {
            open STDERR, '>&STDOUT';
        }
        Cpanel::Env::clean_env(%cleanenv_args);
        if ( $check_cpanel_homedir_user && ( !$Cpanel::homedir || !$Cpanel::user ) ) {
            ( $ENV{'USER'}, $ENV{'HOME'} ) = ( getpwuid($>) )[ 0, 7 ];    #do not use PwCache here
        }
        exec(@command) or exit(1);                                        # Not reached
    }
    else {
        Cpanel::Debug::log_warn('Could not fork new process');
        return \$output if $return_reference;
        return $output;
    }
    close(PROG);
    close(RNULL);
    waitpid( $pid, 0 );
    return \$output if $return_reference;
    return $output;
}

1;

} # --- END Cpanel/SafeRun/Env.pm


{ # --- BEGIN Cpanel/CachedCommand.pm
package Cpanel::CachedCommand;


use strict;
use warnings;
# use Cpanel::StatCache            ();
# use Cpanel::LoadFile             ();
# use Cpanel::CachedCommand::Utils ();
# use Cpanel::CachedCommand::Valid ();
# use Cpanel::Debug                ();

our $VERSION = '2.8';

my %MEMORY_CACHE;

sub _is_memory_cache_valid {
    my %OPTS           = @_;
    my $datastore_file = $OPTS{'datastore_file'};

    if ( !exists $MEMORY_CACHE{$datastore_file} ) {
        print STDERR "_is_memory_cache_valid: rejecting $datastore_file because it does not exist in memory.\n" if $Cpanel::Debug::level;
        return 0;
    }

    my $ttl   = $OPTS{'ttl'};
    my $mtime = $OPTS{'mtime'};

    if ( !$ttl && $mtime && $MEMORY_CACHE{$datastore_file}->{'mtime'} == $mtime ) {
        print STDERR "_is_memory_cache_valid: accepting $datastore_file because it passes the mtime test.\n" if $Cpanel::Debug::level;
        return 1;
    }
    else {
        my $now = time();
        if ( $ttl && $MEMORY_CACHE{$datastore_file}->{'mtime'} > ( $now - $ttl ) ) {
            print STDERR "_is_memory_cache_valid: accepting $datastore_file because it passes the ttl test.\n" if $Cpanel::Debug::level;
            return 1;
        }
    }

    print STDERR "_is_memory_cache_valid: rejecting $datastore_file because it not pass the ttl or mtime test.\n" if $Cpanel::Debug::level;
    delete $MEMORY_CACHE{$datastore_file};
    return 0;
}

sub invalidate_cache {
    my $ds_file = Cpanel::CachedCommand::Utils::invalidate_cache(@_);
    delete $MEMORY_CACHE{$ds_file};

    return;
}

sub _cached_cmd {
    my %OPTS = @_;

    my ( $binary, $ttl, $mtime, $exact, $regexcheck, $args_hr, $min_expire_time, $get_result_cr ) = (
        ( $OPTS{'binary'}          || '' ),
        ( $OPTS{'ttl'}             || 0 ),
        ( $OPTS{'mtime'}           || 0 ),
        ( $OPTS{'exact'}           || 0 ),
        ( $OPTS{'regexcheck'}      || '' ),
        ( $OPTS{'args_hr'}         || {} ),
        ( $OPTS{'min_expire_time'} || 0 ),
        ( $OPTS{'get_result_cr'}   || \&_default_get_result_cr ),
    );

    my @AG;
    if ( ref $OPTS{'args'} eq 'ARRAY' ) {
        @AG = @{ $OPTS{'args'} };
    }

    if ( substr( $binary, 0, 1 ) eq '/' && !-x $binary ) {
        return "$binary is missing or not executable";
    }
    my @SAFEAG = @AG;
    if ( !$exact && scalar @SAFEAG > 4 ) {

        splice( @SAFEAG, 4 );
    }

    my $datastore_file = Cpanel::CachedCommand::Utils::_get_datastore_filename( $binary, @SAFEAG );

    if (
        _is_memory_cache_valid(
            'binary'         => $binary,
            'datastore_file' => $datastore_file,
            'ttl'            => $ttl,
            'mtime'          => $mtime
        )
    ) {
        return $MEMORY_CACHE{$datastore_file}->{'contents'};
    }

    my ( $datastore_file_size, $datastore_file_mtime ) = ( stat($datastore_file) )[ 7, 9 ];
    my $data_mtime;

    my ( $used_cache, $res );
    if (
        Cpanel::CachedCommand::Valid::is_cache_valid(
            'binary'               => $binary,
            'datastore_file'       => $datastore_file,
            'datastore_file_mtime' => $datastore_file_mtime,
            'ttl'                  => $ttl,
            'mtime'                => $mtime,
            'min_expire_time'      => $min_expire_time,
        )
    ) {
        $res        = Cpanel::LoadFile::loadfile_r( $datastore_file, { 'skip_exists_check' => 1 } );
        $data_mtime = $datastore_file_mtime;
        if ( $res && ( !$regexcheck || $$res =~ m/$regexcheck/ ) ) {
            $used_cache = 1;
        }
    }

    if ( !$used_cache ) {
        $data_mtime = _time();

        $res = $get_result_cr->( { binary => $binary, args => \@AG } );

        if ( !$regexcheck || ( defined $res && ( ref $res ? $$res : $res ) =~ m/$regexcheck/ ) ) {
            print STDERR "_cached_command: writing datastore file: $datastore_file " . ( $regexcheck ? "regex_check: $regexcheck" : '' ) . "\n" if $Cpanel::Debug::level;

            require Cpanel::CachedCommand::Save;
            Cpanel::CachedCommand::Save::_savefile( $datastore_file, $res );
        }
        else {
            print STDERR "_cached_command: failed regex check NOT writing datastore file: $datastore_file " . ( $regexcheck ? "regex_check: $regexcheck" : '' ) . "\n" if $Cpanel::Debug::level;
        }
    }

    return _cache_res_if_needed( $res, $ttl, $datastore_file, $data_mtime );
}

sub _cache_res_if_needed {
    my ( $res, $ttl, $datastore_file, $data_mtime ) = @_;

    if ( ref $res ) {
        if ( $ttl && ( !defined $$res || length($$res) < 32768 ) ) { $MEMORY_CACHE{$datastore_file} = { 'mtime' => $data_mtime, 'contents' => $res }; }
        return $res;
    }
    else {
        if ( $ttl && ( !defined $res || length($res) < 32768 ) ) { $MEMORY_CACHE{$datastore_file} = { 'mtime' => $data_mtime, 'contents' => \$res }; }
        return \$res;
    }
}

sub _default_get_result_cr {
    my ($opts) = @_;

    return _get_cmd_output( 'program' => $opts->{binary}, 'args' => $opts->{args}, 'stderr' => \*STDERR );
}

sub _get_memory_cache {
    return \%MEMORY_CACHE;
}

sub _time {
    return time();
}

sub _get_cmd_output {
    my (@key_val) = @_;

    return eval {
        require Cpanel::SafeRun::Object;
        my $run = Cpanel::SafeRun::Object->new(@key_val);
        $run->stdout();
    };
}


sub has_cache {
    my ( $ttl, $bin, @AG ) = @_;
    my @SAFEAG = @AG;
    if ( scalar @SAFEAG > 3 ) {
        splice( @SAFEAG, 3 );
    }
    my $datastore_file = Cpanel::CachedCommand::Utils::_get_datastore_filename( $bin, @SAFEAG );
    return (
        Cpanel::CachedCommand::Valid::is_cache_valid(
            'datastore_file' => $datastore_file,
            'binary'         => $bin,
            'ttl'            => $ttl
        )
    ) ? 1 : 0;
}

sub cachedcommand {
    my ( $binary, @ARGS ) = @_;

    my $cache_ref = _cached_cmd(
        'binary'     => $binary,
        'regexcheck' => qr/./,     # only cache data that actually exists
        'args'       => \@ARGS
    );
    if ( ref $cache_ref eq 'SCALAR' ) { return $$cache_ref; }
    return $cache_ref;
}

sub cachedcommand_no_errors {
    my (%OPTS) = @_;

    return _cached_cmd(
        binary => $OPTS{'binary'},
        args   => $OPTS{'args'},
        ( defined $OPTS{'mtime'} ? ( mtime => $OPTS{'mtime'} ) : () ),
        ( defined $OPTS{'ttl'}   ? ( ttl   => $OPTS{'ttl'} )   : () ),
        get_result_cr => sub {
            my ($opts) = @_;

            return _get_cmd_output( 'program' => $opts->{binary}, 'args' => $opts->{args}, ( $OPTS{ttl} ? ( 'timeout' => $OPTS{ttl}, 'read_timeout' => $OPTS{ttl} ) : () ) );
        }
    );
}

sub cachedcommand_multifile {
    my ( $test_file_ar, $binary, @ARGS ) = @_;
    my ( $mtime, $ctime ) = Cpanel::StatCache::cachedmtime_ctime($binary);
    if ( $ctime > $mtime ) {
        $mtime = $ctime;
    }
    foreach my $file (@$test_file_ar) {
        my @test_times = Cpanel::StatCache::cachedmtime_ctime($file);
        foreach my $new_time (@test_times) {
            if ( $new_time > $mtime ) {
                $mtime = $new_time;
            }
        }
    }
    my $cache_ref = _cached_cmd(
        'binary' => $binary,
        'args'   => \@ARGS,
        'mtime'  => $mtime
    );
    if ( ref $cache_ref eq 'SCALAR' ) { return $$cache_ref; }
    return $cache_ref;
}

sub cachedmcommand {
    my ( $ttl, $binary, @ARGS ) = @_;
    my $cache_ref = _cached_cmd(
        'ttl'    => $ttl,
        'binary' => $binary,
        'args'   => \@ARGS
    );
    if ( ref $cache_ref eq 'SCALAR' ) { return $$cache_ref; }
    return $cache_ref;
}

sub cachedmcommand_r_cleanenv {
    my ( $ttl, $binary, @ARGS ) = @_;
    my $cache_ref = _cached_cmd(
        'ttl'           => $ttl,
        'binary'        => $binary,
        'args'          => \@ARGS,
        'get_result_cr' => sub {
            my ($opts) = @_;

            require Cpanel::SafeRun::Env;
            return Cpanel::SafeRun::Env::saferun_r_cleanenv( $opts->{binary}, @{ $opts->{args} } );
        },
    );
    if ( ref $cache_ref ne 'SCALAR' ) { return \$cache_ref; }
    return $cache_ref;
}

sub cachedmcommand_cleanenv2 {
    my ( $ttl, $args_hr ) = @_;
    my @cmd       = @{ $args_hr->{'command'} };
    my $binary    = shift @cmd;
    my @ARGS      = @cmd;
    my $cache_ref = _cached_cmd(
        'ttl'           => $ttl,
        'binary'        => $binary,
        'args'          => \@ARGS,
        'get_result_cr' => sub {

            require Cpanel::SafeRun::Env;
            return Cpanel::SafeRun::Env::saferun_cleanenv2($args_hr);
        },
    );
    return $cache_ref;
}

sub cachedmcommand_r {
    my ( $ttl, $binary, @ARGS ) = @_;
    my $cache_ref = _cached_cmd(
        'ttl'    => $ttl,
        'binary' => $binary,
        'args'   => \@ARGS
    );
    if ( ref $cache_ref ne 'SCALAR' ) { return \$cache_ref; }
    return $cache_ref;
}

sub cachedmcommand2 {
    my $arg_ref = shift;

    my $bin        = $arg_ref->{'bin'};
    my $ttl        = $arg_ref->{'age'};
    my $timer      = $arg_ref->{'timer'};
    my $exact      = $arg_ref->{'exact'};
    my $regexcheck = $arg_ref->{'regexcheck'};
    my @AG         = @{ $arg_ref->{'ARGS'} };

    my $cache_ref = _cached_cmd(
        'binary'        => $bin,
        'ttl'           => $ttl,
        'exact'         => $exact,
        'regexcheck'    => $regexcheck,
        'args'          => \@AG,
        'get_result_cr' => sub {
            my ($opts) = @_;

            return _get_cmd_output( 'program' => $opts->{binary}, 'args' => $opts->{'args'}, 'stderr' => \*STDERR, ( int($timer) > 0 ? ( 'timeout' => $timer, 'read_timeout' => $timer ) : () ) );
        },
    );
    if ( ref $cache_ref eq 'SCALAR' ) { return $$cache_ref; }
    return $cache_ref;
}

sub noncachedcommand {
    my ( $bin, @AG ) = @_;

    if ( substr( $bin, 0, 1 ) eq '/' && !-x $bin ) {
        return "$bin is missing or not executable";
    }
    my $datastore_file = Cpanel::CachedCommand::Utils::_get_datastore_filename( $bin, $AG[0] );

    if ( -e $datastore_file ) {
        unlink $datastore_file;
    }

    return _get_cmd_output( 'program' => $bin, 'args' => \@AG );
}

sub retrieve {
    my %OPTS = @_;
    return Cpanel::LoadFile::loadfile( Cpanel::CachedCommand::Utils::_get_datastore_filename( $OPTS{'name'} ) );
}

sub clear_memory_cache {
    %MEMORY_CACHE = ();
}

1;

} # --- END Cpanel/CachedCommand.pm


{ # --- BEGIN Cpanel/GlobalCache.pm
package Cpanel::GlobalCache;


use strict;

# use Cpanel::JSON::FailOK ();

my $GCACHEref = {};
our $PRODUCT_CONF_DIR = '/var/cpanel';

sub get_cache_mtime {
    my ($cachename) = @_;
    if ( !exists $GCACHEref->{$cachename} ) { load_cache($cachename); }
    return $GCACHEref->{$cachename}{'mtime'};
}

sub load_cache {
    my ($cachename) = @_;
    if ( open( my $cache_fh, '<', "$PRODUCT_CONF_DIR/globalcache/$cachename.cache" ) ) {
        $GCACHEref->{$cachename} ||= {};
        my $cache_ref = $GCACHEref->{$cachename};

        require Cpanel::JSON;
        $cache_ref->{'data'} = Cpanel::JSON::FailOK::LoadFile($cache_fh);

        if ( ref $cache_ref->{'data'} eq 'HASH' ) {
            $cache_ref->{'mtime'} = ( stat($cache_fh) )[9];
        }
        else {
            $cache_ref->{'data'} = {};
        }
        close($cache_fh);
    }
    return;
}

sub cachedmcommand {    ## no critic(RequireArgUnpacking)
    my $cachename = shift;

    require Cpanel::CachedCommand;

    if ( !exists $GCACHEref->{$cachename} ) { load_cache($cachename); }
    my $cache_max_mtime = shift;
    my $key             = join( '_', @_ );
    return (
        ( exists $GCACHEref->{$cachename}{'data'}{'command'}{$key} && ( $cache_max_mtime + $GCACHEref->{$cachename}{'mtime'} ) > time() )
        ? $GCACHEref->{$cachename}{'data'}{'command'}{$key}
        : 'Cpanel::CachedCommand'->can('cachedmcommand')->( $cache_max_mtime, @_ )
    );
}

sub cachedcommand {    ## no critic(RequireArgUnpacking)
    my $cachename = shift;

    require Cpanel::CachedCommand;
    require Cpanel::StatCache;

    if ( !exists $GCACHEref->{$cachename} ) { load_cache($cachename); }
    my ( $file_mtime, $file_ctime ) = 'Cpanel::StatCache'->can('cachedmtime_ctime')->( $_[0] );
    my $key = join( '_', @_ );
    return (
        ( exists $GCACHEref->{$cachename}{'data'}{'command'}{$key} && $GCACHEref->{$cachename}{'mtime'} > $file_mtime && $GCACHEref->{$cachename}{'mtime'} > $file_ctime )
        ? $GCACHEref->{$cachename}{'data'}{'command'}{$key}
        : 'Cpanel::CachedCommand'->can('cachedcommand')->(@_)
    );
}

sub loadfile {
    my $cachename = shift;
    if ( !exists $GCACHEref->{$cachename} ) { load_cache($cachename); }
    my $file       = shift;
    my $file_mtime = shift;
    unless ( defined $file_mtime ) {
        $file_mtime = ( stat($file) )[9] || 0;
    }

    require Cpanel::LoadFile;
    return (
        ( exists $GCACHEref->{$cachename}{'data'}{'file'}{$file} && $GCACHEref->{$cachename}{'mtime'} > $file_mtime )
        ? $GCACHEref->{$cachename}{'data'}{'file'}{$file}
        : 'Cpanel::LoadFile'->can('loadfile')->($file)
    );
}

sub data {
    my $cachename = shift;
    if ( !exists $GCACHEref->{$cachename} ) { load_cache($cachename); }
    my $data       = shift;
    my $test_mtime = shift || 0;

    return ( ( exists $GCACHEref->{$cachename}{'data'}{'data'}{$data} && $GCACHEref->{$cachename}{'mtime'} > $test_mtime ) ? $GCACHEref->{$cachename}{'data'}{'data'}{$data} : undef );
}

sub clearcache {
    $GCACHEref = {};
    return;
}

sub default_product_dir {
    $PRODUCT_CONF_DIR = shift if @_;
    return $PRODUCT_CONF_DIR;
}

1;

} # --- END Cpanel/GlobalCache.pm


{ # --- BEGIN Cpanel/IP/Loopback.pm
package Cpanel::IP::Loopback;


use strict;
use warnings;

sub is_loopback {
    return (
        length $_[0]
          && (
            $_[0] eq 'localhost'                                          #
            || $_[0] eq 'localhost.localdomain'                           #
            || $_[0] eq '0000:0000:0000:0000:0000:0000:0000:0001'         #
            || index( $_[0], '0000:0000:0000:0000:0000:ffff:7f' ) == 0    # ipv4 inside of ipv6 match 127.*
            || index( $_[0], '::ffff:127.' ) == 0                         # ipv4 inside of ipv6 match 127.*
            || index( $_[0], '127.' ) == 0                                # 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;
}

1;

} # --- END Cpanel/IP/Loopback.pm


{ # --- BEGIN Cpanel/MysqlUtils/MyCnf/Basic.pm
package Cpanel::MysqlUtils::MyCnf::Basic;


use strict;

# use Cpanel::LoadFile     ();
# use Cpanel::LoadModule   ();
# use Cpanel::IP::Loopback ();

our $VERSION = '1.3';

our %MYDBCACHE;
our %HOMECACHE;
our $VAR_MYSQL = '/var/lib/mysql/mysql.sock';

our $_SYSTEM_MY_CNF = '/etc/my.cnf';

sub get_mycnf {
    my $loadConfig = _getloadConfig_coderef();
    return $loadConfig->( $_SYSTEM_MY_CNF, undef, '\s*=\s*', '^\s*[#;]', 0, 1 );
}

*getloadConfig_coderef = \&_getloadConfig_coderef;

sub _getloadConfig_coderef {
    my $module;
    if ( exists $INC{'Cpanel/Config/LoadConfig.pm'} ) {
        $module = 'Cpanel::Config::LoadConfig';
    }
    else {
        Cpanel::LoadModule::lazy_load_module('Cpanel::Config::LoadConfig::Tiny');
        $module = 'Cpanel::Config::LoadConfig::Tiny';
    }

    return $module->can('loadConfig');
}

sub _getmydb_param {
    my ( $param, $file ) = @_;

    if ( !$param || !$file ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Logger');
        my $logger = 'Cpanel::Logger'->new();
        $logger->warn('Missing arguments');
        return;
    }

    my $value;
    my ( $file_size, $file_mtime ) = ( stat($file) )[ 7, 9 ];

    if ($file_mtime) {
        if ( !exists $MYDBCACHE{$file} || $MYDBCACHE{$file}->{'mtime'} != $file_mtime || $MYDBCACHE{$file}->{'size'} != $file_size ) {
            my $loadConfig_module = _getloadConfig_coderef();
            my $data              = $loadConfig_module->( $file, undef, '\s*=\s*', '^\s*[#;]', 0, 1 );
            if ($data) {
                $MYDBCACHE{$file} = {
                    'data'  => $data,
                    'mtime' => $file_mtime,
                    'size'  => $file_size,
                };
            }
        }

        if ( exists $MYDBCACHE{$file} && ref $MYDBCACHE{$file} && ref $MYDBCACHE{$file}{'data'} && $MYDBCACHE{$file}{'data'}{$param} ) {
            $value = $MYDBCACHE{$file}->{'data'}->{$param};
            $value =~ s{ (?: \A \s* ["'] | ["']\s* \z ) }{}xmsg;
        }
    }

    return $value;
}

sub get_dot_my_dot_cnf {
    my $user = shift || 'root';
    my $homedir;
    if ( exists $HOMECACHE{$user} ) {
        $homedir = $HOMECACHE{$user};
    }
    else {
        require Cpanel::PwCache;
        $HOMECACHE{$user} = $homedir = Cpanel::PwCache::gethomedir($user);
    }

    return $homedir . '/.my.cnf';

}

sub _getmydbparm {
    my ( $param, $user ) = @_;
    my $uid;

    if ( !$user ) {
        $uid //= $>;
        $user = 'root' if $uid == 0;
        if ( !$user ) {
            require Cpanel::PwCache;
            $user = Cpanel::PwCache::getusername();
        }
    }

    my $privs_obj;
    if ( $user ne 'root' && ( $uid //= $> ) == 0 ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::AccessIds::ReducedPrivileges');
        $privs_obj = 'Cpanel::AccessIds::ReducedPrivileges'->new($user);
    }

    return _getmydb_param( $param, get_dot_my_dot_cnf($user) );
}


sub getmydbsocket {    ## no critic qw(Subroutines::RequireArgUnpacking)


    my $socket = _getmydbparm( 'socket', @_ );

    if ( $socket && -S $socket ) {
        return $socket;
    }

    my @potential_sockets;
    my $conf = Cpanel::LoadFile::load_if_exists($_SYSTEM_MY_CNF);

    if ( length $conf && index( $conf, 'socket' ) > -1 ) {

        Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::MyCnf::Full');

        my $ref = 'Cpanel::MysqlUtils::MyCnf::Full'->can('etc_my_cnf')->( $_SYSTEM_MY_CNF, $conf );

        if ($ref)    # theoretically /etc/my.cnf does not exist
        {

            push @potential_sockets, $ref->{'client'}->{'socket'} if length $ref->{'client'}->{'socket'};
            push @potential_sockets, $ref->{'mysql'}->{'socket'}  if length $ref->{'mysql'}->{'socket'};
            push @potential_sockets, $ref->{'mysqld'}->{'socket'} if length $ref->{'mysqld'}->{'socket'};
        }
    }

    push @potential_sockets, $VAR_MYSQL;

    my %MTIME_CACHE;
    foreach my $check_socket (@potential_sockets) {
        if ( -S $check_socket ) {
            $MTIME_CACHE{$check_socket} = ( stat(_) )[9];
        }
    }
    foreach my $newest_socket ( sort { $MTIME_CACHE{$b} <=> $MTIME_CACHE{$a} || ( -l $a ? ( -l $b ? 0 : 1 ) : -1 ) || $a cmp $b } keys %MTIME_CACHE ) {
        return $newest_socket;
    }

    return;
}

sub getmydbuser {
    return _getmydbparm( 'user', @_ );
}

sub getmydbpass {
    my $password = _getmydbparm( 'pass', @_ ) || _getmydbparm( 'password', @_ );

    return defined $password && utf8::decode($password) ? $password : undef;
}

sub getmydbhost {
    my $host = _getmydbparm( 'host', @_ );

    if ( !$host && $> != 0 ) {

        Cpanel::LoadModule::load_perl_module('Cpanel::AdminBin');
        $host = 'Cpanel::AdminBin'->can('adminrun')->( 'cpmysql', 'GETHOST' );
    }

    return $host;
}

sub getmydbport { return _getmydbparm( 'port', @_ ); }

sub get_grant_host {
    if ( is_remote_mysql() ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Sys::Hostname');
        Cpanel::Sys::Hostname::gethostname();
    }
    return 'localhost';
}

sub get_server {
    if ( !is_remote_mysql() ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::DIp::MainIP');
        return Cpanel::DIp::MainIP::getmainserverip();
    }
    else {
        my $server = getmydbhost('root');
        Cpanel::LoadModule::load_perl_module('Cpanel::SocketIP');
        return Cpanel::SocketIP::_resolveIpAddress($server);
    }
}

sub is_local_mysql {
    my $mysql_host = shift || getmydbhost('root') || 'localhost';
    return is_remote_mysql($mysql_host) ? 0 : 1;
}

sub is_remote_mysql {
    my $host = shift || getmydbhost('root');
    return 0 if !$host;
    return 0 if Cpanel::IP::Loopback::is_loopback($host);
    Cpanel::LoadModule::load_perl_module('Cpanel::Domain::Local');
    return ( $host && !Cpanel::Domain::Local::domain_or_ip_is_on_local_server($host) ) ? 1 : 0;
}

sub get_server_version {
    my ($dbh) = @_;

    return $dbh->selectrow_array('SELECT VERSION()');
}

sub clear_cache {
    %MYDBCACHE = ();
    return;
}
1;

} # --- END Cpanel/MysqlUtils/MyCnf/Basic.pm


{ # --- BEGIN Cpanel/Analytics/Config.pm



package Cpanel::Analytics::Config;

use strict;
use warnings;



sub ANALYTICS_USER { return q{cpanelanalytics} }


sub ANALYTICS_PID_FILE { return q{/var/cpanel/analytics/run/cpanalyticsd.pid} }


sub ANALYTICS_DIR { return q{/var/cpanel/analytics} }


sub ANALYTICS_DATA_DIR { return ANALYTICS_DIR() . q{/data} }


sub ANALYTICS_LOGS_DIR { return ANALYTICS_DIR() . q{/logs} }


sub ANALYTICS_RUN_DIR { return ANALYTICS_DIR() . q{/run} }


sub ANALYTICS_SOCKET { return ANALYTICS_RUN_DIR() . q{/socket} }


sub ERROR_LOG { return ANALYTICS_LOGS_DIR() . q{/error.log} }


sub OPERATIONS_LOG {
    my ($facility) = @_;
    $facility //= 'operations';
    return ANALYTICS_DATA_DIR() . qq{/$facility.log};
}


sub OPERATIONS_LOG_LOCK { return ANALYTICS_RUN_DIR() . q{/operations.log.lock} }


sub SYSTEM_ID_NAME { return q{system_id} }


sub SYSTEM_ID_PATH { return ANALYTICS_DIR() . '/' . SYSTEM_ID_NAME() }


sub FEATURE_TOGGLES_DIR { return q{/var/cpanel/feature_toggles} }


sub TOUCH_FILE { return FEATURE_TOGGLES_DIR() . q{/analytics} }


sub SERVICE_MANAGER_TOUCH_FILE { return FEATURE_TOGGLES_DIR() . q{/analytics_service_manager} }


sub UI_INCLUDES_TOUCH_FILE { return FEATURE_TOGGLES_DIR() . q{/analytics_ui_includes} }

1;

} # --- END Cpanel/Analytics/Config.pm


{ # --- BEGIN Cpanel/Analytics/Enabled.pm

package Cpanel::Analytics::Enabled;

use strict;
use warnings;

# use Cpanel::Analytics::Config ();


my $_is_enabled;

sub is_enabled {
    return ( $_is_enabled //= -e Cpanel::Analytics::Config::TOUCH_FILE() ? 1 : 0 );
}

sub clear_cache {
    return undef $_is_enabled;
}

1;

} # --- END Cpanel/Analytics/Enabled.pm


{ # --- BEGIN Cpanel/Config/LoadConfig/Tiny.pm
package Cpanel::Config::LoadConfig::Tiny;


use strict;
use warnings;



our $_ENOENT = 2;

sub loadConfig {    ## no critic qw(RequireArgUnpacking ProhibitExcessComplexity)
    my ( $file, $conf_ref, $delimiter, $comment, $pretreatline, $allow_undef_values, $arg_ref ) = (
        $_[0],
        $_[1] || -1,
        ( defined $_[2] ? $_[2] : '=' ),
        ( $_[3] || '^\s*[#;]' ),
        ( $_[4] || 0 ),
        ( $_[5] || 0 ),
        $_[6]
    );


    my $use_reverse          = 0;
    my $use_hash_of_arr_refs = 0;

    die('loadConfig requires valid filename') if !$file || $file =~ tr/\0//;

    if ( defined($arg_ref) && exists( $arg_ref->{'use_reverse'} ) ) {
        $use_reverse = $arg_ref->{'use_reverse'};
    }
    if ( $use_reverse == 0 ) {
        delete $arg_ref->{'use_reverse'};    # should not have been sent -- delete to prevent dupe caching
    }

    if ( exists( $arg_ref->{'use_hash_of_arr_refs'} ) && defined( $arg_ref->{'use_hash_of_arr_refs'} ) ) {
        $use_hash_of_arr_refs = $arg_ref->{'use_hash_of_arr_refs'};
    }
    if ( $use_hash_of_arr_refs == 0 ) {
        delete $arg_ref->{'use_hash_of_arr_refs'};    #should not have been sent -- delete to prevent dupe caching
    }
    my $limit = exists $arg_ref->{'limit'} ? int( $arg_ref->{'limit'} || 0 ) : 0;

    $conf_ref = {} if !ref $conf_ref;
    my $key_value_text = $use_reverse ? '1,0' : '0,1';

    my $fh;

    if ( open( $fh, '<', $file ) ) {
        local $/;

        my $parser_code;

        if ( $use_hash_of_arr_refs || $pretreatline || $allow_undef_values || !length $delimiter ) {
            $parser_code = '
            my ($keys, $name, $value);
LINELOOP:
            foreach my $line (split(/\r?\n/, readline($fh) )) {' . "\n"
              . q{next LINELOOP if $line eq '';} . "\n"
              . ( $comment              ? q{next LINELOOP if ( $line =~ m/$comment/o );}                                                                                       : '' ) . "\n"
              . ( $limit                ? q{last if $keys++ == } . $limit . ';'                                                                                                : '' ) . "\n"
              . ( $pretreatline         ? q{$line =~ s/$pretreatline//go;}                                                                                                     : '' ) . "\n"
              . ( length $delimiter     ? ( $use_reverse ? q{( $value, $name ) = split( /$delimiter/, $line, 2 );} : q{( $name, $value ) = split( /$delimiter/, $line, 2 );} ) : q{($name,$value) = ($line,1);} ) . "\n"
              . ( !$allow_undef_values  ? q{ next LINELOOP if !defined($value); }                                                                                              : '' ) . "\n"
              . ( $use_hash_of_arr_refs ? q{ push @{ $conf_ref->{$name} }, $value; }                                                                                           : q{ $conf_ref->{$name} = $value; } ) . '
           }';
        }
        elsif ($comment) {
            $parser_code = 'my ($k, $v, $count); %{$conf_ref}=(  %$conf_ref, map { ' . 'if (m{' . $comment . '}) { (); } else { ' . '($k,$v) = (split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . ']; ' . ( $limit ? ' $count++ < $limit && ' : '' ) . 'defined($v) ? ($k,$v) : (); ' . '} } split(/\r?\n/, readline($fh) ) )';
        }
        else {
            $parser_code = 'my ($k, $v); %{$conf_ref}=(  %$conf_ref, map { ' . '($k,$v) = (split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . ']; ' . ( $limit ? ' $count++ < $limit && ' : '' ) . 'defined($v) ? ($k,$v) : () ' . '} split(/\r?\n/, readline($fh) ) )';
        }

        eval $parser_code;    ## no critic qw(StringyEval)

        if ($@) {
            die "Failed to parse $file: $@";
        }
    }
    elsif ( $! != $_ENOENT ) {
        warn "open(<$file): $!";
    }

    return wantarray ? %{$conf_ref} : $conf_ref;
}
1;

} # --- END Cpanel/Config/LoadConfig/Tiny.pm


{ # --- BEGIN Cpanel/GreyList/Config.pm
package Cpanel::GreyList::Config;


use strict;
use warnings;

my $CONF_DIR              = '/var/cpanel/greylist';
my $PID_FILE              = '/var/run/cpgreylistd.pid';
my $SOCKET_PATH           = '/var/run/cpgreylistd.sock';
my $SQLITE_DB             = $CONF_DIR . '/greylist.sqlite';
my $ENABLE_FILE           = $CONF_DIR . '/enabled';
my $CONF_FILE             = $CONF_DIR . '/conf';
my $COMMON_MAIL_CONF_FILE = $CONF_DIR . '/common_mail_providers_conf';

my $LOGFILE_PATH = '/usr/local/cpanel/logs/cpgreylistd.log';

use constant DEFAULT => {
    'initial_block_time_mins' => 5,              # 5 mins
    'must_try_time_mins'      => 4 * 60,         # 4 hrs
    'record_exp_time_mins'    => 3 * 24 * 60,    # 3 days
    'spf_bypass'              => 0,              # Skip greylisting if SPF check passes
    'purge_interval_mins'     => 60,             # 1 hr
    'child_timeout_secs'      => 5,              # 5 seconds
    'max_child_procs'         => 5,              # max number of children the daemon will fork to process requests
};


sub get_conf_dir              { return $CONF_DIR; }
sub get_pid_file              { return $PID_FILE; }
sub get_socket_path           { return $SOCKET_PATH; }
sub get_sqlite_db             { return $SQLITE_DB; }
sub get_conf_file             { return $CONF_FILE; }
sub get_common_mail_conf_file { return $COMMON_MAIL_CONF_FILE; }
sub get_logfile_path          { return $LOGFILE_PATH; }
sub get_enable_file           { return $ENABLE_FILE; }

sub get_purge_interval_mins { return loadconfig()->{'purge_interval_mins'}; }
sub get_child_timeout_secs  { return loadconfig()->{'child_timeout_secs'}; }
sub get_max_child_procs     { return loadconfig()->{'max_child_procs'}; }

sub is_enabled { return -e get_enable_file() ? 1 : 0 }

sub enable {
    if ( !-d get_conf_dir() ) {
        require File::Path;
        File::Path::make_path( get_conf_dir() );
    }

    require Cpanel::FileUtils::TouchFile;
    Cpanel::FileUtils::TouchFile::touchfile( get_enable_file() );
    return 1;
}

sub disable {
    if ( -e get_enable_file() ) {
        unlink( get_enable_file() ) && return 1;
        return;
    }
    return 1;
}

sub load_common_mail_providers_config {
    my $default_config_hr = shift;
    die Cpanel::Exception->create('The default common mail provider configuration is not set.') if !$default_config_hr || ref $default_config_hr ne 'HASH';

    $default_config_hr->{'autotrust_new_common_mail_providers'} = 1;

    _any_loadConfig( get_common_mail_conf_file(), $default_config_hr );

    return $default_config_hr;
}

sub save_common_mail_providers_config {
    my ( $default_config_hr, $new_config_hr ) = @_;

    my $valid_mail_providers = { %{$default_config_hr} };
    my $config_hr            = load_common_mail_providers_config($default_config_hr);

    my $is_boolean = sub { return 1 if ( defined $_[0] && ( $_[0] eq '1' || $_[0] eq '0' ) ); return; };
    foreach my $key ( keys %{$new_config_hr} ) {
        exists $config_hr->{$key}               or die Cpanel::Exception->create( "Invalid configuration option: “[_1]” is not a supported common mail provider.", [$key] );
        $is_boolean->( $new_config_hr->{$key} ) or die Cpanel::Exception->create( "Invalid configuration value: “[_1]” for “[_2]”.",                               [ $new_config_hr->{$key}, $key ] );
    }

    foreach my $key ( keys %{$config_hr} ) {
        next if not exists $valid_mail_providers->{$key} && $key ne 'autotrust_new_common_mail_providers';
        if ( !exists $new_config_hr->{$key} || !defined $new_config_hr->{$key} ) {
            $new_config_hr->{$key} = $config_hr->{$key};
        }
    }

    require Cpanel::Config::FlushConfig;
    Cpanel::Config::FlushConfig::flushConfig( get_common_mail_conf_file(), $new_config_hr, undef, undef, { 'perms' => 0600 } ) or die Cpanel::Exception->create( "Failed to save configuration file: [_1]", [$!] );
    return 1;
}

our $_conf_cache_ref;

sub loadconfig {

    my $config = { %{ DEFAULT() } };

    my $filesys_mtime = 0;
    if ( -e get_conf_file() ) {
        $filesys_mtime = ( stat(_) )[9];
    }

    if ( $_conf_cache_ref && exists $_conf_cache_ref->{'mtime'} && $filesys_mtime == $_conf_cache_ref->{'mtime'} ) {
        return $_conf_cache_ref->{'conf'};
    }

    _any_loadConfig( get_conf_file(), $config );
    $config->{'is_enabled'} = is_enabled() . "";

    $_conf_cache_ref = { 'mtime' => $filesys_mtime, 'conf' => $config };

    return $config;
}

sub saveconfig {
    my $new_config_hr = shift || {};
    my $old_config_hr = loadconfig();

    my $is_positive_int            = sub { return 1 if ( $_[0] && $_[0] =~ m/^\d+$/ );                        return; };
    my $is_digit_and_less_than_max = sub { return 1 if ( $_[0] && $_[0] =~ m/^\d+$/ && $_[0] <= $_[1] );      return; };
    my $is_boolean                 = sub { return 1 if ( defined $_[0] && ( $_[0] eq '1' || $_[0] eq '0' ) ); return; };

    require Cpanel::Locale;
    require Cpanel::Exception;
    require Cpanel::Config::FlushConfig;
    my $locale         = Cpanel::Locale->get_handle();
    my $config_options = {
        'initial_block_time_mins' => {
            'validation' => $is_digit_and_less_than_max,
            'desc'       => $locale->maketext('Initial Deferral Period'),
            'max'        => 4 * 60,                                         # 4 hrs
        },
        'must_try_time_mins' => {
            'validation' => $is_digit_and_less_than_max,
            'desc'       => $locale->maketext('Resend Acceptance Period'),
            'max'        => 24 * 60,                                         # 24 hrs
        },
        'record_exp_time_mins' => {
            'validation' => $is_digit_and_less_than_max,
            'desc'       => $locale->maketext('Record Expiration Time'),
            'max'        => 30 * 24 * 60,                                    # 30 days
        },
        'spf_bypass' => {
            'validation' => $is_boolean,
            'desc'       => $locale->maketext('Bypass [asis,Greylisting] for Hosts with Valid [output,acronym,SPF,Sender Policy Framework] Records'),
        },
        'purge_interval_mins' => {
            'validation' => $is_positive_int,
            'desc'       => $locale->maketext('Record Purge Interval'),
        },
        'child_timeout_secs' => {
            'validation' => $is_positive_int,
            'desc'       => $locale->maketext('Child process time-out.'),
        },
        'max_child_procs' => {
            'validation' => $is_positive_int,
            'desc'       => $locale->maketext('Maximum number of processes the [asis,GreyListing] daemon can create.'),
        },
    };

    foreach my $key ( keys %{$new_config_hr} ) {
        if (   exists $config_options->{$key}
            && exists $config_options->{$key}->{'validation'}
            && !$config_options->{$key}->{'validation'}->( $new_config_hr->{$key}, $config_options->{$key}->{'max'} ) ) {
            die Cpanel::Exception->create(
                "Invalid configuration value, “[_1]” for “[_2]” (max: [_3]).",
                [ $new_config_hr->{$key}, $config_options->{$key}->{'desc'}, ( $config_options->{$key}->{'max'} || 'n/a' ) ]
            );
        }
    }
    foreach my $key ( keys %{$config_options} ) {
        if ( !exists $new_config_hr->{$key} || !defined $new_config_hr->{$key} ) {
            $new_config_hr->{$key} = $old_config_hr->{$key};
        }
    }
    delete $new_config_hr->{'is_enabled'};

    if ( $new_config_hr->{'initial_block_time_mins'} >= $new_config_hr->{'must_try_time_mins'} ) {
        die Cpanel::Exception->create(
            "Invalid configuration value, “[_1]” cannot be greater than or equal to the “[_2]” value: [_3]",
            [ $config_options->{'initial_block_time_mins'}->{'desc'}, $config_options->{'must_try_time_mins'}->{'desc'}, $new_config_hr->{'must_try_time_mins'} ]
        );
    }
    elsif ( $new_config_hr->{'initial_block_time_mins'} >= $new_config_hr->{'record_exp_time_mins'} ) {
        die Cpanel::Exception->create(
            "Invalid configuration value, “[_1]” cannot be greater than or equal to the “[_2]” value: [_3]",
            [ $config_options->{'initial_block_time_mins'}->{'desc'}, $config_options->{'record_exp_time_mins'}->{'desc'}, $new_config_hr->{'record_exp_time_mins'} ]
        );
    }
    elsif ( $new_config_hr->{'must_try_time_mins'} >= $new_config_hr->{'record_exp_time_mins'} ) {
        die Cpanel::Exception->create(
            "Invalid configuration value, “[_1]” cannot be greater than or equal to the “[_2]” value: [_3]",
            [ $config_options->{'must_try_time_mins'}->{'desc'}, $config_options->{'record_exp_time_mins'}->{'desc'}, $new_config_hr->{'record_exp_time_mins'} ]
        );
    }

    Cpanel::Config::FlushConfig::flushConfig( get_conf_file(), $new_config_hr, undef, undef, { 'perms' => 0600 } ) or die Cpanel::Exception->create( "Failed to save configuration file: [_1]", [$!] );
    return 1;
}

sub _any_loadConfig {
    if ( $INC{'Cpanel/Config/LoadConfig.pm'} ) {
        goto \&Cpanel::Config::LoadConfig::loadConfig;
    }
    require Cpanel::Config::LoadConfig::Tiny;
    goto \&Cpanel::Config::LoadConfig::Tiny::loadConfig;
}

1;

} # --- END Cpanel/GreyList/Config.pm


{ # --- BEGIN Cpanel/Config/Hulk.pm
package Cpanel::Config::Hulk;


use strict;
use warnings;

our $WHITE_LIST_TYPE         = 1;
our $BLACK_LIST_TYPE         = 2;
our $COUNTRY_WHITE_LIST_TYPE = 3;
our $COUNTRY_BLACK_LIST_TYPE = 4;

our $LOGIN_TYPE_USER_SERVICE_BRUTE = -4;
our $LOGIN_TYPE_EXCESSIVE_BRUTE    = -3;
our $LOGIN_TYPE_BRUTE              = -2;
our $LOGIN_TYPE_FAILED             = -1;
our $LOGIN_TYPE_GOOD               = 1;

our $MAX_LENGTH = 6;

our %LIST_TYPES = (
    $WHITE_LIST_TYPE => 'white',
    $BLACK_LIST_TYPE => 'black'
);

our %LIST_TYPE_VALUES = reverse %LIST_TYPES;

our $HTTP_PORT = 579;

our $conf_dir     = '/var/cpanel/hulkd';
our $app_key_path = '/var/cpanel/cphulkd/keys';
our $socket       = '/var/run/cphulkd.sock';
our $dbsocket     = '/var/run/cphulkd_db.sock';

sub get_sqlite_db { return "$conf_dir/cphulk.sqlite"; }

sub get_cache_dir { return "$conf_dir/cache"; }

sub get_debug_file {
    return -e "$conf_dir/debug" ? "$conf_dir/debug" : '/var/cpanel/hulk_debug';
}

sub get_auth_file {
    my $auth_file = "$conf_dir/password";
    return -e $auth_file ? $auth_file : -e '/var/cpanel/hulkdpass' ? '/var/cpanel/hulkdpass' : $auth_file;
}

sub get_conf_file {
    my $conf_file = "$conf_dir/conf";

    return -e $conf_file ? $conf_file : -e '/var/cpanel/cphulk.conf' ? '/var/cpanel/cphulk.conf' : $conf_file;
}

sub get_action_file {
    my $action_file = "$conf_dir/action";
    return -e $action_file ? $action_file : -e '/var/cpanel/hulkd.conf' ? '/var/cpanel/hulkd.conf' : $action_file;
}

sub get_conf_path { goto &get_conf_file; }

our $enabled_cache;

sub is_enabled {
    return $enabled_cache if defined $enabled_cache;
    return ( $enabled_cache = -e _get_enabled_file() ? 1 : ( -e '/var/cpanel/cphulk_enable' ) ? 1 : 0 );
}

sub disable {
    unlink _get_enabled_file(), '/var/cpanel/cphulk_enable';
    return;
}

sub enable {
    if ( open my $enabled_fh, '>', _get_enabled_file() ) {
        print {$enabled_fh} time();
        close $enabled_fh;
    }
    return;
}

sub _get_enabled_file {
    return "$conf_dir/enabled";
}

1;

} # --- END Cpanel/Config/Hulk.pm


{ # --- BEGIN Cpanel/Chkservd/Config.pm
package Cpanel::Chkservd::Config;


use strict;

our $chkservd_dir = '/etc/chkserv.d';

1;

} # --- END Cpanel/Chkservd/Config.pm


{ # --- BEGIN Cpanel/Chkservd/Config/Drivers.pm
package Cpanel::Chkservd::Config::Drivers;


use strict;
use warnings;

# use Cpanel::LoadFile::ReadFast ();

our $VERSION = '1.0';


sub load_driver_directory {
    my ( $dir, $services_hash_ref, $match_regex ) = @_;

    local $!;

    $services_hash_ref ||= {};
    if ( opendir my $dh, $dir ) {

        my @drivers = readdir($dh);
        die "readdir($dir): $!" if $!;

        foreach my $driver_file (@drivers) {
            if ( $driver_file =~ tr{.-}{} ) {
                next
                  if $driver_file eq '.'
                  || $driver_file eq '..'
                  || $driver_file =~ m/\.conf$/
                  || $driver_file =~ m{\.rpm[^\.]+$}
                  ||                                  # CPANEL-5659: light defense for .rpmorig, .rpmsave files until this can be refactored
                  $driver_file =~ m{-cpanelsync$};    # CPANEL-5659: light defense for -cpanelsync files until this can be refactored
            }

            next if ( $match_regex && $driver_file !~ $match_regex );

            open my $driver_fh, '<:stdio', "$dir/$driver_file" or do {    # Use :stdio to avoid some of the PerlIO overhead since we are slurping in the file
                die "open($dir/$driver_file): $!";
            };

            my $cfg_txt = '';
            Cpanel::LoadFile::ReadFast::read_all_fast( $driver_fh, $cfg_txt );
            die "read($dir/$driver_file): $!" if $!;

            foreach my $line ( split( m{\n}, $cfg_txt ) ) {
                my ( $service, $servdata ) = split( /=/, $line, 2 );
                next if !$service;
                next if $service =~ /^\s*#/;    # Don't process comment lines.
                if ( $service =~ m/service\[([^\]]+)\]/ ) {
                    $services_hash_ref->{$1} = $servdata;
                }
            }
            close $driver_fh;
        }
        closedir $dh;
    }
    else {
        die "opendir($dir): $!" if !$!{'ENOENT'};
    }

    return $services_hash_ref;
}
1;


} # --- END Cpanel/Chkservd/Config/Drivers.pm


{ # --- BEGIN Cpanel/PHPFPM/Constants.pm
package Cpanel::PHPFPM::Constants;


use strict;
use warnings;

our $system_yaml_dir           = "/var/cpanel/ApachePHPFPM";
our $system_yaml               = "system.yaml";
our $system_pool_defaults_yaml = "system_pool_defaults.yaml";
our $php_conf_path             = '/etc/cpanel/ea4/php.conf';
our $apache_include_path       = qq{/etc/apache2/conf.d/userdata/std};

our $opt_cpanel = '/opt/cpanel';    # use for testing.

our $template_dir = "/usr/local/cpanel/shared/templates";

our $system_conf_tmpl      = "system-php-fpm-conf.tmpl";
our $system_pool_conf_tmpl = "system-php-fpm-pool-conf.tmpl";

our $touch_file = '/default_accounts_to_fpm';

our $delay_for_rebuild = 10;

our $convert_all_pid_file = '/var/cpanel/ea_php_fpm_convert_all_in_progress';

1;

} # --- END Cpanel/PHPFPM/Constants.pm


{ # --- BEGIN Cpanel/ProcessInfo.pm
package Cpanel::ProcessInfo;


use strict;
use warnings;

# use Cpanel::Context ();
# use Cpanel::Autodie ();

our $VERSION = '1.0';



sub get_pid_lineage {
    Cpanel::Context::must_be_list();

    my @lineage;

    my $ppid = getppid();
    while ( $ppid > 1 ) {
        push @lineage, $ppid;
        $ppid = get_parent_pid($ppid);
    }

    return @lineage;
}


sub get_parent_pid {
    _die_if_pid_invalid( $_[0] );

    return getppid() if $_[0] == $$;

    if ( open( my $proc_status_fh, '<', "/proc/$_[0]/status" ) ) {
        local $/;
        my %status = map { lc $_->[0] => $_->[1] }
          map  { [ ( split( /\s*:\s*/, $_ ) )[ 0, 1 ] ] }
          grep { index( $_, ':' ) > -1 }
          split( /\n/, readline($proc_status_fh) );
        return $status{'ppid'};
    }

    return undef;
}


sub get_pid_exe {
    _die_if_pid_invalid( $_[0] );
    return Cpanel::Autodie::readlink_if_exists( '/proc/' . $_[0] . '/exe' );
}


sub get_pid_cmdline {
    _die_if_pid_invalid( $_[0] );
    if ( open( my $cmdline, '<', "/proc/$_[0]/cmdline" ) ) {
        local $/;
        my $cmdline = readline($cmdline);
        $cmdline =~ tr{\0}{ };
        $cmdline =~ tr{\r\n}{}d;
        substr( $cmdline, -1, 1, '' ) if substr( $cmdline, -1 ) eq ' ';
        return $cmdline;
    }

    return '';
}


sub get_pid_cwd {
    _die_if_pid_invalid( $_[0] );
    return readlink( '/proc/' . $_[0] . '/cwd' ) || '/';
}

sub _die_if_pid_invalid {
    die "Invalid PID: $_[0]" if !length $_[0] || $_[0] =~ tr{0-9}{}c;
    return;
}
1;

} # --- END Cpanel/ProcessInfo.pm


{ # --- BEGIN Cpanel/PHPFPM/Controller.pm
package Cpanel::PHPFPM::Controller;


use strict;
use warnings;

# use Cpanel::OS                ();
# use Cpanel::SafeRun::Object   ();
# use Cpanel::PHPFPM::Constants ();    # PPI NO PARSE - It is being used
# use Cpanel::ProcessInfo       ();
# use Cpanel::Debug             ();





my $action_message;

sub process_action {
    my ( $version, $action ) = @_;

    if ( $action ne 'start' and $action ne 'restart' and $action ne 'stop' and $action ne 'restart_gracefully' ) {
        warn "Unknown action to _process_action() [ $action ] [ $version ] . We only allow start, restart, restart_gracefully and stop\n";
        return 0;
    }

    return if ( $action ne 'stop' && !phpfpm_version_users_configured($version) );

    if ( $action eq 'restart_gracefully' ) {

        my $pid = get_pid_from_version($version);
        if ($pid) {
            my $pid_exe;

            local $@;
            warn if !eval { $pid_exe = Cpanel::ProcessInfo::get_pid_exe($pid); 1 };

            if ( $pid_exe && index( $pid_exe, 'php-fpm' ) != -1 ) {
                kill( 'USR2', $pid );

                if ( $version =~ /^5/ ) {
                    sleep 1;
                    $pid    = get_pid_from_version($version);
                    $action = 'restart' unless $pid;
                }
            }
            else {
                $action = 'restart';
            }
        }
        else {

            $action = 'restart';
        }
    }

    my $action_result;
    if ( grep { $action eq $_ } qw{start stop restart} ) {

        undef $action_message;
        $action_result = Cpanel::OS::is_systemd() ? systemctl_action( $version, $action ) : init_script_action( $version, $action );
    }

    if ( $action ne 'stop' ) {

        if ( $action eq 'restart_gracefully' || $action_result ) {
            require Cpanel::TimeHiRes;
            my $pid;
            my $ctr = 0;

            print "Waiting up to 10s for PHP-FPM Version $version to be ready...\n" if $Cpanel::Debug::level;
            while ( !( $pid = get_pid_from_version($version) ) && $ctr++ < 100 ) {
                Cpanel::TimeHiRes::sleep(0.1);
            }
            if ($pid) {
                my $pid_exe;

                local $@;
                warn if !eval { $pid_exe = Cpanel::ProcessInfo::get_pid_exe($pid); 1 };

                if ( $pid_exe && $pid_exe =~ m/php-fpm/ ) {
                    return undef;
                }
            }
        }
        die $action_message ? $action_message : "PHP-FPM Version $version failed to start\n";
    }
    return;
}


sub systemctl_action {
    my ( $version, $action ) = @_;
    my $service = 'ea-php' . $version . '-php-fpm';
    my $run     = Cpanel::SafeRun::Object->new( 'program' => '/usr/bin/systemctl', 'args' => [ $action, $service ] );
    if ( $run->CHILD_ERROR() ) {
        my $msg        = join( q< >, map { $run->$_() // () } qw( autopsy stdout stderr ) );
        my $status_run = Cpanel::SafeRun::Object->new( 'program' => '/usr/bin/systemctl', 'args' => [ 'status', "$service" ] );    # ea-php56-php-fpm.service
        my $status_msg = join( q< >, map { $status_run->$_() // () } qw( stdout stderr ) );

        $action_message = "Failed to perform action “$action” for php-fpm “$version”: $msg: $status_msg";
        return 0;
    }

    return 1;
}


sub init_script_action {
    my ( $version, $action ) = @_;
    my $run = Cpanel::SafeRun::Object->new( 'program' => '/etc/init.d/ea-php' . $version . '-php-fpm', 'args' => [$action] );
    if ( $run->CHILD_ERROR() ) {
        my $msg = join( q< >, map { $run->$_() // () } qw( autopsy stdout stderr ) );
        $action_message = "Failed to perform action “$action” for php-fpm “$version”: $msg";
        return 0;
    }
    return 1;
}


sub restart_version {
    my ($version) = @_;
    process_action( $version, 'restart' );
    return;
}


sub get_phpfpm_versions {
    my @versions;
    if ( opendir( my $optcpanel_dh, ${Cpanel::PHPFPM::Constants::opt_cpanel} ) ) {
        my @files = readdir($optcpanel_dh);
        foreach my $file (@files) {
            if ( $file =~ m/ea\-php(\d{2})/ ) {

                if ( -f ${Cpanel::PHPFPM::Constants::opt_cpanel} . '/' . $file . '/root/etc/php-fpm.conf' and -f ${Cpanel::PHPFPM::Constants::opt_cpanel} . '/' . $file . '/root/usr/sbin/php-fpm' ) {
                    push( @versions, $1 );
                }
            }
        }
        close($optcpanel_dh);
    }
    return \@versions;
}


sub get_pid_from_version {
    my ($version) = @_;
    my $pid;
    if ( open( my $fpmconf_fh, '<', ${Cpanel::PHPFPM::Constants::opt_cpanel} . '/ea-php' . $version . '/root/etc/php-fpm.conf' ) ) {
        while ( my $line = <$fpmconf_fh> ) {
            if ( $line =~ m/^pid\s*=\s*(\/.*\.pid)$/ ) {
                my $pid_file_path = $1;
                if ( open( my $pid_file_fh, '<', $pid_file_path ) ) {
                    $pid = <$pid_file_fh>;
                    close($pid_file_fh);
                }
            }
        }
    }
    return $pid;
}


sub phpfpm_version_users_configured {
    my ($version) = @_;

    if ( $version =~ m/ea-php(\d+)/ ) {
        $version = $1;
    }
    my $count = 0;

    if ( opendir( my $user_confs_dir, ${Cpanel::PHPFPM::Constants::opt_cpanel} . '/ea-php' . $version . '/root/etc/php-fpm.d/' ) ) {
        $count = scalar grep { length $_ > 5 && substr( $_, -5 ) eq '.conf' } readdir($user_confs_dir);
    }
    return $count;
}


sub get_phpfpm_versions_in_use {
    my @versions;

    for my $ver ( @{ get_phpfpm_versions() } ) {

        if ( phpfpm_version_users_configured($ver) > 0 ) {
            push( @versions, $ver );
        }
    }
    return \@versions;
}


1;

} # --- END Cpanel/PHPFPM/Controller.pm


{ # --- BEGIN Cpanel/FileUtils/LinkTest.pm
package Cpanel::FileUtils::LinkTest;


use strict;
use warnings;

# use Cpanel::Exception ();


use constant {
    _ENOENT => 2,
    _EINVAL => 22,
};


sub get_type {
    local ( $!, $^E );
    readlink $_[0] // do {
        return undef      if $! == _ENOENT();
        return 'not_link' if $! == _EINVAL();    #non-symlink

        die Cpanel::Exception->create( 'The system failed to determine whether “[_1]” exists on the filesystem because of an error: [_2]', [ $_[0], $! ] );
    };

    return 'link';
}

1;

} # --- END Cpanel/FileUtils/LinkTest.pm


{ # --- BEGIN Cpanel/LoadModule/Name.pm
package Cpanel::LoadModule::Name;


use strict;
use warnings;

# use Cpanel::FileUtils::LinkTest ();
# use Cpanel::Exception           ();

sub get_module_names_from_directory {
    my ($dir) = @_;

    die "List context only!" if !wantarray;

    my @names;

    if ( Cpanel::FileUtils::LinkTest::get_type($dir) ) {
        local $!;

        opendir( my $dh, $dir ) or die Cpanel::Exception::create( 'IO::DirectoryOpenError', [ path => $dir, error => $! ] );

        @names = map { length $_ > 3 && substr( $_, -3, 3, '' ) eq '.pm' ? $_ : () } readdir $dh;    ## no critic qw(ControlStructures::ProhibitMutatingListFunctions)
        die Cpanel::Exception::create( 'IO::DirectoryReadError', [ path => $dir, error => $! ] ) if $!;

        closedir $dh or warn "Failed to close directory $dir: $!";
    }

    return @names;
}

1;

} # --- END Cpanel/LoadModule/Name.pm


{ # --- BEGIN Cpanel/LoadModule/Custom.pm
package Cpanel::LoadModule::Custom;


use strict;
use warnings;


# use Cpanel::ConfigFiles      ();
# use Cpanel::LoadModule::Name ();

# use Cpanel::LoadModule ();

our $_CUSTOM_MODULES_DIR;
*_CUSTOM_MODULES_DIR = \$Cpanel::ConfigFiles::CUSTOM_PERL_MODULES_DIR;



sub list_modules_for_namespace {
    my ($ns) = @_;
    $ns =~ s<::></>g;

    return Cpanel::LoadModule::Name::get_module_names_from_directory("$_CUSTOM_MODULES_DIR/$ns");
}


sub load_perl_module {
    my ( $module, %opts ) = @_;

    local @INC = (
        ( !$opts{builtin_first} ? ($_CUSTOM_MODULES_DIR) : () ),
        @INC,
        ( $opts{builtin_first} ? ($_CUSTOM_MODULES_DIR) : () ),
    );

    return Cpanel::LoadModule::load_perl_module($module);
}

1;

} # --- END Cpanel/LoadModule/Custom.pm


{ # --- BEGIN Cpanel/Services/List.pm
package Cpanel::Services::List;


use strict;
use warnings;

# use Cpanel::Chkservd::Config          ();
# use Cpanel::Chkservd::Config::Drivers ();
# use Cpanel::Debug                     ();


sub get_service_list {
    my $services = _get_services();
    return wantarray ? %$services : $services;
}

sub get_name {
    my $service = shift;
    return unless defined $service;

    my $services = _get_services();
    return          if !exists $services->{$service};
    return $service if !exists $services->{$service}->{'name'};
    return $services->{$service}->{'name'};
}


sub canonicalize_service {
    my ( $service, $enabled, $monitored_status_for ) = @_;

    unless ( $service eq 'exim-altport' ) {
        return {
            'service'   => $service,
            'enabled'   => $enabled,
            'monitored' => $monitored_status_for->{$service},
        };
    }

    my @services;
    if ( opendir my $chkservd, $Cpanel::Chkservd::Config::chkservd_dir ) {
        @services = grep { !m{-cpanelsync$} && !m{\.rpm[^\.]+$} } readdir $chkservd;
        closedir $chkservd;
    }

    my $settings = {
        'name'  => 'exim-altportnum',
        'size'  => 30,
        'value' => 26,
    };

    foreach my $service (@services) {
        if ( $service =~ /^exim-([0-9\,]+)/ ) {
            $settings->{'value'} = $1;
            my $monitored = exists $monitored_status_for->{$service} && $monitored_status_for->{$service} == 1 ? 1 : 0;
            return {
                'service'   => $service,
                'enabled'   => 1,
                'monitored' => $monitored,
                'settings'  => $settings,
            };
        }
    }

    return {
        'service'   => $service,
        'enabled'   => 0,
        'monitored' => 0,
        'settings'  => $settings,
    };
}

our $SERVS;

sub _get_services {
    require Cpanel::PHPFPM::Controller;
    if ( !defined $SERVS ) {
        require Cpanel::Locale;
        my $locale = Cpanel::Locale->get_handle();
        require Cpanel::Config::LoadCpConf;
        my $cpconf_ref = Cpanel::Config::LoadCpConf::loadcpconf_not_copy();

        $SERVS = {
            'cpanalyticsd' => { 'name' => $locale->maketext('EXPERIMENTAL: [asis,cPanel] Analytics Daemon'), 'description'    => $locale->maketext('[asis,cPanel] [output,amp] [asis,WHM’s] internal analytics service.') },
            'clamd'        => { 'name' => $locale->maketext('[asis,ClamAV] Daemon'),                         'description'    => $locale->maketext('[asis,ClamAV] Virus Scanner') },
            'crond'        => { 'name' => $locale->maketext('[asis,Cron] Daemon'),                           'always_enabled' => 1 },
            'cpanellogd'   => { 'name' => $locale->maketext('[asis,cPanel] Log and Bandwidth Processor') },
            'cpdavd'       => { 'name' => $locale->maketext('[asis,cPanel] [asis,DAV] Daemon') },
            'cphulkd'      => { 'name' => $locale->maketext('[asis,cPHulk] Daemon'), 'description' => $locale->maketext('[asis,cPHulk] Brute Force Protection') },
            'cpsrvd'       => {
                'name'           => $locale->maketext('[asis,cPanel] Daemon'),
                'always_enabled' => 1,
            },
            'cpanel_php_fpm' => { 'name' => $locale->maketext('[asis,PHP-FPM] service for [asis,cPanel] Daemons'), 'skip_dnsonly' => 1 },
            'cpgreylistd'    => { 'name' => $locale->maketext('[asis,cPanel] [asis,Greylisting] Daemon'),          'skip_dnsonly' => 1 },
            'p0f'            => { 'name' => $locale->maketext('Passive [output,abbr,OS,Operating System] Fingerprinting Daemon') },
            'dnsadmin'       => {
                'name'           => $locale->maketext('[asis,cPanel] [output,abbr,DNS,Domain Name System] Admin Cache'),
                'description'    => $locale->maketext('[asis,cPanel] [output,abbr,DNS,Domain Name System] Admin Cache Service'),
                'always_enabled' => 1
            },
            'exim' => { 'name' => $locale->maketext('[asis,Exim] Mail Server'), 'description' => $locale->maketext('[output,abbr,SMTP,Simple Mail Transport Protocol] Server') },

            'exim-altport' => { name => $locale->maketext('[asis,Exim] Mail Server (on another port)'), 'note' => $locale->maketext('Useful for providers that block port 25 (multiple comma-delimited ports may be added).'), 'description' => $locale->maketext('Allow [asis,exim] to listen on a port other than 25, 465, and 587.') },

            'ftpd'      => { 'name' => $locale->maketext('[output,abbr,FTP,File Transfer Protocol] Server') },
            'httpd'     => { 'name' => $locale->maketext('[asis,Apache] Web Server'),                                'description' => $locale->maketext('Web Server') },
            'imap'      => { 'name' => $locale->maketext('[output,abbr,IMAP,Internet Mail Access Protocol] Server'), description   => $locale->maketext('[asis,Dovecot] [output,abbr,IMAP,Internet Mail Access Protocol] Server'), 'skip_dnsonly'   => 1 },
            'lmtp'      => { 'name' => $locale->maketext('[output,abbr,LMTP,Local Mail Transport Protocol] Server'), description   => $locale->maketext('[asis,Dovecot] [output,abbr,LMTP,Local Mail Transport Protocol] Server'), 'always_enabled' => 1 },
            'pop'       => { 'name' => $locale->maketext('[output,abbr,POP3,Post Office Protocol 3] Server'),        description   => $locale->maketext('[asis,Dovecot] [output,abbr,POP3,Post Office Protocol 3] Server'),        'skip_dnsonly'   => 1 },
            'ipaliases' => { 'name' => $locale->maketext('[output,abbr,IP,Internet Protocol] Aliases') },
            'mailman'   => { 'name' => $locale->maketext('[asis,Mailman]'), 'description' => $locale->maketext('Mailing List Manager') },
            'mysql'     => { 'name' => $locale->maketext('[asis,MySQL] Server'), 'description' => $locale->maketext('[asis,MySQL] Database Server'), 'always_enabled' => ( $cpconf_ref->{'roundcube_db'} eq 'mysql' ? 1 : 0 ) },
            'named'     => {
                'name'                 => $locale->maketext('[output,abbr,DNS,Domain Name System] Server'),
                'description'          => $locale->maketext('Berkeley Name Server Daemon ([asis,BIND])'),
                'description_nsd'      => $locale->maketext('Name Server Daemon ([asis,NSD])'),
                'description_mydns'    => $locale->maketext('Name Server Daemon ([asis,MyDNS])'),
                'description_powerdns' => $locale->maketext('[asis,PowerDNS]'),
                'description_disabled' => $locale->maketext( 'You have disabled the [output,abbr,DNS,Domain Name System] Server. Visit the [output,url,_1,Nameserver Selection] page to enable this service.', '../scripts/nameserverconfig' )
            },
            'postgresql' => { 'name' => $locale->maketext('[asis,PostgreSQL] Server'), 'description' => $locale->maketext('[asis,PostgreSQL] Database Server') },
            'queueprocd' => {
                'name'           => $locale->maketext('[asis,TaskQueue] Processor'),
                'description'    => $locale->maketext('[asis,TaskQueue] Processing Server'),
                'always_enabled' => 1,

            },
            'rsyslogd'   => { 'name' => $locale->maketext('[asis,rsyslog] System Logger Daemon'),   'description' => $locale->maketext('Enhanced System Logger Daemon') },
            'spamd'      => { 'name' => $locale->maketext('[asis,Apache SpamAssassin™]'),           'description' => $locale->maketext('[asis,SpamAssassin] Server (if you choose to disable this, you should disable [asis,SpamAssassin] in the [asis,Tweak Settings] interface as well)'), 'skip_dnsonly' => 1 },
            'sshd'       => { 'name' => $locale->maketext('[output,abbr,SSH,Secure Shell] Daemon'), 'description' => $locale->maketext('Secure Shell Daemon') },
            'nscd'       => { 'name' => $locale->maketext('Name Service Cache Daemon'), },
            'syslogd'    => { 'name' => $locale->maketext('[asis,syslog] System Logger Daemon'), 'description' => $locale->maketext('System Logger Daemon') },
            'tailwatchd' => { 'name' => $locale->maketext('[asis,TailWatch] Daemon'), 'subopt_heading' => $locale->maketext('[asis,TailWatch] Drivers:'), note => $locale->maketext('Disabling all drivers will effectively disable [asis,tailwatchd].'), 'description' => $locale->maketext('[asis,TailWatch] Daemon (Configurable Log Monitoring Service)') },
        };

        my $phpfpmversions_installed_ar = Cpanel::PHPFPM::Controller::get_phpfpm_versions();
        my $is_php_fpm_available        = @{$phpfpmversions_installed_ar};
        my $apache_php_fpm_description  = $locale->maketext('The PHP-FPM daemons for the [asis,Apache] Web Server are installed and removed using [asis,EasyApache 4] and may not be enabled or disabled here.');
        if ($is_php_fpm_available) {
            $SERVS->{'apache_php_fpm'} = {
                'name'           => $locale->maketext('[asis,PHP-FPM] service for [asis,Apache]'),
                'description'    => $apache_php_fpm_description,
                'skip_dnsonly'   => 1,
                'always_enabled' => 1
            };
        }
        else {
            $SERVS->{'apache_php_fpm'} = {
                'name'               => $locale->maketext('[asis,PHP-FPM] service for [asis,Apache]'),
                'description'        => $apache_php_fpm_description,
                'skip_dnsonly'       => 1,
                'always_disabled'    => 1,
                'always_unmonitored' => 1
            };
        }

        if ( $cpconf_ref->{local_nameserver_type} && $cpconf_ref->{local_nameserver_type} eq 'disabled' ) {
            $SERVS->{named}{always_disabled}    = 1;
            $SERVS->{named}{always_unmonitored} = 1;
        }

    }

    my $drivers_ref = Cpanel::Chkservd::Config::Drivers::load_driver_directory($Cpanel::Chkservd::Config::chkservd_dir);
    foreach my $srv ( keys %$drivers_ref ) {
        next if ref $SERVS->{$srv} eq 'HASH';
        my ( $name, $description );

        my @cfg_line = split( /,/, ( $drivers_ref->{$srv} // '' ) );
        my $module   = $cfg_line[8];
        if ($module) {
            local $@;
            require Cpanel::LoadModule::Custom;
            my $desc_hr = eval {
                Cpanel::LoadModule::Custom::load_perl_module($module);
                my $cr = $module->can("get_service_description_hashref");
                $cr ? $cr->() : undef;
            };
            Cpanel::Debug::log_error($@) if !$desc_hr && $@;

            ( $name, $description ) = ( $desc_hr->{name}, $desc_hr->{description} );
        }

        $SERVS->{$srv} ||= { 'name' => $name || $srv, 'description' => $description || $srv };
    }

    return $SERVS;
}

1;

} # --- END Cpanel/Services/List.pm


{ # --- BEGIN Cpanel/Server/Type/Profile/Constants.pm
package Cpanel::Server::Type::Profile::Constants;


use strict;
use warnings;


use constant {
    DNSNODE      => "DNSNODE",
    DATABASENODE => "DATABASENODE",
    DNSONLY      => "DNSONLY",
    MAILNODE     => "MAILNODE",
    STANDARD     => "STANDARD"
};

our %PROFILE_CHILD_WORKLOADS = (
    MAILNODE() => ['Mail'],
);

1;

} # --- END Cpanel/Server/Type/Profile/Constants.pm


{ # --- BEGIN Cpanel/Server/Type/License.pm
package Cpanel::Server::Type::License;


use strict;
use warnings;

# use Cpanel::Server::Type                     ();
# use Cpanel::Server::Type::Profile::Constants ();

BEGIN { *is_ea4_allowed = *is_cpanel }


sub is_full_license {

    return !$Cpanel::Server::Type::DNSONLY_MODE if defined $Cpanel::Server::Type::DNSONLY_MODE;

    if ( Cpanel::Server::Type::_read_license() ) {
        return $Cpanel::Server::Type::PRODUCTS{'cpanel'} ? 1 : 0;
    }

    return -e Cpanel::Server::Type::_get_dnsonly_file_path() ? 0 : 1;
}


sub is_cpanel {
    return 0 if !is_full_license() || _is_license_restricted_node();
    return 1;
}

sub _is_license_restricted_node {
    return Cpanel::Server::Type::is_dnsonly() || Cpanel::Server::Type::get_producttype() ne Cpanel::Server::Type::Profile::Constants::STANDARD();
}


1;

} # --- END Cpanel/Server/Type/License.pm


{ # --- BEGIN Cpanel/Config/Httpd/EA4.pm
package Cpanel::Config::Httpd::EA4;



use strict;
use warnings;

# use Cpanel::Autodie ();

our $_FLAG_FILE = '/etc/cpanel/ea4/is_ea4';


my $is_ea4_cached;

sub is_ea4 {
    return $is_ea4_cached //= _is_ea4();
}


sub _is_ea4 {
    return Cpanel::Autodie::exists($_FLAG_FILE) ? 1 : 0;
}

sub reset_cache {
    undef $is_ea4_cached;
    return;
}

1;

} # --- END Cpanel/Config/Httpd/EA4.pm


{ # --- BEGIN Cpanel/DbUtils.pm
package Cpanel::DbUtils;


use strict;

# use Cpanel::FindBin ();

our $VERSION = 1.2;

sub _find_bin {
    return Cpanel::FindBin::findbin( $_[0], ( defined $_[1] ? $_[1] : () ) );
}

sub find_mysql        { return _find_bin('mysql'); }
sub find_mysql_config { return _find_bin('mysql_config'); }
sub find_mysqladmin   { return _find_bin('mysqladmin'); }
sub find_mysqlcheck   { return _find_bin('mysqlcheck'); }
sub find_mysqldump    { return _find_bin('mysqldump'); }

sub find_mysql_fix_privilege_tables { return _find_bin('mysql_fix_privilege_tables'); }
sub find_mysql_upgrade              { return _find_bin('mysql_upgrade') }
sub find_mysql_install_db           { return _find_bin('mysql_install_db') }
sub find_mysqld                     { return _find_bin( 'mysqld', [ '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin', '/usr/libexec', '/usr/local/libexec' ] ); }

sub find_pg_dump    { return _find_bin('pg_dump') }
sub find_pg_restore { return _find_bin('pg_restore') }
sub find_psql       { return _find_bin('psql') }

sub find_postmaster { return _find_bin('postmaster') }
sub find_createdb   { return _find_bin('createdb'); }
sub find_pg_ctl     { return _find_bin('pg_ctl'); }
sub find_createuser { return _find_bin('createuser'); }
sub find_dropdb     { return _find_bin('dropdb'); }
sub find_dropuser   { return _find_bin('dropuser'); }

1;

} # --- END Cpanel/DbUtils.pm


{ # --- BEGIN Cpanel/Services/Installed.pm
package Cpanel::Services::Installed;


use strict;
use warnings;

# use Cpanel::Server::Type              ();
# use Cpanel::Server::Type::License     ();
# use Cpanel::Debug                     ();
# use Cpanel::FindBin                   ();
# use Cpanel::Binaries                  ();
# use Cpanel::Chkservd::Config          ();
# use Cpanel::Config::Httpd::EA4        ();
# use Cpanel::Services::AlwaysInstalled ();

$Cpanel::Services::Installed::VERSION = '0.4';

my $find_path = [qw{ /sbin /usr/sbin /usr/local/sbin /bin /usr/bin /usr/local/bin /usr/local/cpanel/3rdparty/bin }];

sub _service_is_installed_clamd {
    require Cpanel::Binaries;
    if ( -x Cpanel::Binaries::path('clamd') ) {
        return 1;
    }
    return;
}

sub _service_is_installed_cpdavd {
    if ( Cpanel::Server::Type::is_dnsonly() ) { return 0; }
    return 1;
}

sub _service_is_installed_exim {
    if ( -x Cpanel::Binaries::path('exim') ) {
        return 1;
    }
    return;
}

sub _service_is_installed_exim_altport {
    if ( -x Cpanel::Binaries::path('exim') ) {
        return 1;
    }
    return;
}

sub _service_is_installed_ftpd {
    if ( Cpanel::Server::Type::is_dnsonly() ) { return 0; }
    if ( Cpanel::FindBin::findbin( 'pure-ftpd', 'path' => $find_path ) || Cpanel::FindBin::findbin( 'proftpd', 'path' => $find_path ) ) {
        return 1;
    }
    return;
}

sub _service_is_installed_httpd {
    if ( !Cpanel::Config::Httpd::EA4::is_ea4() )             { return 0; }
    if ( !Cpanel::Server::Type::License::is_full_license() ) { return 0; }
    return 1;
}

sub _service_is_installed_imap {
    if ( Cpanel::Server::Type::is_dnsonly() ) { return 0; }
    return 1;
}

sub _service_is_installed_pop {
    if ( Cpanel::Server::Type::is_dnsonly() ) { return 0; }
    return 1;
}

sub _service_is_installed_mailman {
    if ( Cpanel::Server::Type::is_dnsonly() ) { return 0; }
    return 1;
}

sub _service_is_installed_mysql {
    require Cpanel::DbUtils;
    if ( Cpanel::DbUtils::find_mysqld() ) {
        return 1;
    }
    return;
}

sub _service_is_installed_postgresql {
    require Cpanel::DbUtils;
    if ( Cpanel::DbUtils::find_postmaster() ) {
        return 1;
    }
    return;
}

sub _service_is_installed_cpanellogd {
    return 1;
}

sub _service_is_installed_rsyslogd {
    if ( Cpanel::FindBin::findbin( 'rsyslogd', 'path' => $find_path ) ) {
        return 1;
    }
    return;
}

sub _service_is_installed_spamd {
    if ( -x Cpanel::Binaries::path('spamd') ) {
        return 1;
    }
    return;
}

sub _service_is_installed_sshd {
    if ( -x Cpanel::FindBin::findbin('sshd') ) {
        return 1;
    }
    return;
}

sub _service_is_installed_crond {
    require Cpanel::OS;
    if ( -x Cpanel::OS::cron_bin_path() ) {
        return 1;
    }
    return;
}

sub _service_is_installed_nscd {
    if ( Cpanel::FindBin::findbin( 'nscd', 'path' => $find_path ) ) {
        return 1;
    }
    return;
}

sub _service_is_installed_syslogd {
    if ( Cpanel::FindBin::findbin( 'syslogd', 'path' => $find_path ) ) {
        return 1;
    }
    return;
}

sub _service_is_installed_p0f {
    if ( -e '/usr/local/cpanel/3rdparty/sbin/p0f' ) {
        return 1;
    }
    return 0;
}

sub _service_is_installed_apache_php_fpm {
    require Cpanel::PHPFPM::Controller;
    my $versions_ar = Cpanel::PHPFPM::Controller::get_phpfpm_versions();
    if ( @{$versions_ar} ) {
        return 1;
    }
    return 0;
}

sub _service_is_installed_pdns {
    return -x Cpanel::Binaries::path('pdns_server') ? 1 : 0;
}

sub _service_has_chkservd_file {
    return -e "$Cpanel::Chkservd::Config::chkservd_dir/$_[0]" ? 1 : 0;
}

sub service_is_installed {
    my ($service) = @_;
    if ( $service =~ tr{0-9A-Za-z_-}{}c ) {
        Cpanel::Debug::log_warn("[$service] doesn't look like a service name");
        return;
    }


    my $service_code_name = $service;
    $service_code_name =~ tr{-}{_};

    return 1 if grep { $_ eq $service_code_name } Cpanel::Services::AlwaysInstalled::SERVICES();

    my $is_installed = "_service_is_installed_$service_code_name";
    my $result       = undef;

    if ( my $code = __PACKAGE__->can($is_installed) ) {
        $result = $code->();
        return 1 if $result;
    }
    elsif ( _service_has_chkservd_file($service) ) {
        return 1;
    }

    return undef;
}

1;


} # --- END Cpanel/Services/Installed.pm


{ # --- BEGIN Cpanel/Autodie/CORE/exists.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub exists {    ## no critic qw( RequireArgUnpacking )
    local ( $!, $^E );

    if ( ${^GLOBAL_PHASE} eq 'START' ) {
        _die_err( $_[0], "do not access the filesystem at compile time" );
    }

    return 1 if -e $_[0];
    return 0 if $! == _ENOENT();

    return _die_err( $_[0], $! );
}


sub exists_nofollow {
    my ($path) = @_;


    local ( $!, $^E );

    return 1 if CORE::lstat $path;

    return 0 if $! == _ENOENT();

    return _die_err( $path, $! );
}

sub _die_err {
    my ( $path, $err ) = @_;

    local $@;    # $! is already local()ed.
    require Cpanel::Exception;

    die Cpanel::Exception::create( 'IO::StatError', [ error => $err, path => $path ] );
}

1;

} # --- END Cpanel/Autodie/CORE/exists.pm


{ # --- BEGIN Cpanel/Autodie/CORE/exists_nofollow.pm
package Cpanel::Autodie;


use strict;
use warnings;

# use Cpanel::Autodie::CORE::exists();    # PPI NO PARSE


1;

} # --- END Cpanel/Autodie/CORE/exists_nofollow.pm


{ # --- BEGIN Cpanel/Autodie/More/Lite.pm
package Cpanel::Autodie::More::Lite;


use strict;
use warnings;

# use Cpanel::Autodie                        ();
# use Cpanel::Autodie::CORE::exists          ();    # PPI USE OK - reload so we can map the symbol below
# use Cpanel::Autodie::CORE::exists_nofollow ();    # PPI USE OK - reload so we can map the symbol below

BEGIN {
    *exists          = *Cpanel::Autodie::exists;
    *exists_nofollow = *Cpanel::Autodie::exists_nofollow;
}
1;

} # --- END Cpanel/Autodie/More/Lite.pm


{ # --- BEGIN Cpanel/Services/Enabled/Spamd.pm
package Cpanel::Services::Enabled::Spamd;


use strict;
use warnings;



# use Cpanel::Autodie::More::Lite ();

our $_TOUCHFILE_PATH = '/etc/spamddisable';



sub is_enabled {
    return !Cpanel::Autodie::More::Lite::exists($_TOUCHFILE_PATH);
}

1;

} # --- END Cpanel/Services/Enabled/Spamd.pm


{ # --- BEGIN Cpanel/Dovecot/Constants.pm
package Cpanel::Dovecot::Constants;


use strict;

our $PROTOCOLS_FILE = '/var/cpanel/dovecot_protocols';

our $INCLUDE_TRASH_IN_QUOTA_CONFIG_CACHE_FILE = '/var/cpanel/dovecot_include_trash_in_quota';

1;

} # --- END Cpanel/Dovecot/Constants.pm


{ # --- BEGIN Cpanel/Services/Enabled.pm
package Cpanel::Services::Enabled;


use strict;
use warnings;


# use Cpanel::LoadModule                ();
# use Cpanel::Server::Type              ();
# use Cpanel::Services::AlwaysInstalled ();

use constant _ENOENT => 2;

our $DOVECOT_CONF_FILE = '/var/cpanel/conf/dovecot/main';


my @common_dns_files         = qw{/etc/nameddisable /etc/binddisable /etc/dnsdisable};
my %disable_files_exceptions = (
    'dns'        => [@common_dns_files],
    'bind'       => [@common_dns_files],
    'mydns'      => [@common_dns_files],
    'nsd'        => [@common_dns_files],
    'pdns'       => [@common_dns_files],
    'ftp'        => [qw{/etc/ftpddisable /etc/ftpserverdisable}],
    'httpd'      => [qw{/etc/httpddisable /etc/apachedisable /etc/httpdisable}],
    'imap'       => [qw{/etc/imapdisable /etc/imapddisable /etc/cpimapdisable}],
    'mail'       => [qw{/etc/imapdisable /etc/imapddisable}],
    'pop'        => [qw{/etc/popdisable /etc/cppopdisable}],
    'postgresql' => [qw{/etc/postgresqldisable /etc/postgresdisable}],
    'rsyslogd'   => [qw{/etc/rsyslogddisable /etc/rsyslogdisable}],
    'tailwatchd' => [qw{/etc/tailwatchddisable /etc/tailwatchdisable}],
    'mysql'      => [qw{/etc/mysqldisable /etc/mysqlddisable}],
);

my %installed_service_exceptions;
@installed_service_exceptions{ qw(dns ftp ftpd mail cpipv6), Cpanel::Services::AlwaysInstalled::SERVICES() } = ();

my $services_status_from_cpanel_config = {

    'mailman' => { key => 'skipmailman', meaning => 'disabled' },
};


sub are_provided {
    my ($service) = @_;

    if ( 'HASH' eq ref $service ) {

        $service = { %$service, items => $service->{'services'} };

        delete $service->{services};
    }

    require Cpanel::Validate::AnyAllMatcher;
    return Cpanel::Validate::AnyAllMatcher::match( $service, \&is_provided );
}


sub is_provided {
    my ($service) = @_;
    my $is_enabled = is_enabled($service);
    if ( index( $service, 'mysql' ) == 0 && !$is_enabled ) {
        require Cpanel::GlobalCache;
        my $has_remote_mysql = Cpanel::GlobalCache::data( 'cpanel', 'has_remote_mysql' );

        if ( !defined $has_remote_mysql ) {
            require Cpanel::MysqlUtils::MyCnf::Basic;
            $has_remote_mysql = Cpanel::MysqlUtils::MyCnf::Basic::is_remote_mysql();
        }

        return $has_remote_mysql;
    }
    return $is_enabled;
}


sub are_enabled {
    my ($service) = @_;

    if ( 'HASH' eq ref $service ) {

        $service = { %$service, items => $service->{'services'} };

        delete $service->{services};
    }

    require Cpanel::Validate::AnyAllMatcher;
    return Cpanel::Validate::AnyAllMatcher::match( $service, \&is_enabled );
}

sub is_enabled {
    my $service = shift;

    return -1 unless defined $service;

    if ( $service eq 'cpanalyticsd' ) {
        require Cpanel::Analytics::Enabled;
        return 'Cpanel::Analytics::Enabled'->can('is_enabled')->();
    }
    elsif ( $service eq 'cpgreylistd' ) {
        require Cpanel::GreyList::Config;
        return 'Cpanel::GreyList::Config'->can('is_enabled')->();
    }
    elsif ( $service eq 'cphulkd' ) {
        require Cpanel::Config::Hulk;
        return 'Cpanel::Config::Hulk'->can('is_enabled')->();
    }
    elsif ( $service eq 'imap' ) {
        return get_dovecot_enabled_protocols()->{'imap'} ? 1 : 0;
    }
    elsif ( $service eq 'pop' ) {
        return get_dovecot_enabled_protocols()->{'pop3'} ? 1 : 0;
    }
    elsif ( $service eq 'spamd' ) {
        return 0 unless is_enabled('exim');
    }
    elsif ( $service eq 'exim-altport' ) {
        require Cpanel::Services::List;
        return Cpanel::Services::List::canonicalize_service( $service, 1, {} )->{'enabled'};
    }
    elsif ( $service eq 'mysql' || $service eq 'mysqld' ) {
        $service = 'mysql';
    }
    elsif ( $service eq 'postgres' ) {
        $service = 'postgresql';
    }
    elsif ( $service eq 'cpdavd' ) {

        Cpanel::LoadModule::load_perl_module('Cpanel::ServiceConfig::cpdavd');

        return 0 if !Cpanel::ServiceConfig::cpdavd::is_needed();
    }
    elsif ( $service eq 'cpanel_php_fpm' ) {
        return 0 if Cpanel::Server::Type::is_dnsonly();
    }

    return 1 if ( $service eq 'dnsadmin' || $service eq 'cpsrvd' );

    if ( my $cpconfig_exception = $services_status_from_cpanel_config->{$service} ) {
        my $status = _process_service_status_from_cpconf(
            $service,
            $cpconfig_exception,
        );

        return $status if defined $status;
    }

    if ( !exists $installed_service_exceptions{$service} ) {

        require Cpanel::Services::Installed;
        return 0 if !Cpanel::Services::Installed::service_is_installed($service);
    }

    if ( $service eq 'spamd' ) {
        require Cpanel::Services::Enabled::Spamd;
        return eval { Cpanel::Services::Enabled::Spamd::is_enabled() } // do {
            warn;
            1;    # this defaults to on for historical reasons
        };
    }

    return _check_for_disabled_file($service);
}

sub _process_service_status_from_cpconf {
    my ( $service, $cpconfig_exception ) = @_;

    require Cpanel::Config::LoadCpConf;
    return -1 unless my $loadcpconf = 'Cpanel::Config::LoadCpConf'->can('loadcpconf_not_copy');
    my $cpconf = $loadcpconf->();
    my $value  = $cpconf->{ $cpconfig_exception->{'key'} };
    if ( $cpconfig_exception->{'meaning'} ) {
        if ( $cpconfig_exception->{'meaning'} eq 'disabled' ) {
            return !$value ? 1 : 0;
        }
        elsif ( $cpconfig_exception->{'meaning'} eq 'enabled' ) {
            return !!$value ? 1 : 0;
        }
    }

    if ( length $value ) {
        return 0 if $value eq 'disabled';
    }

    return undef;
}

sub _check_for_disabled_file {
    my $service = shift;

    if ( my $files = get_files_for_service($service) ) {
        foreach my $f (@$files) {
            return 0 if -e $f;

            warn "stat($f): $!" if $! != _ENOENT();
        }

        return 1;
    }

    return -1;
}

sub touch_disable_file {
    my $service = shift;
    return unless defined $service;

    return 1 if is_enabled($service) == 0;
    if ( $service eq 'cpgreylistd' ) {
        require Cpanel::GreyList::Config;
        return Cpanel::GreyList::Config::disable();
    }

    return 1 unless service_has_files($service);

    my $files = get_files_for_service($service);
    return unless defined $files && defined $files->[0];

    require Cpanel::FileUtils::TouchFile;
    return Cpanel::FileUtils::TouchFile::touchfile( $files->[0] );
}

sub remove_disable_files {
    my $service = shift;
    return unless defined $service;

    return 1 unless service_has_files($service);

    my $files = get_files_for_service($service);
    return unless defined $files;

    my $ok = 1;
    foreach my $f (@$files) {
        if ( -f $f && !-l $f ) {
            $ok = 0 if !unlink($f);
        }
    }

    return $ok;
}

sub service_has_files {
    my $service = shift;
    return unless defined $service;

    return if $service !~ m/^imap|pop$/ && exists $services_status_from_cpanel_config->{$service};
    return 1;
}

sub get_files_for_service {
    my $service = shift;
    return unless defined $service;

    return unless service_has_files($service);

    if ( !defined $disable_files_exceptions{$service} ) {

        return [ '/etc/' . $service . 'disable', '/etc/' . $service . 'isevil' ];
    }

    return ref $disable_files_exceptions{$service} ? $disable_files_exceptions{$service} : [ $disable_files_exceptions{$service} ];
}

sub get_dovecot_enabled_protocols {

    require Cpanel::LoadFile;
    require Cpanel::Dovecot::Constants;
    my $protos;
    local $@;
    eval {
        if ( -e $Cpanel::Dovecot::Constants::PROTOCOLS_FILE ) {

            $protos = Cpanel::LoadFile::load($Cpanel::Dovecot::Constants::PROTOCOLS_FILE);

        }
        else {
            my $conf = Cpanel::LoadFile::load($DOVECOT_CONF_FILE);
            if ( length $conf ) {
                ($protos) = $conf =~ m{^protocols:[ \t]*([^\n]+)}m;
            }
        }
    };
    warn if $@ && !$ENV{'CPANEL_BASE_INSTALL'};

    $protos =~ s{[ \t]+$}{} if length $protos;
    $protos ||= 'imap pop3';

    return { map { $_ => 1 } split( m{ }, $protos ) };
}

1;

} # --- END Cpanel/Services/Enabled.pm


{ # --- BEGIN Cpanel/MariaDB.pm
package Cpanel::MariaDB;


use cPstrict;

sub version_is_mariadb ($version) {

    return 0 unless defined $version && length $version;

    if ( $version =~ m{^(\d+\.\d+)\D*} ) {
        return ( $1 >= 10.0 ? 1 : 0 );
    }

    return 0 unless $version =~ qr{^[0-9]+$};

    return ( $version >= 100 ? 1 : 0 );
}

sub dbh_is_mariadb ($dbh) {
    return 0 unless defined $dbh;
    return 0 unless ref($dbh) =~ /DBI/ && $dbh->can('selectrow_array');

    my ($version_string) = $dbh->selectrow_array('SELECT VERSION()');
    return ( $version_string =~ /mariadb/i ) ? 1 : 0;
}

1;

} # --- END Cpanel/MariaDB.pm


{ # --- BEGIN Cpanel/MysqlUtils/Versions.pm
package Cpanel::MysqlUtils::Versions;


use cPstrict;

# use Cpanel::MariaDB ();
# use Cpanel::Context ();
# use Cpanel::OS      ();


sub get_first_newstyle_mysql_version {
    return '5.7';
}

sub get_first_mariadb_version {
    return '10.0';
}

sub get_supported_mariadb_versions {
    return (qw{10.0 10.1 10.2 10.3 10.5 10.6});
}

sub get_supported_mysql_versions {
    return (qw{5.5 5.6 5.7 8.0});
}

sub get_versions {

    return (qw{4.1 5.0 5.1 5.5 5.6 5.7 8.0 10.0 10.1 10.2 10.3 10.4 10.5 10.6});
}

my %DEPRECATED = ( '4.1' => 1, '5.0' => 1, '5.1' => 1 );

my $UPGRADE_TARGETS_BY_VERSION = {
    '4.1'  => [qw{5.5 5.6 5.7 10.5 10.6}],
    '5.0'  => [qw{5.5 5.6 5.7 10.5 10.6}],
    '5.1'  => [qw{5.5 5.6 5.7 10.5 10.6}],
    '5.5'  => [qw{5.5 5.6 5.7 10.5 10.6}],
    '5.6'  => [qw{5.6 5.7 10.5 10.6}],
    '5.7'  => [qw{5.7 8.0 10.5 10.6}],
    '8.0'  => [qw{8.0}],
    '10.0' => [qw{10.0 10.5 10.6}],
    '10.1' => [qw{10.1 10.5 10.6}],
    '10.2' => [qw{10.2 10.5 10.6}],
    '10.3' => [qw{10.3 10.5 10.6}],
    '10.4' => [qw{10.4 10.5 10.6}],
    '10.5' => [qw{10.5 10.6}],
    '10.6' => [qw{10.6}],
};

sub get_upgrade_targets ( $version = undef ) {
    if ( !$version ) {
        _die_trace("get_upgrade_targets requires a version");
    }
    return $UPGRADE_TARGETS_BY_VERSION->{$version};
}

my $UPGRADE_PATHS_FOR_TREE = {
    'MariaDB'      => [qw{10.5 10.6}],
    'Mysql-legacy' => [qw{5.5 5.6}],
    'Mysql'        => [qw{5.7 8.0}],
};

sub get_incremental_versions ( $from_version = undef, $to_version = undef ) {
    if ( !( $from_version && $to_version ) ) {
        _die_trace("get_incremental_versions requires a from and to version");
    }
    my @versions = get_versions();

    return grep { $_ > $from_version && $_ <= $to_version } get_versions();
}

sub get_rpm_target_names (@versions) {
    Cpanel::Context::must_be_list();
    if ( !@versions ) { @versions = get_versions() }

    tr/.//d for @versions;

    return map { Cpanel::MariaDB::version_is_mariadb($_) ? "MariaDB$_" : "MySQL$_" } @versions;
}

sub get_vendor_for_version ( $version = undef ) {
    if ( !$version ) {
        _die_trace("get_vendor_for_version requires a version");
    }

    if ( Cpanel::MariaDB::version_is_mariadb($version) ) {
        return 'MariaDB';
    }
    elsif ( $version >= get_first_newstyle_mysql_version() ) {
        return 'Mysql';
    }

    return 'Mysql-legacy';
}

sub get_installable_versions {
    my %unsupported_db = map { $_ => 1 } @{ Cpanel::OS::unsupported_db_versions() };
    return grep { !$DEPRECATED{$_} && !$unsupported_db{$_} } get_versions();
}

sub get_installable_versions_for_version ( $current_version = undef ) {
    if ( !$current_version ) {
        _die_trace("get_installable_versions_for_version requires a version");
    }

    if ( !$UPGRADE_TARGETS_BY_VERSION->{$current_version} ) {
        _die_trace("get_installable_versions_for_version does not know about $current_version");
    }

    my %unsupported_db = map { $_ => 1 } @{ Cpanel::OS::unsupported_db_versions() };

    return grep { !$DEPRECATED{$_} && !$unsupported_db{$_} } @{ $UPGRADE_TARGETS_BY_VERSION->{$current_version} };
}

sub get_upgrade_path_for_version ( $current_version = undef, $want_version = undef ) {
    if ( !$current_version || !$want_version ) {
        _die_trace("get_upgrade_path_for_version requires a current_version and a want_version");
    }

    if ( !$UPGRADE_TARGETS_BY_VERSION->{$current_version} ) {
        _die_trace("get_upgrade_path_for_version does not know about $current_version");
    }

    my @upgrade_targets = @{ $UPGRADE_TARGETS_BY_VERSION->{$current_version} };

    if ( $current_version eq $want_version || !grep { $_ eq $want_version } @upgrade_targets ) {
        return $current_version;
    }

    my $current_vendor = get_vendor_for_version($current_version);
    my $want_vendor    = get_vendor_for_version($want_version);

    if ( $want_vendor eq 'MariaDB' ) {
        return ($want_version);
    }

    return grep { $_ >= $current_version && $_ <= $want_version } @upgrade_targets;
}

sub _die_trace {
    require Cpanel::Carp;
    die Cpanel::Carp::safe_longmess(@_);
}


1;

} # --- END Cpanel/MysqlUtils/Versions.pm


{ # --- BEGIN Cpanel/FileLookup.pm
package Cpanel::FileLookup;


use strict;
use warnings;

# use Cpanel::Exception          ();
# use Cpanel::LoadFile::ReadFast ();
# use Cpanel::SV                 ();

use constant _ENOENT => 2;

my $max_buffer_size = 4194304;

sub filelookup {
    my ( $file, %OPTS ) = @_;
    my $key = $OPTS{'key'};

    open my $file_fh, '<:stdio', $file or do {
        if ( $! != _ENOENT() ) {
            die Cpanel::Exception::create( 'IO::FileOpenError', [ path => $file, mode => '<', error => $! ] );
        }

        return;
    };

    my $length = -f $file_fh && -s _;

    die "“$key” may not contain a “:”" if index( $key, ':' ) > -1;
    Cpanel::SV::untaint($key);
    substr( $key, 0, 4, '' ) if index( $key, 'www.' ) == 0;

    my $match         = "\n$key:";
    my $wwwmatch      = "\nwww.$key:";
    my $match_either  = "$key:";
    my $capture_match = qr/\n((?:www\.)?\Q$key\E:[^\n]*)/s;

    my $togo = $length;
    my $final_newline_position;
    my $bytes_read;
    my $final_newline_and_remainder;
    my $data = "\n";
    while ( $togo && ( $bytes_read = Cpanel::LoadFile::ReadFast::read_fast( $file_fh, $data, $togo > $max_buffer_size ? $max_buffer_size : $togo, length $data ) ) ) {
        $togo -= $bytes_read;
        $final_newline_position = rindex( $data, "\n" );

        $final_newline_and_remainder = ( $togo && $final_newline_position != -1 ) ? substr( $data, $final_newline_position, length $data, '' ) : "\n";

        if ( index( $data, $match_either ) > -1 && ( index( $data, $match ) > -1 || index( $data, $wwwmatch ) > -1 ) && $data =~ $capture_match ) {
            my $line = $1;

            next if $line =~ m/^\s*#/;    # handle beginning of line comments

            my $val = ( split( /:/, $line, 2 ) )[1];

            $val =~ s/[\r\n]//g;
            $val =~ s/\s+#.*$//g;         # handle end of line comments
            $val =~ s/^\s+//;
            $val =~ s/\s+$//;

            return $val;
        }
        $data = $final_newline_and_remainder if $togo;
    }

    return;
}

1;

} # --- END Cpanel/FileLookup.pm


{ # --- BEGIN Cpanel/AcctUtils/DomainOwner/Tiny.pm
package Cpanel::AcctUtils::DomainOwner::Tiny;


use strict;
use warnings;

# use Cpanel::ConfigFiles           ();
# use Cpanel::FileLookup            ();
# use Cpanel::Config::HasCpUserFile ();

my $domainowner_cache_hr;
my $true_domainowner_cache_hr;

our $CACHE_IS_SET           = 0;
our $DEFAULT_USER_TO_RETURN = 'root';


sub get_cache {
    return $domainowner_cache_hr;
}

sub build_truedomain_cache {
    require Cpanel::Config::LoadUserDomains;
    return ( $true_domainowner_cache_hr = Cpanel::Config::LoadUserDomains::loadtrueuserdomains( undef, 1 ) );
}

sub build_domain_cache {
    require Cpanel::Config::LoadUserDomains;
    $CACHE_IS_SET         = 1;
    $domainowner_cache_hr = scalar Cpanel::Config::LoadUserDomains::loaduserdomains( undef, 1 );
    return $domainowner_cache_hr;
}

sub clearcache {
    $CACHE_IS_SET              = 0;
    $domainowner_cache_hr      = {};
    $true_domainowner_cache_hr = {};
    return 1;
}


sub getdomainowner {
    my $owner = ( _getdomainowner(@_) )[0];

    return $owner eq $DEFAULT_USER_TO_RETURN ? ( exists $_[1]->{'default'} ? $_[1]->{'default'} : $owner ) : $owner;
}


sub getdomainowner_with_reason {

    my ( $owner, $reason ) = _getdomainowner(@_);

    if ( $owner eq $DEFAULT_USER_TO_RETURN ) {
        $owner = $_[1]->{'default'} if exists $_[1]->{'default'};
    }
    return ( $owner, $reason );
}

sub _set_cache {
    my ( $domain, $user, $reason ) = @_;
    my $entry = $domainowner_cache_hr->{$domain} = [ $user, $reason ];
    return @$entry;
}

sub domain_has_owner {
    return ( _getdomainowner( $_[0], { 'skiptruelookup' => 1 } ) )[0] eq $DEFAULT_USER_TO_RETURN ? 0 : 1;
}

sub _getdomainowner {    ## no critic qw(RequireArgUnpacking)
    return ($DEFAULT_USER_TO_RETURN)                                                                                           if ( length( $_[0] ) > 255 || length( $_[0] ) < 3 || $_[0] =~ tr{a-z0-9_.*-}{}c || index( $_[0], '..' ) != -1 );
    return ref $domainowner_cache_hr->{ $_[0] } ? @{ $domainowner_cache_hr->{ $_[0] } } : ( $domainowner_cache_hr->{ $_[0] } ) if exists $domainowner_cache_hr->{ $_[0] };

    return ($DEFAULT_USER_TO_RETURN) if $CACHE_IS_SET;    # If the cache is built no need to fall back since we have everything in memory

    my ( $domain, $opref ) = @_;

    if ( index( $domain, '*' ) == -1 ) {

        if ( my $uid = ( stat("$Cpanel::ConfigFiles::VALIASES_DIR/$domain") )[4] ) {
            local $@;
            eval 'require Cpanel::PwCache;' if !$INC{'Cpanel/PwCache.pm'};    ## no critic(ProhibitStringyEval)
            if ( !$@ ) {
                my $valias_user = ( 'Cpanel::PwCache'->can('getpwuid_noshadow')->($uid) )[0];
                if ( Cpanel::Config::HasCpUserFile::has_cpuser_file($valias_user) ) {
                    return _set_cache( $domain, $valias_user, 'A valiases file exists for this domain.' );
                }
            }

        }
    }

    my $is_root = $> == 0 ? 1 : 0;
    my $owner;
    if ( !$opref->{'skiptruelookup'} && ( $is_root || -r $Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE ) ) {
        $owner = Cpanel::FileLookup::filelookup( $Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE, 'key' => $domain );
    }
    if ( !$owner && ( $is_root || -r $Cpanel::ConfigFiles::USERDOMAINS_FILE ) ) {
        $owner = Cpanel::FileLookup::filelookup( $Cpanel::ConfigFiles::USERDOMAINS_FILE, 'key' => $domain );
    }

    if ($owner) {
        return _set_cache( $domain, $owner, 'A userdomains entry exists for this domain.' );
    }

    if ( !$is_root ) {
        local $@;
        eval 'require Cpanel::Config::LoadCpUserFile; require Cpanel::Config::HasCpUserFile; require Cpanel::PwCache;';    ## no critic qw(ProhibitStringyEval) -- quoted eval to hide this from perlcc
        if ( !$@ ) {
            my $current_user = ( Cpanel::PwCache::getpwuid($>) )[0];
            if ( Cpanel::Config::HasCpUserFile::has_readable_cpuser_file($current_user) ) {
                my $cpuser_ref = Cpanel::Config::LoadCpUserFile::loadcpuserfile($current_user);
                if ( $cpuser_ref && ( $cpuser_ref->{'DOMAIN'} eq $domain || grep { $_ eq $domain } @{ $cpuser_ref->{'DOMAINS'} } ) ) {
                    return _set_cache( $domain, $current_user, "This domain is in the current user's cpuser file." );
                }
            }
        }
        else {
            die "Failed to load Cpanel::Config::LoadCpUserFile or Cpanel::PwCache: $@";

        }
    }

    return ($DEFAULT_USER_TO_RETURN);
}

1;

} # --- END Cpanel/AcctUtils/DomainOwner/Tiny.pm


{ # --- BEGIN Cpanel/Transaction/File/Read/JSON.pm
package Cpanel::Transaction::File::Read::JSON;


use strict;

# use Cpanel::LoadFile::ReadFast ();
# use Cpanel::JSON               ();

my $READ_SIZE = 262140;

sub _init_data {
    my ( $self, %opts ) = @_;

    return \undef if -z $self->{'_fh'};

    my $func = \&Cpanel::JSON::Load;
    my $txt  = '';
    Cpanel::LoadFile::ReadFast::read_all_fast( $self->{'_fh'}, $txt );

    my $load = $func->($txt);

    return ref($load) ? $load : \$load;
}

1;

} # --- END Cpanel/Transaction/File/Read/JSON.pm


{ # --- BEGIN Cpanel/Transaction/File/BaseReader.pm
package Cpanel::Transaction::File::BaseReader;



use strict;
use warnings;

# use Cpanel::Autodie   qw(open exists stat close);
INIT { Cpanel::Autodie->import(qw{open exists stat close}); }
# use Cpanel::Exception ();

my $PACKAGE = __PACKAGE__;

sub new {
    my ( $class, %opts ) = @_;

    die "No file!" if !length $opts{'path'};

    my $path = $opts{'path'};

    my $self = bless {}, $class;

    my $data;

    if ( !Cpanel::Autodie::exists($path) ) {
        $data = \undef;
    }
    else {
        Cpanel::Autodie::open( my $read_fh, '<', $path );

        $self->{'_original_mtime'} = ( Cpanel::Autodie::stat($read_fh) )[9];
        local $self->{'_fh'} = $read_fh;

        $data = $self->_init_data_with_catch(%opts);

        Cpanel::Autodie::close( $read_fh, $path );
    }

    return bless { _data => $data, _did_init_data => 1 }, $class;
}

sub _init_data_with_catch {
    my ( $self, %opts ) = @_;

    my $data;
    local $@;

    eval { $data = $self->_init_data(%opts); 1 } or do {
        die Cpanel::Exception->create(
            'The system failed to load and to parse the file “[_1]” because of an error: [_2]',
            [ $opts{'path'}, Cpanel::Exception::get_string($@) ]
        );
    };

    return $data;
}

sub _init_data {
    die "Do not instantiate $PACKAGE directly; use a subclass instead.";
}

sub _get_data {
    if ( !$_[0]->{'_did_init_data'} ) {
        $_[0]->{'_data'}          = $_[0]->_init_data_with_catch( %{ $_[0]->{'_opts'} } );
        $_[0]->{'_did_init_data'} = 1;
    }

    return $_[0]->{'_data'};
}

sub get_original_mtime {
    return $_[0]->{'_original_mtime'};
}

sub path_is_newer {

    return ( Cpanel::Autodie::stat( $_[0]->{'_path'} ) )[9] != $_[0]->{'_original_mtime'} ? 1 : 0;
}

sub get_fh {
    return $_[0]->{'_fh'};
}

sub get_mtime {
    return ( stat( $_[0]->{'_fh'} ) )[9];
}

no warnings 'once';
*get_data = \&_get_data;

1;

} # --- END Cpanel/Transaction/File/BaseReader.pm


{ # --- BEGIN Cpanel/Transaction/File/JSONReader.pm
package Cpanel::Transaction::File::JSONReader;



use strict;

# use Cpanel::Transaction::File::Read::JSON();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Transaction::File::Read::JSON); }
# use Cpanel::Transaction::File::BaseReader();
BEGIN { push @ISA, qw(Cpanel::Transaction::File::BaseReader); }

1;

} # --- END Cpanel/Transaction/File/JSONReader.pm


{ # --- BEGIN Cpanel/FileUtils/Read.pm
package Cpanel::FileUtils::Read;


use cPstrict;


use Errno ();
use Try::Tiny;

# use Cpanel::Exception  ();
# use Cpanel::LoadModule ();


sub for_each_line {
    my ( $path, $todo_cr ) = @_;

    return _for_each_thingie(
        path          => $path,
        todo_cr       => $todo_cr,
        whatsit       => 'File',
        iterator_type => 'Line',
        do_open       => sub { open( my $fh, '<', $path ) or return; $fh },
        do_close      => sub { close shift },
    );
}

sub for_each_directory_node ( $path, $todo_cr ) {
    return _for_each_directory_node( $path, $todo_cr, 0 );
}

sub for_each_directory_node_if_exists ( $path, $todo_cr ) {
    return _for_each_directory_node( $path, $todo_cr, 1 );
}

sub _for_each_directory_node ( $path, $todo_cr, $ignore_enoent_yn ) {    ## no critic qw(ManyArgs) - mis-parse
    return _for_each_thingie(
        path          => $path,
        todo_cr       => $todo_cr,
        whatsit       => 'Directory',
        iterator_type => 'DirectoryNode',
        do_open       => sub { opendir( my $fh, $path ) or return; $fh },
        do_close      => sub { closedir shift },
        ignore_enoent => $ignore_enoent_yn,
    );
}

sub _for_each_thingie {
    my %opts = @_;

    my $iterator_class = "Cpanel::FileUtils::Read::$opts{'iterator_type'}Iterator";

    Cpanel::LoadModule::load_perl_module($iterator_class);

    local $!;

    my $fh = $opts{'do_open'}->() or do {
        if ( $! == Errno::ENOENT && $opts{'ignore_enoent'} ) {
            return 0;
        }

        if ( $opts{'whatsit'} eq 'Directory' ) {
            die Cpanel::Exception::create( "IO::DirectoryOpenError", [ path => $opts{'path'}, error => $! ] );
        }
        die Cpanel::Exception::create( "IO::FileOpenError", [ path => $opts{'path'}, error => $! ] );
    };

    try {
        $iterator_class->new( $fh, $opts{'todo_cr'} );
    }
    catch {
        if ( UNIVERSAL::isa( $_, "Cpanel::Exception::IO::$opts{'whatsit'}ReadError" ) ) {
            if ( $opts{'whatsit'} eq 'Directory' ) {
                die Cpanel::Exception::create( "IO::DirectoryReadError", [ error => $_->get('error'), path => $opts{'path'} ] );
            }
            die Cpanel::Exception::create( "IO::FileReadError", [ error => $_->get('error'), path => $opts{'path'} ] );
        }

        die $_;
    };

    $opts{'do_close'}->($fh) or do {
        if ( $opts{'whatsit'} eq 'Directory' ) {
            die Cpanel::Exception::create( "IO::DirectoryCloseError", [ path => $opts{'path'}, error => $! ] );
        }
        die Cpanel::Exception::create( "IO::FileCloseError", [ path => $opts{'path'}, error => $! ] );
    };

    return 1;
}

1;

} # --- END Cpanel/FileUtils/Read.pm


{ # --- BEGIN Cpanel/iContact/EventImportance/Legacy.pm
package Cpanel::iContact::EventImportance::Legacy;


use strict;

# use Cpanel::FileUtils::Read ();

our $_legacy_iclevels_file = '/var/cpanel/iclevels.conf';

sub get_data_struct_from_legacy {
    my %legacy;

    if ( -s $_legacy_iclevels_file ) {
        Cpanel::FileUtils::Read::for_each_line(
            $_legacy_iclevels_file,
            sub {
                chomp;
                s/\r//g;
                if (m/^(\S+)\s+(\S+)/) {
                    my $app   = $1;
                    my $level = $2;
                    next if !length $level;

                    $legacy{$app} = $level;
                }
            },
        );
    }

    return \%legacy;
}

1;

} # --- END Cpanel/iContact/EventImportance/Legacy.pm


{ # --- BEGIN Cpanel/iContact/EventImportance.pm
package Cpanel::iContact::EventImportance;



use strict;
use warnings;

# use Cpanel::Transaction::File::JSONReader     ();    # PPI USE OK -- used in new via __TRANSACTION_CLASS
# use Cpanel::iContact::EventImportance::Legacy ();

our $_datastore_file = '/var/cpanel/icontact_event_importance.json';

our %NAME_TO_NUMBER = (
    'High'     => 1,
    'Medium'   => 2,
    'Low'      => 3,
    'Disabled' => 0,
);

our $DEFAULT_IMPORTANCE = $NAME_TO_NUMBER{'Low'};

sub new {
    my ($class) = @_;

    my $self = bless {}, $class;

    my $trans_class = $self->__TRANSACTION_CLASS();
    $self->{'_trans'} = $trans_class->new( path => $_datastore_file );

    $self->{'_data'} = $self->{'_trans'}->get_data();

    if ( 'SCALAR' eq ref $self->{'_data'} ) {
        $self->{'_data'} = {};

        $self->_init_data_from_legacy();
    }

    $self->_ensure_that_defaults_are_there();

    return $self;
}


sub __TRANSACTION_CLASS {
    return 'Cpanel::Transaction::File::JSONReader';
}


sub get_mtime {
    my ($self) = @_;

    return $self->{'_trans'}->get_original_mtime();
}

sub get_event_importance {
    my ( $self, $app, $event ) = @_;

    my $data = $self->{'_data'};

    return $DEFAULT_IMPORTANCE if !$data->{$app};

    return $data->{$app}{$event} if length $event && exists $data->{$app}{$event};

    return $data->{$app}{'*'};
}

sub get_application_importance {
    my ( $self, $app ) = @_;

    return $self->get_event_importance( $app, '*' );
}

sub get_all_contact_importance {
    my ($self) = @_;

    my @importance;
    my %number_to_name = reverse %NAME_TO_NUMBER;
    foreach my $app ( sort keys %{ $self->{'_data'} } ) {
        foreach my $event ( sort keys %{ $self->{'_data'}{$app} } ) {
            my $number = $self->{'_data'}{$app}{$event};
            push @importance, { 'app' => $app, 'event' => $event, 'importance' => $number, 'name' => $number_to_name{$number} };
        }

    }
    return \@importance;
}

sub get_application_importance_setting {
    my ( $self, $app ) = @_;

    return $self->get_event_importance_setting( $app, '*' );
}

sub get_event_importance_setting {
    my ( $self, $app, $event ) = @_;

    my $data = $self->{'_data'};

    return $data->{$app} && $data->{$app}{$event};
}


sub _ensure_that_defaults_are_there {
    my ($self) = @_;

    my ( $high_importance, $medium_importance, $low_importance, $disabled ) = map { $NAME_TO_NUMBER{$_} } qw( High Medium Low Disabled );

    my %default = (
        'Accounts'                             => $low_importance,
        'Accounts::ChildDedistributionFailure' => $high_importance,
        'Accounts::ChildDedistributionSuccess' => $low_importance,
        'Accounts::ChildDistributionFailure'   => $high_importance,
        'Accounts::ChildDistributionSuccess'   => $low_importance,
        'Accounts::ChildRedistributionFailure' => $high_importance,
        'Accounts::ChildRedistributionSuccess' => $low_importance,
        'AdminBin'                             => $low_importance,
        'Backup'                               => $medium_importance,
        'Backup::Delayed'                      => $high_importance,
        'Backup::Disabled'                     => $high_importance,
        'Backup::Failure'                      => $high_importance,
        'Backup::PreBackupNotice'              => $low_importance,
        'Backup::Success'                      => $low_importance,
        'Backup::Transport'                    => $high_importance,
        'BandwidthUsageExceeded'               => $medium_importance,
        'ChangePassword'                       => $low_importance,
        'Check'                                => $low_importance,
        'Check::Biglog'                        => $high_importance,
        'Check::CpanelPackages'                => $high_importance,
        'Check::EximConfig'                    => $high_importance,
        'Check::Hack'                          => $high_importance,
        'Check::IP'                            => $high_importance,
        'Check::ImmutableFiles'                => $high_importance,
        'Check::InvalidDomains'                => $medium_importance,
        'Check::MySQL'                         => $high_importance,
        'Check::MysqlConnection'               => $high_importance,
        'Check::Oops'                          => $high_importance,
        'Check::SSLCertExpired'                => $high_importance,
        'Check::SSLCertExpiresSoon'            => $medium_importance,
        'Check::Smart'                         => $high_importance,
        'Check::ValidServerHostname'           => $high_importance,
        'Check::UnmonitoredEnabledServices'    => $high_importance,
        'Check::SecurityAdvisorStateChange'    => $high_importance,
        'Check::HostnameOwnedByUser'           => $high_importance,
        'Check::Resolvers'                     => $high_importance,
        'Check::PdnsConf'                      => $medium_importance,
        'Check::LocalConfTemplate'             => $medium_importance,
        'CloudLinux'                           => $medium_importance,
        'Config'                               => $high_importance,
        'ConvertAddon'                         => $high_importance,
        'DemoMode'                             => $high_importance,
        'Deprecated::API1'                     => $medium_importance,
        'Deprecated::EA3RPMs'                  => $medium_importance,
        'DigestAuth'                           => $medium_importance,
        'DnsAdmin'                             => $medium_importance,
        'DnsAdmin::ClusterError'               => $medium_importance,
        'DnsAdmin::UnreachablePeer'            => $high_importance,
        'DnsAdmin::DnssecError'                => $medium_importance,
        'Solr::Maintenance'                    => $medium_importance,
        'EasyApache'                           => $high_importance,
        'EasyApache::EA4_TemplateCheckUpdated' => $high_importance,
        'EasyApache::EA4_ConflictRemove'       => $high_importance,
        'Greylist'                             => $low_importance,
        'ImportMyDNSdb'                        => $low_importance,
        'ImportMyDNSdb::Failure'               => $high_importance,
        'ImportMyDNSdb::InProgress'            => $low_importance,
        'ImportMyDNSdb::Success'               => $low_importance,
        'Install'                              => $low_importance,
        'Install::CheckcPHulkDB'               => $medium_importance,
        'Install::PackageExtension'            => $low_importance,
        'Install::FixcPHulkConf'               => $low_importance,
        'Install::CheckRemoteMySQLVersion'     => $low_importance,
        'Logd'                                 => $low_importance,
        'Logger'                               => $low_importance,
        'Notice'                               => $low_importance,
        'NSD'                                  => $low_importance,
        'NSD::BadZones'                        => $high_importance,
        'OutdatedSoftware::Notify'             => $medium_importance,
        'OverLoad::CpuWatch'                   => $medium_importance,
        'OverLoad::LogRunner'                  => $medium_importance,
        'Quota'                                => $low_importance,
        'Quota::Broken'                        => $high_importance,
        'Quota::DiskWarning'                   => $low_importance,
        'Quota::RebootRequired'                => $medium_importance,
        'Quota::SetupComplete'                 => $low_importance,
        'RPMVersions'                          => $high_importance,
        'StuckScript'                          => $high_importance,
        'TwoFactorAuth::UserEnable'            => $low_importance,
        'TwoFactorAuth::UserDisable'           => $low_importance,
        'Update'                               => $high_importance,
        'Update::Blocker'                      => $high_importance,
        'Update::ServiceDeprecated'            => $high_importance,
        'Update::Now'                          => $high_importance,
        'appconfig'                            => $low_importance,
        'cPHulk'                               => $low_importance,
        'cPHulk::BruteForce'                   => $low_importance,
        'cPHulk::Login'                        => $low_importance,
        'chkservd'                             => $high_importance,
        'chkservd::DiskUsage'                  => $high_importance,
        'chkservd::Hang'                       => $high_importance,
        'chkservd::OOM'                        => $high_importance,
        'MailServer::OOM'                      => $medium_importance,
        'Mail::SpammersDetected'               => $disabled,
        'SSL::CertificateExpiring'             => $medium_importance,
        'SSL::LinkedNodeCertificateExpiring'   => $high_importance,
        'SSL::CheckAllCertsWarnings'           => $medium_importance,
        'Monitoring::SignupComplete'           => $low_importance,

        'AutoSSL::CertificateExpiring'         => $low_importance,
        'AutoSSL::CertificateExpiringCoverage' => $low_importance,
        'AutoSSL::CertificateRenewalCoverage'  => $low_importance,

        'AutoSSL::CertificateInstalled'                 => $low_importance,
        'AutoSSL::CertificateInstalledReducedCoverage'  => $high_importance,
        'AutoSSL::CertificateInstalledUncoveredDomains' => $medium_importance,

        'AutoSSL::DynamicDNSNewCertificate' => $medium_importance,

        'Mail::ClientConfig'        => $low_importance,
        'Mail::HourlyLimitExceeded' => $low_importance,
        'Mail::SendLimitExceeded'   => $low_importance,
        'cpbackup'                  => $medium_importance,
        'cpbackupdisabled'          => $high_importance,
        'iContact'                  => $medium_importance,
        'installbandwidth'          => $high_importance,
        'killacct'                  => $low_importance,
        'parkadmin'                 => $low_importance,
        'queueprocd'                => $high_importance,
        'rpm.versions'              => $high_importance,
        'suspendacct'               => $low_importance,
        'sysup'                     => $high_importance,
        'unsuspendacct'             => $low_importance,
        'upacct'                    => $low_importance,
        'upcp'                      => $high_importance,
        'wwwacct'                   => $low_importance,
        'Stats'                     => $medium_importance,

        'Market' => $high_importance,

        'Application' => $high_importance,
    );

    my $self_data_hr = $self->{'_data'};

    for my $key ( keys %default ) {
        my ( $namespace, $notification ) = split( m{::}, $key );
        $notification ||= '*';
        if ( !defined $self_data_hr->{$namespace}{$notification} ) {
            $self_data_hr->{$namespace}{$notification} = $default{$key};
        }
    }

    my %event_importances = (
        cPHulk => {

            Login => $high_importance,
        },
    );

    return 1;
}

sub _init_data_from_legacy {
    my ($self) = @_;

    my $legacy_data_hr = Cpanel::iContact::EventImportance::Legacy::get_data_struct_from_legacy();

    for my $app ( keys %$legacy_data_hr ) {

        $self->{'_data'}{$app}{'*'} = $legacy_data_hr->{$app};
    }

    return;
}

1;

} # --- END Cpanel/iContact/EventImportance.pm


{ # --- BEGIN Cpanel/iContact/Providers.pm


package Cpanel::iContact::Providers;

use strict;
# use Cpanel::ConfigFiles        ();
# use Cpanel::ArrayFunc::Uniq    ();
# use Cpanel::LoadModule::Name   ();
# use Cpanel::LoadModule::Custom ();

my @module_list;
my %KNOWN_PROVIDERS = ();

my $namespace  = 'Cpanel::iContact::Provider::Schema';
my $schema_dir = 'Cpanel/iContact/Provider/Schema';
our $MODULE_DIR         = "$Cpanel::ConfigFiles::CPANEL_ROOT/$schema_dir";
our $CUSTOM_MODULES_DIR = "$Cpanel::ConfigFiles::CUSTOM_PERL_MODULES_DIR/$schema_dir";

my @displays_keys = qw(display_name icon_name icon verification_api);


my %Conf;

sub get_settings {
    return %Conf if %Conf;
    foreach my $module ( _get_all_icontact_modules() ) {
        %Conf = ( %Conf, %{ "$namespace\:\:$module"->get_settings() } );
    }

    return %Conf;
}


sub augment_shadow_keys {
    my ($shadow_ref) = @_;

    foreach my $module ( _get_all_icontact_modules() ) {
        my $ref = "$namespace\:\:$module"->get_settings();
        foreach my $setting ( keys %{$ref} ) {
            if ( $ref->{$setting}{'shadow'} ) {
                $shadow_ref->{$setting} = '';
            }
        }

    }
    return 1;

}


sub augment_icontact_providers {
    my ($providers_ref) = @_;

    foreach my $module ( _get_all_icontact_modules() ) {
        $providers_ref->{ _key_from_module($module) } = $module;
    }
    return 1;

}


sub augment_method_display {
    my ($method_display_ref) = @_;

    foreach my $module ( _get_all_icontact_modules() ) {
        my $modname = _key_from_module($module);
        my $ref     = "$namespace\:\:$module"->get_config();
        foreach my $display_key (@displays_keys) {
            if ( exists $ref->{$display_key} ) {
                $method_display_ref->{$modname}{$display_key} = $ref->{$display_key};
            }
        }
    }
    return 1;

}


sub augment_contacts_with_default_levels {
    my ($contact_ref) = @_;

    foreach my $module ( _get_all_icontact_modules() ) {
        $contact_ref->{ _key_from_module($module) }{'level'} = $Cpanel::iContact::RECEIVES_NAME_TO_NUMBER{ "$namespace\:\:$module"->get_config()->{'default_level'} } // $Cpanel::iContact::RECEIVES_NAME_TO_NUMBER{'All'};
    }
    return 1;
}


sub augment_tweak_texts {
    my ($tweak_text_ref) = @_;

    my %known_keys = map { $_ => 1 } @{ $tweak_text_ref->{'TS_display'}->[0]->[1] };

    foreach my $module ( _get_all_icontact_modules() ) {
        my $ref = "$namespace\:\:$module"->get_settings();

        foreach my $setting ( sort keys %{$ref} ) {
            if ( !exists $known_keys{$setting} ) {
                push @{ $tweak_text_ref->{'TS_display'}->[0]->[1] }, $setting;
                $known_keys{$setting} = 1;
            }
            $tweak_text_ref->{$setting} ||= $ref->{$setting};
        }

    }

    return 1;

}


sub augment_contact_settings {
    my ( $wwwacct_ref, $contacts ) = @_;
    foreach my $module ( _get_all_icontact_modules() ) {
        my $ref = "$namespace\:\:$module"->get_settings();
        foreach my $setting ( keys %{$ref} ) {

            my $key_from_module = _key_from_module($module);
            $contacts->{$key_from_module}{$setting} = $wwwacct_ref->{$setting} if $setting ne $key_from_module;
        }
    }
    return $contacts;
}

sub _get_all_icontact_modules {
    return @module_list if @module_list;

    require Cpanel::iContact;

    @module_list = sort( Cpanel::ArrayFunc::Uniq::uniq(
            Cpanel::LoadModule::Name::get_module_names_from_directory($CUSTOM_MODULES_DIR),
            Cpanel::LoadModule::Name::get_module_names_from_directory($MODULE_DIR),
    ) );

    foreach my $module (@module_list) {
        Cpanel::LoadModule::Custom::load_perl_module("$namespace\:\:$module") if !$INC{"$schema_dir/$module.pm"};
    }

    return @module_list;
}

sub _key_from_module {
    return 'CONTACT' . uc( $_[0] );
}

1;

} # --- END Cpanel/iContact/Providers.pm


{ # --- BEGIN Cpanel/Validate/EmailLocalPart.pm
package Cpanel::Validate::EmailLocalPart;


use strict;
use warnings;

my %reserved_localparts;

sub _init () {
    my @reserved_localparts_list = qw(shadow passwd quota _archive _mainaccount _privs.json _privs.cache shadow.lock passwd.lock quota.lock _archive.lock _mainaccount.lock _privs.json.lock _privs.cache.lock cpanel);
    @reserved_localparts{@reserved_localparts_list} = (1) x scalar @reserved_localparts_list;

    {
        no warnings 'redefine';
        *_init = sub () { };
    }

    return 1;
}

sub is_valid {
    return defined $_[0] && $_[0] =~ /\A[a-zA-Z0-9!#\$\-=?^_{}~]+(?:\.[a-zA-Z0-9!#\$\-=?^_{}~]+)*\z/;
}

sub get_name_and_domain {
    my ($name) = @_;
    return unless defined $name;
    return split( /@/, $name, 2 );
}

sub is_reserved {
    my ($localpart) = @_;
    _init();
    return 1 if exists $reserved_localparts{$localpart};
    return;
}

sub list_reserved_localparts {
    _init();
    return keys %reserved_localparts;
}
1;

} # --- END Cpanel/Validate/EmailLocalPart.pm


{ # --- BEGIN Cpanel/WildcardDomain/Tiny.pm
package Cpanel::WildcardDomain::Tiny;


use strict;
use warnings;



sub is_wildcard_domain {
    return ( index( $_[0], '*.' ) == 0 ? 1 : 0 );
}


sub contains_wildcard_domain {
    return ( index( $_[0], '*' ) > -1 ? 1 : 0 );
}

1;    # Magic true value required at end of module

} # --- END Cpanel/WildcardDomain/Tiny.pm


{ # --- BEGIN Cpanel/Validate/EmailCpanel.pm
package Cpanel::Validate::EmailCpanel;


use strict;
use warnings;
# use Cpanel::Validate::EmailLocalPart ();
# use Cpanel::WildcardDomain::Tiny     ();

sub is_valid {
    my ($name) = @_;
    return unless defined $name;

    my ( $local, $domain ) = get_name_and_domain($name);
    return unless defined $local and defined $domain;
    return Cpanel::Validate::EmailLocalPart::is_valid($local) && is_domain_valid($domain);
}

sub get_name_and_domain {
    my ($name) = @_;
    return unless defined $name;
    my ( $local, $domain ) = split( /\@/, $name, 2 );
    return ( length $local ? $local : undef, length $domain ? $domain : undef );
}

sub has_email_separator {
    my ($str) = @_;
    return scalar $str =~ /\@/;
}

sub is_domain_valid {
    my ($domain) = @_;
    return unless defined $domain;
    return 0 if Cpanel::WildcardDomain::Tiny::is_wildcard_domain($domain);
    return scalar $domain =~ m/\A[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?(?:\.[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?)*\z/;
}

1;

} # --- END Cpanel/Validate/EmailCpanel.pm


{ # --- BEGIN Cpanel/Validate/IP/v4.pm
package Cpanel::Validate::IP::v4;


use strict;
use warnings;

sub is_valid_ipv4 {
    my ($ip) = @_;
    return unless $ip;    # False scalars are never an _[0].

    my @segments = split /\./, $ip, -1;
    return unless scalar @segments == 4;

    my $octet_index;
    for my $octet_value (@segments) {
        return if !_valid_octet( $octet_value, ++$octet_index );
    }

    return 1;
}

sub is_valid_cidr4 {
    my ($ip) = @_;

    return unless defined $ip && $ip;
    my ( $ip4, $mask ) = split /\//, $ip;
    return if !defined $mask || !length $mask || $mask =~ tr/0-9//c;

    return is_valid_ipv4($ip4) && 0 < $mask && $mask <= 32;
}

sub _valid_octet {
    my ( $octet_value, $octet_index ) = @_;
    return (
        !length $octet_value                                                ||    #
          $octet_value =~ tr/0-9//c                                         ||    #
          $octet_value > 255                                                ||    #
          ( substr( $octet_value, 0, 1 ) == 0 && length($octet_value) > 1 ) ||    # Only dec values are permitted
          $octet_index == 1 && length($octet_value) && !$octet_value              # First oct can't be zero.
    ) ? 0 : 1;
}

1;

} # --- END Cpanel/Validate/IP/v4.pm


{ # --- BEGIN Cpanel/Validate/IP.pm
package Cpanel::Validate::IP;


use strict;
use warnings;

# use Cpanel::Validate::IP::v4 ();

sub is_valid_ipv6 {
    my ($ip) = @_;
    return unless defined $ip && $ip;

    if (   ( substr( $ip, 0, 1 ) eq ':' && substr( $ip, 1, 1 ) ne ':' )
        || ( substr( $ip, -1, 1 ) eq ':' && substr( $ip, -2, 1 ) ne ':' ) ) {
        return;    # Can't have single : on front or back
    }

    my @seg = split /:/, $ip, -1;    # -1 to keep trailing empty fields

    shift @seg if $seg[0] eq '';
    pop @seg   if $seg[-1] eq '';

    my $max = 8;
    if ( index( $seg[-1], '.' ) > -1 ) {
        return unless Cpanel::Validate::IP::v4::is_valid_ipv4( pop @seg );
        $max -= 2;
    }

    my $cmp;
    for my $seg (@seg) {
        if ( !defined $seg || $seg eq '' ) {

            return if $cmp;
            ++$cmp;
            next;
        }
        return if $seg =~ tr/0-9a-fA-F//c || length $seg == 0 || length $seg > 4;
    }
    if ($cmp) {

        return ( @seg && @seg <= $max ) && 1;    # true returned as 1
    }

    return $max == @seg;
}

sub is_valid_ipv6_prefix {
    my ($ip) = @_;
    return unless $ip;
    my ( $ip6, $mask ) = split /\//, $ip;
    return unless defined $mask;
    return if !length $mask || $mask =~ tr/0-9//c;
    return is_valid_ipv6($ip6) && 0 < $mask && $mask <= 128;
}

sub is_valid_ip {
    return !defined $_[0] ? undef : index( $_[0], ':' ) > -1 ? is_valid_ipv6(@_) : Cpanel::Validate::IP::v4::is_valid_ipv4(@_);
}

sub ip_version {
    return 4 if Cpanel::Validate::IP::v4::is_valid_ipv4(@_);
    return 6 if is_valid_ipv6(@_);
    return;
}

sub is_valid_ip_cidr_or_prefix {
    return unless defined $_[0];
    if ( $_[0] =~ tr/:// ) {
        return $_[0] =~ tr{/}{} ? is_valid_ipv6_prefix(@_) : is_valid_ipv6(@_);
    }
    return $_[0] =~ tr{/}{} ? Cpanel::Validate::IP::v4::is_valid_cidr4(@_) : Cpanel::Validate::IP::v4::is_valid_ipv4(@_);
}

sub is_valid_ip_range_cidr_or_prefix {
    my $str = shift;
    return 0 if !$str;
    return 1 if is_valid_ip_cidr_or_prefix($str);

    my @pieces = split /-/, $str, 2;
    return 1 if 2 == grep { defined($_) } map { Cpanel::Validate::IP::v4::is_valid_ipv4($_) } @pieces;
    return 1 if 2 == grep { defined($_) } map { is_valid_ipv6($_) } @pieces;
    return 0;
}

1;

} # --- END Cpanel/Validate/IP.pm


{ # --- BEGIN Cpanel/Validate/Domain/Tiny.pm
package Cpanel::Validate::Domain::Tiny;


use strict;
use warnings;

# use Cpanel::Debug        ();
# use Cpanel::Validate::IP ();

sub domain_meets_basic_requirements {
    my ( $domainname, $quiet ) = @_;
    return wantarray ? ( 0, 'invalid domain name specified' ) : 0 unless defined $domainname;

    if (
        $domainname =~ tr{:0-9}{} &&    # It cannot be an ip address if it does not have a digit or a : in it
        $domainname !~ tr{g-z}{}  &&    # It cannot be an ip address if has non-hex characters
        Cpanel::Validate::IP::is_valid_ip($domainname)
    ) {
        Cpanel::Debug::log_warn( $domainname . ' is an IP address, not a domain name' ) if !$quiet;
        return wantarray ? ( 0, 'argument is an IP address, not a domain name' ) : 0;
    }

    if ( length($domainname) > 254 ) {
        Cpanel::Debug::log_warn( $domainname . ' domain name exceeds 254 characters' ) if !$quiet;
        return wantarray ? ( 0, 'domain name exceeds 254 characters' ) : 0;
    }

    elsif ($domainname !~ m/[.][a-z0-9]+$/i
        && $domainname !~ m/[.]xn--[a-z0-9-]+$/i ) {
        Cpanel::Debug::log_warn( $domainname . ' domain name must have a valid TLD label' ) if !$quiet;
        return wantarray ? ( 0, 'domain name must have a valid TLD label' ) : 0;
    }

    if ( index( $domainname, '.' ) == -1 ) {
        Cpanel::Debug::log_warn("invalid domain name $domainname") if !$quiet;
        return wantarray ? ( 0, "invalid domain name $domainname" ) : 0;
    }

    return wantarray ? ( 1, 'ok' ) : 1;
}
sub validdomainname {
    my ( $domainname, $quiet ) = @_;

    my ( $status, $msg ) = domain_meets_basic_requirements( $domainname, $quiet );
    return wantarray ? ( $status, $msg ) : $status if !$status;

  LABELS_LOOP:
    foreach my $label ( split( /\./, $domainname ) ) {

        if (
               length($label) < 64
            && length($label) > 0
            && (

                $label =~ m{
                            \A
                            [a-z0-9]
                            [a-z0-9-]*
                            [a-z0-9]
                            \z
                        }xmsi
                ||

                $label =~ m{
                            \A
                            [a-z0-9]
                            \z
                        }xmsi
            )
        ) {
            next LABELS_LOOP;
        }

        Cpanel::Debug::log_warn("domain name element $label does not conform to requirements") if !$quiet;
        return wantarray ? ( 0, "domain name element $label does not conform to requirements" ) : 0;
    }
    return wantarray ? ( 1, $domainname ) : 1;
}

1;

} # --- END Cpanel/Validate/Domain/Tiny.pm


{ # --- BEGIN Cpanel/Validate/Domain.pm
package Cpanel::Validate::Domain;


use strict;
use warnings;

our $VERSION = '1.0';

# use Cpanel::Exception              ();
# use Cpanel::Sys::Hostname          ();
# use Cpanel::Validate::Domain::Tiny ();

sub valid_wild_domainname {
    my ( $domain, $quiet ) = @_;
    return Cpanel::Validate::Domain::Tiny::validdomainname( $domain, $quiet ) unless index( $domain, '*.' ) > -1;

    return Cpanel::Validate::Domain::Tiny::validdomainname( substr( $domain, 2 ), $quiet );
}

sub valid_rfc_domainname_or_die {
    my ($domain) = @_;

    return _valid_or_die( $domain, \&Cpanel::Validate::Domain::Tiny::validdomainname );
}

sub valid_wild_domainname_or_die {
    my ($domain) = @_;

    return _valid_or_die( $domain, \&valid_wild_domainname );
}

sub valid_domainname_for_customer_or_die {
    my ($domain) = @_;

    if ( !is_valid_cpanel_domain( $domain, my $why ) ) {
        die Cpanel::Exception::create( 'DomainNameNotAllowed', [ given => $domain, why => $why ] );
    }

    return 1;
}

sub is_cpanel_only_domain {
    return
         $_[0] eq 'cpanel.net'
      || $_[0] eq 'cpanel.com'
      || $_[0] =~ m/\.(?:cpanel\.(?:net|com))\z/i;
}

sub is_disallowed_domain {
    return
         $_[0] eq 'ruby-on-rails.db'
      || $_[0] eq 'ruby-on-rails-rewrites.db'
      || $_[0] eq 'ftpxferlog.offsetftpsep';
}

sub has_disallowed_tld {
    return $_[0] =~ m/\.(?:bkup2?|cache|json|lock|mbox|offset|stor|yaml|invalid|localhost)\z/i;
}

sub is_valid_cpanel_domain {    ##no critic qw(RequireArgUnpacking)
    my $domain = $_[0];

    my $quiet = 1;
    my ( $result, $reason ) = Cpanel::Validate::Domain::Tiny::validdomainname( $domain, $quiet );

    if ($result) {
        if ( has_disallowed_tld($domain) ) {
            undef $result;
            $reason = $domain . ' domain name has a disallowed TLD label';
        }

        if ( is_disallowed_domain($domain) ) {
            undef $result;
            $reason = $domain . ' is a disallowed domain';
        }

        my $hostname = Cpanel::Sys::Hostname::gethostname();

        if ( is_cpanel_only_domain($domain) && ( $hostname !~ m/\.cpanel\.net$/ ) ) {
            undef $result;
            $reason = $domain . ' is a cPanel domain';
        }

        if ( rindex( $domain, 'www.', 0 ) == 0 ) {
            undef $result;
            $reason = $domain . ' starts with “www.”, which is not allowed';
        }
    }

    if ( scalar @_ >= 2 ) {
        $_[1] = $reason;
    }

    return $result;
}

sub validwildcarddomain {
    my ($domainname) = @_;

    return Cpanel::Validate::Domain::Tiny::validdomainname($domainname) if index( $domainname, '*' ) == -1;

    if ( is_valid_wildcard_domain($domainname) ) {
        $domainname =~ tr{*}{a};    #replace * with a for Cpanel::Validate::Domain::Tiny::validdomainname to understand this
        return Cpanel::Validate::Domain::Tiny::validdomainname($domainname);
    }
    else {
        return wantarray ? ( 0, "domain name is not a valid wildcard format" ) : 0;
    }
}

sub is_valid_wildcard_domain {
    my ($domain) = @_;

    if ( $domain =~ /.\*/ ) {
        return 0;
    }
    elsif ( $domain =~ /\*[^\.]/ ) {
        return 0;
    }

    return 1;
}


sub _valid_or_die {
    my ( $domain, $tester_cr ) = @_;

    my ( $ok, $why ) = $tester_cr->( $domain, 1 );    #1 to make it not log->warn

    if ( !$ok ) {

        die Cpanel::Exception::create( 'DomainNameNotRfcCompliant', [ given => $domain, why => $why ] );
    }

    return 1;
}

1;

} # --- END Cpanel/Validate/Domain.pm


{ # --- BEGIN Cpanel/Validate/VirtualUsername.pm


package Cpanel::Validate::VirtualUsername;

use strict;
use warnings;

# use Cpanel::Exception                ();
# use Cpanel::Validate::EmailLocalPart ();
# use Cpanel::Validate::Domain         ();

sub is_valid {
    my ($full_username) = @_;    # including @domain, if applicable
    return eval { validate_or_die($full_username); 1 };
}

sub validate_or_die {
    my ($full_username) = @_;    # including @domain, if applicable

    if ( !length($full_username) ) {
        my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
        die Cpanel::Exception::create( 'InvalidParameter', 'The username validation routine received an empty username.' );
    }

    if ( length($full_username) > 254 ) {
        my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
        die Cpanel::Exception::create( 'InvalidParameter', 'The full username cannot exceed [numf,_1] characters.', [254] );    # In order to accommodate the SMTP limitation warned about in https://www.rfc-editor.org/errata_search.php?eid=1690
    }

    if ( $full_username =~ tr/@// ) {
        my ( $local_part, $domain ) = split /\@/, $full_username, 2;

        if ( length($local_part) > 64 ) {
            my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
            die Cpanel::Exception::create( 'InvalidParameter', 'The local part cannot exceed [numf,_1] characters.', [64] );    # RFCs 5321, 3696, etc.
        }
        if ( !Cpanel::Validate::EmailLocalPart::is_valid($local_part) ) {
            my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
            die Cpanel::Exception::create( 'InvalidParameter', 'The local part “[_1]” for user “[_2]” is invalid.', [ $local_part, $full_username ] );
        }
        if ( !Cpanel::Validate::Domain::is_valid_cpanel_domain($domain) ) {
            my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
            die Cpanel::Exception::create( 'InvalidParameter', 'The domain “[_1]” for user “[_2]” is invalid.', [ $domain, $full_username ] );
        }
    }
    else {
        my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
        die Cpanel::Exception::create( 'InvalidParameter', 'All virtual users must include both a local part and a domain.' );
    }
    return 1;
}

sub is_valid_for_creation {
    my ($full_username) = @_;    # including @domain, if applicable
    return eval { validate_for_creation_or_die($full_username); 1 };
}

sub validate_for_creation_or_die {
    my ($full_username) = @_;

    if ( !defined $full_username || !length $full_username ) {
        my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
        die Cpanel::Exception::create( 'InvalidParameter', 'You must specify a username.' );
    }

    my ($local_part) = split /\@/, $full_username, 2;
    if ( $local_part !~ m{\A[a-zA-Z0-9.\-_]*\z} ) {    # allow empty since the VirtualUsername validation will catch that
        my $suppress = Cpanel::Exception::get_stack_trace_suppressor();
        die Cpanel::Exception::create( 'InvalidParameter', 'The local part can only contain letters [asis,(a-z)], numbers [asis,(0-9)], periods, hyphens [asis,(-)], and underscores [asis,(_)].' );    # Our own rule -- stricter than any RFC
    }

    return validate_or_die($full_username);
}

1;

} # --- END Cpanel/Validate/VirtualUsername.pm


{ # --- BEGIN Cpanel/Time/HTTP.pm
package Cpanel::Time::HTTP;



my @weekday = qw/Sun Mon Tue Wed Thu Fri Sat/;
my @longday = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
my @month   = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;

sub time2http {
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday ) = gmtime( $_[0] || time() );
    return sprintf( '%s, %02d %s %04d %02d:%02d:%02d GMT', $weekday[$wday], $mday, $month[$mon], $year + 1900, $hour, $min, $sec );
}

sub time2cookie {
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday ) = gmtime( $_[0] || time() );
    return sprintf( '%s, %02d-%s-%d %02d:%02d:%02d GMT', $weekday[$wday], $mday, $month[$mon], $year + 1900, $hour, $min, $sec );
}

1;

} # --- END Cpanel/Time/HTTP.pm


{ # --- BEGIN Cpanel/Email/Object.pm
package Cpanel::Email::Object;



use strict;

use MIME::Base64      ();
use MIME::QuotedPrint ();

# use Cpanel::Autodie       ();
# use Cpanel::Hostname      ();
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::LoadModule    ();
# use Cpanel::UTF8::Strict  ();

my $CHUNK_SIZE = 2**14;

my $CHUNK_SIZE_FOR_BASE64 = 60 * 57;

my $DEFAULT_CONTENT_TYPE = 'text/plain; charset="utf-8"';

sub new {    ## no critic(RequireArgUnpacking)
    my $class = shift;

    my $opts_ref;
    if ( ref $_[0] ) {
        $opts_ref = $_[0];
    }
    else {
        $opts_ref = {@_};
    }

    _validate_opts($opts_ref);
    _fill_in_message_id($opts_ref);

    for (qw( subject from )) {
        $opts_ref->{$_} //= q<>;
    }

    $opts_ref->{'charset'} //= 'utf-8';

    return bless { _opts => $opts_ref }, $class;
}

sub _print_mime_header_if_needed {
    my ( $self, $wfh ) = @_;

    if ( !$self->{'_mime_header_is_printed'} ) {
        Cpanel::Autodie::print( $wfh, "Mime-Version: 1.0\n" );
        $self->{'_mime_header_is_printed'} = 1;
    }

    return;
}

sub print {
    my ( $self, $wfh ) = @_;

    local $self->{'_mime_header_is_printed'} = 0;

    my %headers_to_encode = (
        To => join( ',', @{ $self->{'_opts'}{'to'} } ),
    );

    foreach my $param (qw{from Reply-To subject}) {
        next if !length $self->{'_opts'}{$param};
        $headers_to_encode{ ucfirst($param) } = $self->{'_opts'}{$param};
    }

    if ( $self->{'_opts'}{'x_headers'} ) {
        my $xh_hr = $self->{'_opts'}{'x_headers'};
        @headers_to_encode{ map { "X-$_" } keys %$xh_hr } = values %$xh_hr;
    }

    if ( $self->{'_opts'}{'headers'} ) {
        my $hhr = $self->{'_opts'}{'headers'};
        @headers_to_encode{ keys %$hhr } = values %$hhr;
    }

    if ( !exists $headers_to_encode{'Date'} ) {
        require Cpanel::Time::HTTP;
        $headers_to_encode{'Date'} = Cpanel::Time::HTTP::time2http();
    }

    my %encoded_headers;
    {
        local $@;

        eval {
            require    # Cpanel::Static OK - inside eval block
              Email::MIME::Encode;
            require Encode;

            my @keys_to_encode = keys %headers_to_encode;
            foreach my $key (@keys_to_encode) {
                my $value = $headers_to_encode{$key};

                if ( defined $value && $key =~ qr{^(?: From | To | Bcc | Cc)$}xi ) {
                    if ( $value =~ qr{^[-_@+.a-zA-Z0-9<>, ]{5,79}$} ) {    # skip most of the encode when possible to preserve angle brackets
                        $encoded_headers{$key} = $value;
                        next;
                    }

                    require                                                # Cpanel::Static OK - inside eval block
                      Email::MIME::Header::AddressList;
                    my $decoded      = Encode::decode( $self->{'_opts'}{'charset'}, $value );
                    my $address_list = Email::MIME::Header::AddressList->from_string($decoded);
                    $encoded_headers{$key} = $address_list->as_mime_string();

                    next;
                }

                my $decoded = Encode::decode( $self->{'_opts'}{'charset'}, $value );
                $encoded_headers{$key} = Email::MIME::Encode::maybe_mime_encode_header( $key, $decoded, $self->{'_opts'}{'charset'} );
            }

        };

        if ($@) {
            %encoded_headers = map { $_ => Cpanel::UTF8::Strict::decode( $headers_to_encode{$_} ) } keys %headers_to_encode;
        }
    }

    my @headers = map { "$_: $encoded_headers{$_}" } sort keys %encoded_headers;

    Cpanel::Autodie::print( $wfh, map { "$_\n" } @headers );

    my $has_attachments = $self->{'_opts'}{'attachments'};
    $has_attachments &&= @$has_attachments;

    if ($has_attachments) {
        my $boundary = $self->_make_boundary('mixed');
        $self->_print_mime_header_if_needed($wfh);
        Cpanel::Autodie::print( $wfh, qq<Content-Type: multipart/mixed; boundary="$boundary"\n\n> );

        Cpanel::Autodie::print( $wfh, "--$boundary\n" );
        $self->_print_full_body($wfh);

        for my $attch_hr ( @{ $self->{'_opts'}{'attachments'} } ) {
            $self->_print_attachment( $wfh, $boundary, $attch_hr );
        }

        Cpanel::Autodie::print( $wfh, "--$boundary--\n" );
    }
    else {
        $self->_print_full_body($wfh);
    }

    return;
}

sub _fill_in_message_id {
    my ($opts) = @_;
    return if exists $opts->{'headers'} && exists $opts->{'headers'}{'Message-Id'};
    my $left_part = $opts->{'message_id'} // do {
        require Cpanel::Rand::Get;
        time . "." . Cpanel::Rand::Get::getranddata(16);
    };
    my $hostname = Cpanel::Hostname::gethostname();
    $opts->{'headers'}{'Message-Id'} = "<$left_part\@$hostname>";
    return;
}

sub _print_attachment {
    my ( $self, $wfh, $boundary, $attch_hr ) = @_;

    Cpanel::Autodie::print( $wfh, "\n--$boundary\n" );

    my $content_type = $attch_hr->{'content_type'} || $DEFAULT_CONTENT_TYPE;
    my $type_header  = "Content-Type: $content_type; x-unix-mode=0600";

    my $disp_header = 'Content-Disposition: attachment';
    if ( length $attch_hr->{'name'} ) {

        my $mime_filename = qq["$attch_hr->{'name'}"];
        $disp_header .= "; filename=$mime_filename";
        $type_header .= "; name=$mime_filename";
    }

    Cpanel::Autodie::print( $wfh, "$type_header\n$disp_header\n" );

    if ( length $attch_hr->{'content_id'} ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Encoder::URI');    #load_perl_module to keep upcp.static working on c6
        my $cid_uri = Cpanel::Encoder::URI::uri_encode_str( $attch_hr->{'content_id'} );
        Cpanel::Autodie::print( $wfh, "Content-ID: <$cid_uri>\n" );
    }

    Cpanel::Autodie::print( $wfh, "Content-Transfer-Encoding: base64\n\n" );

    if ( 'SCALAR' eq ref $attch_hr->{'content'} ) {
        my $content_sr = $attch_hr->{'content'};
        my $pos        = 0;
        while ( $pos < length $$content_sr ) {
            Cpanel::Autodie::print( $wfh, MIME::Base64::encode_base64( substr( $$content_sr, $pos, $CHUNK_SIZE_FOR_BASE64 ) ) );
            $pos += $CHUNK_SIZE_FOR_BASE64;
        }
    }
    elsif ( Cpanel::FHUtils::Tiny::is_a( $attch_hr->{'content'} ) ) {
        my $buffer;
        while ( Cpanel::Autodie::read( $attch_hr->{'content'}, $buffer, $CHUNK_SIZE_FOR_BASE64 ) ) {    #must be this size for encode_base64
            Cpanel::Autodie::print( $wfh, MIME::Base64::encode_base64($buffer) );
        }
    }

    return;
}

sub _print_body_part {
    my ( $self, $wfh, $body_key, $content_type ) = @_;

    my $body_sr = $self->{'_opts'}{$body_key};
    my $charset = $self->{'_opts'}{'charset'};

    Cpanel::Autodie::print( $wfh, "Content-Type: $content_type; charset=$charset\n" );
    Cpanel::Autodie::print( $wfh, "Content-Transfer-Encoding: quoted-printable\n\n" );
    $self->_send_msg_into_fh( $body_sr, $wfh );

    return;
}

sub _print_full_body {
    my ( $self, $wfh ) = @_;

    my $text_sr = $self->{'_opts'}{'text_body'};
    my $html_sr = $self->{'_opts'}{'html_body'};

    my $has_text = $text_sr && length $$text_sr;
    my $has_html = $html_sr && length $$html_sr;

    $self->_print_mime_header_if_needed($wfh);
    if ($has_text) {
        if ($has_html) {
            my $boundary = $self->_make_boundary('alternative');

            Cpanel::Autodie::print( $wfh, qq<Content-Type: multipart/alternative; boundary="$boundary"\n\n> );

            Cpanel::Autodie::print( $wfh, "--$boundary\n" );
            $self->_print_body_part( $wfh, 'text_body', 'text/plain' );

            Cpanel::Autodie::print( $wfh, "\n--$boundary\n" );

            $self->_print_html_section($wfh);

            Cpanel::Autodie::print( $wfh, "\n--$boundary--\n" );
        }
        else {
            $self->_print_body_part( $wfh, 'text_body', 'text/plain' );
        }
    }
    elsif ($has_html) {
        $self->_print_html_section($wfh);
    }
    else {
        die "No body to print!";    #should never get here, but just in case
    }

    return;
}

sub _print_html_section {
    my ( $self, $wfh ) = @_;

    my $html_sr = $self->{'_opts'}{'html_body'};

    my $html_rel = $self->{'_opts'}{'html_related'};
    $html_rel &&= @$html_rel;

    if ($html_rel) {
        my $boundary = $self->_make_boundary('related');

        $self->_print_mime_header_if_needed($wfh);
        Cpanel::Autodie::print( $wfh, qq<Content-Type: multipart/related; boundary="$boundary"\n\n> );

        Cpanel::Autodie::print( $wfh, "--$boundary\n" );
        $self->_print_body_part( $wfh, 'html_body', 'text/html' );

        for my $rel_part ( @{ $self->{'_opts'}{'html_related'} } ) {
            $self->_print_attachment( $wfh, $boundary, $rel_part );
        }

        Cpanel::Autodie::print( $wfh, "\n--$boundary--\n" );
    }
    else {
        $self->_print_body_part( $wfh, 'html_body', 'text/html' );
    }

    return;
}

sub _make_boundary {
    my ( $self, $base_str ) = @_;

    return join( '-', $base_str, __PACKAGE__, $$, time(), rand() );
}

sub _construct_content_type {
    my ($self) = @_;

    my $type = $self->{'_opts'}{'content_type'};
    if ( $self->{'_opts'}{'charset'} ) {
        $type .= "; charset=$self->{'_opts'}{'charset'}";
    }

    return $type;
}

sub _send_msg_into_fh {
    my ( $self, $msg_ref, $wfh ) = @_;

    if ( Cpanel::FHUtils::Tiny::is_a($msg_ref) ) {
        my $buffer;
        while ( Cpanel::Autodie::read( $msg_ref, $buffer, $CHUNK_SIZE ) ) {
            Cpanel::Autodie::print( $wfh, MIME::QuotedPrint::encode_qp($buffer) );
        }
    }
    else {
        Cpanel::Autodie::print( $wfh, MIME::QuotedPrint::encode_qp($$msg_ref) );
    }

    return;
}


sub _validate_opts {
    my ($opts_hr) = @_;

    if ( ref( $opts_hr->{'to'} ) ne 'ARRAY' ) {
        die "“to” must be an arrayref, not “$opts_hr->{'to'}”!";
    }

    for (qw( text_body  html_body )) {
        next if !defined $opts_hr->{$_};
        next if ref( $opts_hr->{$_} ) eq 'SCALAR';
        next if Cpanel::FHUtils::Tiny::is_a( $opts_hr->{$_} );

        die "“$_” must be a file handle or a SCALAR reference, not “$opts_hr->{$_}”!";
    }

    if ( !grep { defined $opts_hr->{$_} } qw( text_body  html_body ) ) {
        die "Give either text or HTML!";
    }

    if ( defined $opts_hr->{'attachments'} ) {
        if ( ref( $opts_hr->{'attachments'} ) ne 'ARRAY' ) {
            die "“attachments” must be an arrayref, not “$opts_hr->{'attachments'}”!";
        }

        if ( grep { ref ne 'HASH' } @{ $opts_hr->{'attachments'} } ) {
            die 'each element of “attachments” must be a hashref!';
        }
    }

    if ( defined $opts_hr->{'x_headers'} && 'HASH' ne ref $opts_hr->{'x_headers'} ) {
        die '“x_headers” must be a hashref!';
    }

    return 1;
}

1;

} # --- END Cpanel/Email/Object.pm


{ # --- BEGIN Cpanel/iContact/Email.pm
package Cpanel::iContact::Email;


use strict;

use Try::Tiny;

# use Cpanel::Debug           ();
# use Cpanel::Autodie         ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::Email::Object   ();

our $DEFAULT_CONTENT_TYPE = 'text/plain';

sub write_email_to_fh {
    my ( $sendmail_fh, %OPTS ) = @_;

    convert_attach_files_to_attachments( \%OPTS );

    return Cpanel::Email::Object->new( \%OPTS )->print($sendmail_fh);
}

sub convert_attach_files_to_attachments {
    my ($email_args_hr) = @_;
    for my $file ( @{ $email_args_hr->{'attach_files'} } ) {
        if ( ref $file ) {
            push @{ $email_args_hr->{'attachments'} }, $file;
        }
        else {
            next unless defined $file && length($file);
            my @FP       = split( /\//, $file );
            my $filename = pop @FP;
            if ( $filename =~ /\.log$/ ) {
                $filename .= '.txt';    #blackberry compat
            }

            $email_args_hr->{'attachments'} ||= [];

            my $mimetype = _guess_binary_mime_type_from_filename($file);

            my $rfh;
            try {
                Cpanel::Autodie::open( $rfh, '<', $file );
            }
            catch {
                undef $rfh;
                Cpanel::Debug::log_warn("Failed to open “$file”: $_");
            };

            next if !$rfh;

            push @{ $email_args_hr->{'attachments'} },
              {
                name         => $filename,
                content      => $rfh,
                content_type => $mimetype,
              };
        }
    }

    return 1;
}

sub _guess_binary_mime_type_from_filename {
    my ($file) = @_;


    return 'application/x-tar'        if $file =~ m/\.tar\.?(?:gz|bz2|Z)?$/i;
    return 'application/octet-stream' if -B $file;



    my $mime;
    eval { $mime = Cpanel::SafeRun::Object->new_or_die( 'program' => '/usr/bin/file', 'args' => [ qw{ --brief --mime }, $file ] )->stdout; 1 }
      or Cpanel::Debug::log_warn("Failed to check mime type for file “$file”: $_");
    chomp($mime)                  if $mime;
    $mime = $DEFAULT_CONTENT_TYPE if !$mime;

    return $mime;
}

1;

} # --- END Cpanel/iContact/Email.pm


{ # --- BEGIN Whostmgr/UI.pm
package Whostmgr::UI;


use strict;
use warnings;

# use Cpanel::JSON       ();
# use Cpanel::LoadModule ();

our $method             = 'print';
our $nohtml             = 0;
our $status_block_depth = 0;

sub setstatus {
    local $| = 1;
    my $statusdata = shift;
    $statusdata =~ s/\n//g;

    $status_block_depth++;

    my $js_status = Cpanel::JSON::SafeDump($statusdata);
    if (   !$nohtml
        && !( -t STDOUT || !defined $ENV{'GATEWAY_INTERFACE'} || $ENV{'GATEWAY_INTERFACE'} !~ m/CGI/i ) ) {
        if ( $method ne 'hide' ) {
            print "<script>if (window.update_ui_status) update_ui_status($js_status);</script>" . ( qq{ } x 4096 ) . "\n";
        }
        my $indent = ( $status_block_depth > 1 ) ? " margin-left: 1rem;" : "";
        my $txt    = qq{<div style="border-bottom: 1px #ccc dotted; font: 12px 'Andale Mono', 'Courier New', Courier, monospace; padding: .5em 0;$indent">};
        $txt .= qq{<span style="white-space: pre-wrap;">$statusdata...</span><pre style="margin: 0;">};
        $method eq 'print' ? print $txt : return $txt;
    }
    else {
        $method eq 'print' ? print qq{$statusdata...} : return qq{$statusdata...};
    }
    return '';
}

sub setstatusdone {
    Cpanel::LoadModule::load_perl_module('Cpanel::MagicRevision') if !$INC{'Cpanel/MagicRevision.pm'};
    return _end_status_block( "Done", Cpanel::MagicRevision::calculate_magic_url( '/cjt/images/icons/success.png', $ENV{'REQUEST_URI'}, '/usr/local/cpanel/whostmgr/docroot' ) );
}

sub setstatuserror {
    Cpanel::LoadModule::load_perl_module('Cpanel::MagicRevision') if !$INC{'Cpanel/MagicRevision.pm'};
    return _end_status_block( "Failed", Cpanel::MagicRevision::calculate_magic_url( '/cjt/images/icons/error.png', $ENV{'REQUEST_URI'}, '/usr/local/cpanel/whostmgr/docroot' ) );
}

sub _end_status_block {
    my ( $msg, $img ) = @_;
    local $| = 1;
    $status_block_depth--;
    if ( !$nohtml && !( -t STDOUT || !defined $ENV{'GATEWAY_INTERFACE'} || $ENV{'GATEWAY_INTERFACE'} !~ /CGI/i ) ) {
        my $txt = qq{</pre><span style="white-space: pre;">...$msg</span><img style="float: right;" src="} . $img . qq{"></div>\n};
        $method eq 'print' ? print $txt : return $txt;
    }
    else {
        $method eq 'print' ? print qq{...$msg\n} : return qq{...$msg\n};
    }
    return '';
}

sub clearstatus {
    local $| = 1;
    if (   !$nohtml
        && !( -t STDOUT || !defined $ENV{'GATEWAY_INTERFACE'} || $ENV{'GATEWAY_INTERFACE'} !~ /CGI/i ) ) {
        if ( $method ne 'hide' ) { print "<script>if (window.clear_ui_status) clear_ui_status();</script>\n"; }
    }
    return '';
}

1;

} # --- END Whostmgr/UI.pm


{ # --- BEGIN Whostmgr/Transfers/State.pm
package Whostmgr::Transfers::State;


use strict;

my $is_transfer = 0;

sub start_transfer {
    $is_transfer = 1;
    return 1;
}

sub is_transfer {
    return ( $is_transfer eq 1 ) ? 1 : 0;
}

sub end_transfer {
    $is_transfer = 0;
    return 1;
}

1;

} # --- END Whostmgr/Transfers/State.pm


{ # --- BEGIN Cpanel/Validate/Username/Mode.pm
package Cpanel::Validate::Username::Mode;


use strict;
use warnings;

# use Whostmgr::Transfers::State ();

my $_allows_leading_digits;

sub allows_leading_digits {
    return ( $_allows_leading_digits //= ( -e '/etc/allowstupidstuff' ? 1 : 0 ) );
}

*in_transfer_mode = *Whostmgr::Transfers::State::is_transfer;

sub additional_reserved_usernames {
    return ();
}

sub _clear_cache {
    return undef $_allows_leading_digits;
}

1;

} # --- END Cpanel/Validate/Username/Mode.pm


{ # --- BEGIN Cpanel/Validate/Username/Core.pm
package Cpanel::Validate::Username::Core;


use strict;
use warnings;

# use Cpanel::Validate::Username::Mode ();
# use Cpanel::ArrayFunc::Uniq          ();
# use Cpanel::LoadFile                 ();

our $MAX_LENGTH                 = 16;                    #Constrained by MySQL
our $MAX_SYSTEM_USERNAME_LENGTH = 31;
our $ETC_ALIASES_PATH           = '/etc/aliases';
our $ETC_LOCALALIASES_PATH      = '/etc/localaliases';

my @_list_reserved_usernames;

sub list_reserved_usernames {
    return @_list_reserved_usernames if @_list_reserved_usernames;
    my @names = qw(
      abrt
      all
      clamav
      cpanel-ccs
      cpeasyapache
      cpses
      cptkt
      cphulkd
      cpwebcalls
      dbus
      dirs
      dnsadmin
      dovecot
      eximstats
      files
      ftpxferlog
      haldaemon
      horde
      information_schema
      mailman
      modsec
      munin
      mydns
      nobody
      performance_schema
      postgres
      postmaster
      proftpd
      root
      roundcube
      shadow
      spamassassin
      ssl
      sys
      system
      tcpdump
      tmp
      tomcat
      toor
      virtfs
      virtual
      webmaster
      whmxfer
      _lock
    );
    push @names, aliases();
    push @names, Cpanel::Validate::Username::Mode::additional_reserved_usernames();
    return ( @_list_reserved_usernames = Cpanel::ArrayFunc::Uniq::uniq(@names) );
}

sub reserved_username_prefixes {
    return qw(test
      passwd.
      cpmydns
      cpanel
      mydns
      pg_toast
      pg_temp
      cpses
      cptkt
      cpbackup);
}

sub reserved_username_suffixes {
    return qw(
      .lock
      .cache
      .yaml
      .json
      .db
      assword
    );
}

sub list_reserved_username_patterns {
    return (
        list_reserved_username_regexes(),
        ( map { '^' . quotemeta($_) } reserved_username_prefixes() ),
        ( map { quotemeta($_) . '$' } reserved_username_suffixes() )
    );
}

sub list_reserved_username_regexes {
    return qw(
      ^[-._0-9]+$
    );
}

sub get_system_username_regexp_str {
    return '^' . _regexp_lead() . "[-._A-Za-z0-9]{1,$MAX_SYSTEM_USERNAME_LENGTH}\$";
}

sub get_regexp_str {
    return '^' . _regexp_lead() . "[-._a-z0-9]{1,$MAX_LENGTH}\$";
}

sub _regexp_lead {
    return Cpanel::Validate::Username::Mode::allows_leading_digits() ? '(?![-.])' : '(?![-.0-9])';
}

sub is_valid_system_username {
    my ($user) = @_;
    return if !defined $user;

    my $regexp = get_system_username_regexp_str();

    $regexp = _apply_perl_boundary($regexp);

    return $user =~ m{$regexp}o;
}

sub is_valid {
    my ($user) = @_;
    return if !defined $user;

    my $regexp = get_regexp_str();

    $regexp = _apply_perl_boundary($regexp);

    return $user =~ m{$regexp}o;
}

sub normalize {
    my ($name) = @_;
    return unless defined $name;
    $name =~ s/^\s+//;
    $name =~ s/\s+$//;
    $name =~ tr/A-Z/a-z/;
    return $name;
}

sub scrub {
    my ($name) = @_;
    return unless defined $name;

    $name = normalize($name);
    if ( Cpanel::Validate::Username::Mode::in_transfer_mode() ) {
        $name =~ tr/-a-z0-9._//cd;
    }
    else {
        $name =~ tr/a-z0-9._//cd;
    }

    substr( $name, 0, 1, '' ) while index( $name, '.' ) == 0;
    $name =~ s/^\d+// unless Cpanel::Validate::Username::Mode::allows_leading_digits();

    if ( length $name > $MAX_LENGTH ) {
        substr( $name, $MAX_LENGTH ) = q{};
    }

    return $name;
}

sub reserved_username_check {
    my ($user) = @_;

    return   if !$user;
    return 1 if grep { $_ eq $user } list_reserved_usernames();
    return 1 if grep { rindex( $user, $_, 0 ) == 0 } reserved_username_prefixes();
    return 1 if grep { index( $user, $_, length($user) - length($_) ) != -1 } reserved_username_suffixes();
    return 1 if grep { $user =~ m{$_} } list_reserved_username_regexes();
    return;
}

sub aliases {
    my @reserved_names;

    foreach my $file ( $ETC_ALIASES_PATH, $ETC_LOCALALIASES_PATH ) {
        next if ( !-f $file || !-r _ );

        my ( $name, $line );
        for $line ( split m<\n+>, Cpanel::LoadFile::load($file) ) {
            $name = ( split /:/, $line )[0];
            next if !length $name || $name =~ tr< :#\t><>;

            push @reserved_names, $name;
        }
    }
    return @reserved_names;
}

sub _apply_perl_boundary {
    $_[0] =~ s{^\^}{\\A};
    $_[0] =~ s{\$$}{\\z};
    return $_[0];
}

1;

} # --- END Cpanel/Validate/Username/Core.pm


{ # --- BEGIN Cpanel/AcctUtils/Domain.pm
package Cpanel::AcctUtils::Domain;


use strict;
use warnings;

# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::Config::HasCpUserFile  ();

sub getdomain {
    my ($user) = @_;
    return unless Cpanel::Config::HasCpUserFile::has_cpuser_file($user);
    return Cpanel::Config::LoadCpUserFile::loadcpuserfile($user)->{'DOMAIN'};
}

1;

} # --- END Cpanel/AcctUtils/Domain.pm


{ # --- BEGIN Cpanel/Config/userdata/Constants.pm
package Cpanel::Config::userdata::Constants;


use strict;
use warnings;


our $USERDATA_DIR = '/var/cpanel/userdata';

1;

} # --- END Cpanel/Config/userdata/Constants.pm


{ # --- BEGIN Cpanel/AcctUtils/Account.pm
package Cpanel::AcctUtils::Account;


use strict;
use warnings;

# use Cpanel::PwCache ();

our $USERS_DIR = '/var/cpanel/users';



sub accountexists {

    return 1 if $_[0] && $_[0] eq 'root';

    return length( scalar Cpanel::PwCache::getpwnam_noshadow( $_[0] ) ) ? 1 : 0;
}


sub get_existing_account_parts {
    my ($user) = @_;

    my @existing_parts = ();

    push( @existing_parts, "$USERS_DIR/$user" ) if -e "$USERS_DIR/$user";

    push( @existing_parts, "system user “$user”" ) if accountexists($user);

    require Cpanel::Config::userdata::Constants;
    push( @existing_parts, "$Cpanel::Config::userdata::Constants::USERDATA_DIR/$user" ) if -e "$Cpanel::Config::userdata::Constants::USERDATA_DIR/$user";

    return \@existing_parts;
}


sub accountexists_or_die {
    accountexists( $_[0] ) or do {
        require Cpanel::Exception;
        die Cpanel::Exception::create( 'UserNotFound', [ name => $_[0] ] );
    };
    return 1;
}

1;

} # --- END Cpanel/AcctUtils/Account.pm


{ # --- BEGIN Cpanel/AcctUtils/Lookup/Webmail.pm
package Cpanel::AcctUtils::Lookup::Webmail;



use strict;
use warnings;


sub is_webmail_user {
    return (
        (
            defined $_[0]                                         # must have some value
              && length( $_[0] ) > 4                              # must be at least 5 characters long (1 localpart, 3 domain, 1 domain separator)
              && 1 == $_[0]             =~ tr{+%:@}{}             # must have 1 domain separator character
              && 1 == $_[0]             =~ tr{a-zA-Z0-9._-}{}c    # the domain separator is the only character present that is not allowed in a localpart or domain
              && substr( $_[0], 0, 1 )  !~ tr{+%:@.}{}            # first character could be a localpart ( no domain separator or . )
              && substr( $_[0], -3, 2 ) !~ tr{+%:@_}{}            # first two of the last three characters could be a domain
              && substr( $_[0], -1, 1 ) !~ tr{+%:@._-}{}          # last character could be a tld
        ) ? 1 : 0
    );
}


sub is_strict_webmail_user {
    return (
        (
            defined $_[0]                                      # must have some value
              && length( $_[0] ) > 4                           # must be at least 5 characters long (1 localpart, 3 domain, 1 domain separator)
              && 1 == $_[0]             =~ tr{@}{}             # must contain 1 domain separator character
              && 1 == $_[0]             =~ tr{a-z0-9._-}{}c    # the domain separator is the only character that is not allowed in a localpart or domain
              && substr( $_[0], 0, 1 )  !~ tr{@.}{}            # first character could be a localpart ( no domain separator or . )
              && substr( $_[0], -3, 2 ) !~ tr{@_}{}            # first two of the last three characters could be a domain
              && substr( $_[0], -1, 1 ) !~ tr{@._-}{}          # last character could be a tld
        ) ? 1 : 0
    );
}


sub normalize_webmail_user {
    my ($user) = @_;

    $user =~ tr/A-Z+%:/a-z@/;

    return ( wantarray() ? split( '@', $user, 2 ) : $user );
}

1;

} # --- END Cpanel/AcctUtils/Lookup/Webmail.pm


{ # --- BEGIN Cpanel/AcctUtils/Lookup.pm
package Cpanel::AcctUtils::Lookup;



use strict;
use warnings;

# use Cpanel::AcctUtils::DomainOwner::Tiny ();
# use Cpanel::AcctUtils::Account           ();
# use Cpanel::AcctUtils::Lookup::Webmail   ();
# use Cpanel::Exception                    ();


sub get_system_user {
    my $sysuser = get_system_user_without_existence_validation( $_[0] );

    if ( !Cpanel::AcctUtils::Account::accountexists($sysuser) ) {
        die Cpanel::Exception::create( 'UserNotFound', [ name => $sysuser ] );
    }

    return $sysuser;
}


sub get_system_user_without_existence_validation {    ##no critic qw(RequireArgUnpacking)

    die Cpanel::Exception::create( 'UserNotFound', [ name => '' ] ) unless defined $_[0] && length $_[0];

    if ( $_[0] =~ tr{/}{} ) {
        die Cpanel::Exception::create( 'InvalidParameter', '“[_1]” is not a valid username because it contains a “[_2]” character.', [ $_[0], '/' ] );
    }

    return $_[0] if !Cpanel::AcctUtils::Lookup::Webmail::is_strict_webmail_user( $_[0] );

    my ($domain) = ( split( m{@}, $_[0], 2 ) )[1];

    my $sysuser = Cpanel::AcctUtils::DomainOwner::Tiny::getdomainowner( $domain, { 'skiptruelookup' => 1, 'default' => '' } );
    if ( !length $sysuser ) {
        die Cpanel::Exception::create( 'DomainDoesNotExist', 'The domain “[_1]” does not exist.', [$domain] );
    }
    return $sysuser;
}
1;

} # --- END Cpanel/AcctUtils/Lookup.pm


{ # --- BEGIN Cpanel/Sereal/Decoder.pm
package Cpanel::Sereal::Decoder;


use cPstrict;



use Sereal::Decoder ();

my %REQUIRED_OPTIONS = (

    refuse_objects => 1,

    no_bless_objects => 1,

    refuse_snappy => 1,

    validate_utf8 => 1,

    max_recursion_depth => 100,
);



sub create {
    return Sereal::Decoder->new( \%REQUIRED_OPTIONS );
}

1;

} # --- END Cpanel/Sereal/Decoder.pm


{ # --- BEGIN Cpanel/Sereal/Encoder.pm
package Cpanel::Sereal::Encoder;


use cPstrict;



use Sereal::Encoder ();

my %REQUIRED_OPTIONS = (

    croak_on_bless => 1,
);



sub create {
    return Sereal::Encoder->new( \%REQUIRED_OPTIONS );
}

1;

} # --- END Cpanel/Sereal/Encoder.pm


{ # --- BEGIN Cpanel/JSON/Sanitize.pm
package Cpanel::JSON::Sanitize;


use cPstrict;



sub sanitize_for_dumping {
    my $item    = shift;
    my $reftype = ref $item;

    if ( !defined $item || $reftype eq "" ) {
        return $item;
    }
    elsif ( ( $reftype eq 'SCALAR' || $reftype eq 'JSON::XS::Boolean' || $reftype eq 'JSON::PP::Boolean' || $reftype eq 'Types::Serialiser::Boolean' ) && ( $$item eq '1' || $$item eq '0' ) ) {
        return $item;
    }
    elsif ( $reftype eq "ARRAY" ) {
        return [ map { sanitize_for_dumping($_) } grep { _suitable_for_dumping($_) } @$item ];
    }
    elsif ( $reftype eq "HASH" ) {
        return {
            map    { $_ => sanitize_for_dumping( $item->{$_} ) }
              grep { _suitable_for_dumping( $item->{$_} ) }
              keys %$item
        };
    }
    else {
        die "That data structure isn't suitable for dumping.";
    }
}


sub filter_to_json ($item) {
    my $ref = ref $item;

    return $item if !$ref;

    if ( 'ARRAY' eq $ref ) {
        return [ map { filter_to_json($_) } @$item ];
    }
    elsif ( 'HASH' eq $ref ) {
        my %dupe = map { ( $_ => filter_to_json( $item->{$_} ) ) } keys %$item;

        return \%dupe;
    }
    elsif ( UNIVERSAL::can( $item, 'TO_JSON' ) ) {
        return filter_to_json( $item->TO_JSON() );
    }

    require Carp;
    Carp::croak("$item is not JSON-compatible!");
}


sub uxxxx_to_bytes {
    my $str_r = \$_[0];

    $$str_r =~ s/
        (\\+)u( [a-fA-F0-9]{4} )
    /
        if ( length($1) % 2 ) {
            my $c = pack('U', hex $2);
            utf8::encode($c);
            substr($1, 1) . $c;
        }
        else {
            "$1u$2";
        }
    /exg;

    return $$str_r;
}

sub _suitable_for_dumping {
    my $item    = shift;
    my $reftype = ref $item;

    return 1 if !defined $item;
    return 1 if $reftype eq "" || $reftype eq 'ARRAY' || $reftype eq 'HASH';
    return 1 if ( $reftype eq 'SCALAR' || $reftype eq 'JSON::XS::Boolean' || $reftype eq 'JSON::PP::Boolean' || $reftype eq 'Types::Serialiser::Boolean' ) && ( $$item eq '1' || $$item eq '0' );
    return 0;
}

1;

} # --- END Cpanel/JSON/Sanitize.pm


{ # --- BEGIN Cpanel/UntrustedException.pm


package Cpanel::UntrustedException;

use strict;
use warnings;

use overload ( '""' => \&stringify, fallback => 1 );


sub new {
    my ( $package, %params ) = @_;

    my $self = {
        string   => $params{string},
        class    => $params{class},
        longmess => $params{longmess},
        metadata => $params{metadata},
    };

    return bless $self, $package;
}


sub class {
    my ($self) = @_;
    return $self->{class};
}


sub string {
    my ($self) = @_;
    return $self->{string};
}


sub longmess {
    my ($self) = @_;
    return $self->{longmess};
}


sub get {
    my ( $self, $attr ) = @_;
    return $self->{metadata}{$attr};
}

sub stringify {
    my ($self) = @_;

    if ( $self->{class} ) {
        return $self->{class} . '/' . join "\n", $self->{string} || '<no message>', $self->{longmess} || '';
    }

    return $self->{string};
}

1;

} # --- END Cpanel/UntrustedException.pm


{ # --- BEGIN Cpanel/ForkSync.pm
package Cpanel::ForkSync;


use strict;
use warnings;




# use Cpanel::ChildErrorStringifier();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::ChildErrorStringifier); }

use Try::Tiny;
# use Cpanel::ForkAsync          ();
# use Cpanel::Exception          ();
# use Cpanel::Sereal::Decoder    ();
# use Cpanel::FHUtils::Autoflush ();
# use Cpanel::LoadFile::ReadFast ();


our $quiet;


sub new {
    my ( $class, $code, @args ) = @_;

    return $class->new_with_parent_callback( undef, $code, @args );
}


sub new_with_parent_callback {
    my ( $class, $parent_code, $code, @args ) = @_;

    local $SIG{'CHLD'} = 'DEFAULT';

    my ( $PR, $CW, $RC );
    pipe( $PR, $CW ) or do {
        my $err = $!;
        require Cpanel::Debug;
        Cpanel::Debug::log_die("Failed to pipe(): $err");
    };

    Cpanel::FHUtils::Autoflush::enable($CW);

    my $decoder = Cpanel::Sereal::Decoder::create();

    my $run = sub {
        require Cpanel::Sereal::Encoder;
        my $encoder = Cpanel::Sereal::Encoder::create();

        close $PR or die "close() on parent reader in child failed: $!";
        my ( $err, $ret );
        try {
            $ret = { '_return' => [ $code->(@args) ] };    # if we die/exit here, json is going to be corrupted
        }
        catch {
            $err = $_;

            $ret = _build_serializable_exception_data($err);
        };

        my $encoded;

        eval { $encoded = $encoder->encode($ret); 1 } or do {
            local ( $@, $! );
            require Cpanel::JSON::Sanitize;

            $ret = Cpanel::JSON::Sanitize::filter_to_json($ret);

            $encoded = $encoder->encode($ret);
        };

        syswrite $CW, $encoded or die "Failed to write: $!";

        close $CW or die "close() on child writer in child failed: $!";
        die $err if $err;

        return;
    };

    my $pid =
      $quiet
      ? Cpanel::ForkAsync::do_in_child_quiet($run)
      : Cpanel::ForkAsync::do_in_child($run);

    close $CW or warn "Parent failed to close child-write: $!";

    if ($parent_code) {
        warn if !eval { $parent_code->(); 1 };
    }

    local $@;
    eval {
        local $SIG{__DIE__};
        local $SIG{__WARN__};

        Cpanel::LoadFile::ReadFast::read_all_fast( $PR, my $buf );

        $RC = $decoder->decode($buf);
    };
    my $retrieve_err = $@;
    close $PR or warn "Parent failed to close parent-read: $!";

    local $?;

    waitpid( $pid, 0 );

    if ( ref $RC->{'_structured_exception'} eq 'HASH' && $RC->{'_structured_exception'}{'class'} ) {

        if ( my $errno = delete $RC->{'_structured_exception'}{'metadata_errno'} ) {
            $RC->{'_structured_exception'}{'metadata'}{'error'} = do {
                local $! = $errno;
            };
        }

        require Cpanel::UntrustedException;
        $RC->{'_structured_exception'} = Cpanel::UntrustedException->new(
            class    => $RC->{'_structured_exception'}->{'class'},
            string   => $RC->{'_structured_exception'}->{'string'},
            longmess => $RC->{'_structured_exception'}->{'longmess'},
            metadata => $RC->{'_structured_exception'}->{'metadata'},
        );
    }

    my $self = {
        _CHILD_ERROR          => $?,
        _pid                  => $pid,
        _retrieve_err         => $retrieve_err,
        _return               => $RC->{'_return'},
        _exception            => $RC->{'_exception'},
        _full_exception_text  => $RC->{'_full_exception_text'},
        _structured_exception => $RC->{'_structured_exception'},
    };

    return bless $self, $class;
}

sub new_quiet {
    my ( $package, $code, @args ) = @_;

    local $quiet = 1;
    return $package->new( $code, @args );
}

sub exception {
    my ($self) = @_;

    return $self->{'_exception'};
}

sub full_exception_text {
    my ($self) = @_;

    return $self->{'_full_exception_text'};
}


sub structured_exception {
    my ($self) = @_;

    return $self->{'_structured_exception'};
}


sub retrieve_error {
    my ($self) = @_;

    return $self->{'_retrieve_err'};
}


sub return {
    my ($self) = @_;

    return $self->{'_return'};
}


sub had_error {
    my ($self) = @_;

    return ( $self->CHILD_ERROR() || $self->exception() || $self->retrieve_error() ) ? 1 : 0;
}


sub pid {
    my ($self) = @_;

    return $self->{'_pid'};
}


sub do_in_child {
    my ( $code, @args ) = @_;

    if ( !wantarray ) {
        my $given_code = $code;
        $code = sub { return scalar $given_code->(@_) };
    }

    my $run = __PACKAGE__->new( $code, @args );

    $? = $run->CHILD_ERROR();    ## no critic(RequireLocalizedPunctuationVars) -- legacy compatibility

    return undef if $run->retrieve_error() || !defined $run->return() || $run->CHILD_ERROR();

    return wantarray ? @{ $run->return() } : $run->return()->[-1];
}

sub _build_serializable_exception_data {
    my ($err) = @_;

    my ( $_exception, $_full_exception_text, $_structured_exception, $_metadata );
    if ( try { $err->isa('Cpanel::Exception') } ) {
        $_exception            = Cpanel::Exception::get_string($err);    # short message
        $_full_exception_text  = $err . '';                              # force long-form stringification
        $_structured_exception = {
            class    => ref($err),
            string   => $err->get_string,
            longmess => $err->longmess,
            metadata => {},
        };

        for my $attr ( sort keys %{ $err->{'_metadata'} } ) {
            my $value = $err->get($attr);
            if ( !ref($value) ) {    # For now we'll just transport simple scalar values back to the parent to avoid having to deal with weeding blessed objects out from underneath hashes or arrays
                $_structured_exception->{'metadata'}{$attr} = $value;
            }
        }

        if ( my $error = $_structured_exception->{'metadata'}{'error'} ) {
            local $! = $error;
            if ($!) {
                $_structured_exception->{'metadata_errno'} = 0 + $!;
            }
        }
    }
    elsif ( ref($_) eq 'HASH' || ref($_) eq 'ARRAY' ) {
        $_exception            = $err;
        $_full_exception_text  = undef;
        $_structured_exception = $err;
    }
    else {
        $_exception            = $err;
        $_full_exception_text  = $err;
        $_structured_exception = undef;
    }

    return {
        '_return'               => undef,
        '_exception'            => $_exception,
        '_full_exception_text'  => $_full_exception_text,
        '_structured_exception' => $_structured_exception,
        '_metadata'             => $_metadata,
    };
}

1;

} # --- END Cpanel/ForkSync.pm


{ # --- BEGIN Cpanel/Pack/Template.pm
package Cpanel::Pack::Template;


use strict;
use warnings;



use constant PACK_TEMPLATE_INT           => 'i';
use constant PACK_TEMPLATE_UNSIGNED_INT  => 'i!';
use constant PACK_TEMPLATE_UNSIGNED_LONG => 'L!';
use constant PACK_TEMPLATE_U32           => 'L';
use constant U32_BYTES_LENGTH            => 4;
use constant PACK_TEMPLATE_U16           => 'S';
use constant U16_BYTES_LENGTH            => 2;
use constant PACK_TEMPLATE_U8            => 'C';
use constant U8_BYTES_LENGTH             => 1;
use constant PACK_TEMPLATE_BE16          => 'n';
use constant PACK_TEMPLATE_BE32          => 'N';

1;

} # --- END Cpanel/Pack/Template.pm


{ # --- BEGIN Cpanel/Sys/Id.pm
package Cpanel::Sys::Id;



use strict;
use warnings;
# use Cpanel::Pack::Template ();    # PPI USE OK - in use constant
# use Cpanel::Syscall        ();

use constant PACK_TEMPLATE_UNSIGNED_INT => Cpanel::Pack::Template::PACK_TEMPLATE_UNSIGNED_INT();


sub setresgid {
    return Cpanel::Syscall::syscall( 'setresgid', int $_[0], int $_[1], int $_[2] );
}


sub setresuid {
    return Cpanel::Syscall::syscall( 'setresuid', int $_[0], int $_[1], int $_[2] );
}


sub setgroups {
    return Cpanel::Syscall::syscall( 'setgroups', scalar @_, pack( PACK_TEMPLATE_UNSIGNED_INT x scalar @_, @_ ) );
}

1;

} # --- END Cpanel/Sys/Id.pm


{ # --- BEGIN Cpanel/AccessIds/SetUids.pm
package Cpanel::AccessIds::SetUids;


use strict;
use warnings;


# use Cpanel::Debug                ();
# use Cpanel::AccessIds::Utils     ();
# use Cpanel::AccessIds::Normalize ();
# use Cpanel::Sys::Id              ();

our $VERSION = '1.3';


sub setuids {    ## no critic qw(RequireArgUnpacking)
    my ( $uid, $gid, @additional_gids ) = Cpanel::AccessIds::Normalize::normalize_user_and_groups(@_);
    if ( 'Cpanel::PwCache::Cache'->can('pwmksafecache') ) {    # PPI NO PARSE - will not fail if not loaded
        Cpanel::PwCache::Cache::pwmksafecache();               # PPI NO PARSE - nothing to do if the can is false
    }

    if ( !defined $uid || !defined $gid ) {
        Cpanel::Debug::log_die("setuids failed: Could not resolve UID or GID (@_)");
    }

    local $@;
    eval { Cpanel::Sys::Id::setgroups( $gid, @additional_gids ); };
    if ($@) {
        _log_and_die_if_not_root() or die;
    }

    eval { Cpanel::Sys::Id::setresgid( $gid, $gid, $gid ); };
    if ($@) {
        _log_and_die_if_not_root() or die;
    }

    Cpanel::AccessIds::Utils::validate_var_set( 'EGID', join( ' ', $gid, @additional_gids ? ( @additional_gids, $gid ) : ($gid) ), $) );
    Cpanel::AccessIds::Utils::validate_var_set( 'RGID', join( ' ', $gid, @additional_gids ? ( @additional_gids, $gid ) : ($gid) ), $( );

    eval { Cpanel::Sys::Id::setresuid( $uid, $uid, $uid ); };
    if ($@) {
        _log_and_die_if_not_root() or die;
    }

    Cpanel::AccessIds::Utils::validate_var_set( 'EUID', $uid, $< );
    Cpanel::AccessIds::Utils::validate_var_set( 'RUID', $uid, $> );

    return $uid;
}

sub _log_and_die_if_not_root {
    if ( $< != 0 ) {
        Cpanel::Debug::log_die("setuids failed: Attempting to setuid as a normal user with RUID $<");
    }

    if ( $> != 0 ) {
        Cpanel::Debug::log_die("setuids failed: Attempting to setuid as a normal user with EUID $>");
    }
    return 0;
}

1;

} # --- END Cpanel/AccessIds/SetUids.pm


{ # --- BEGIN Cpanel/Sys/Setsid/Fast.pm
package Cpanel::Sys::Setsid::Fast;


use strict;
use warnings;

my $ALREADY_GAVE_UP_TTY = 0;
my $TIOCNOTTY           = 0x5422;

sub fast_setsid {
    setpgrp( 0, 0 );
    return if $ALREADY_GAVE_UP_TTY;
    open( my $tty, '+<', '/dev/tty' ) or do {
        $ALREADY_GAVE_UP_TTY = 1;
        return 0;    # if we can't open /dev/tty then we don't need to do anything.
    };
    ioctl( $tty, $TIOCNOTTY, 0 ) or die "Unable to ioctl on /dev/tty: $!";
    close $tty;
    return 1;
}

1

} # --- END Cpanel/Sys/Setsid/Fast.pm


{ # --- BEGIN Cpanel/AccessIds.pm
package Cpanel::AccessIds;


use strict;
use warnings;

use Try::Tiny;

# use Cpanel::ForkSync             ();
# use Cpanel::PwCache              ();
# use Cpanel::Debug                ();
# use Cpanel::LoadModule           ();
# use Cpanel::AccessIds::SetUids   ();
# use Cpanel::AccessIds::Normalize ();
# use Cpanel::Sys::Setsid::Fast    ();

our $VERSION = '1.4';



{
    no warnings 'once';
    *setuid            = *Cpanel::AccessIds::SetUids::setuids;
    *setuids           = *Cpanel::AccessIds::SetUids::setuids;
    *run_as_user_group = *runasusergroup;
    *run_as_user       = *runasuser;


    *do_as_current_user = *Cpanel::ForkSync::do_in_child;
}


sub runasuser {
    my $user = shift;
    my $gid  = ( Cpanel::PwCache::getpwnam_noshadow($user) )[3];    # gets passed to setuids() which works w/ numeric id or name
    my @CMDS = @_;
    return runasusergroup( $user, $gid, @CMDS );
}


sub runasusergroup {
    my ( $user, $group, @CMDS ) = @_;
    my $homedir = '';
    if ( $user !~ m/^\d+$/ ) {
        $homedir = Cpanel::PwCache::gethomedir($user);
    }
    else {
        $homedir = Cpanel::PwCache::gethomedir($user);
    }

    if ( my $pid = fork() ) {
        waitpid( $pid, 0 );
    }
    elsif ( defined $pid ) {
        Cpanel::Sys::Setsid::Fast::fast_setsid();
        Cpanel::AccessIds::SetUids::setuids( $user, $group );
        $ENV{'HOME'} = $homedir;

        exec @CMDS or die "exec(@CMDS) failed: $!";
    }
    else {
        die "The system failed to fork because of an error: $!";
    }

    return;
}


sub do_as_user {
    my ( $user, $code ) = @_;

    return do_as_user_group( $user, undef, $code );
}


sub do_as_user_with_exception {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my ( $code, $user, $group ) = Cpanel::AccessIds::Normalize::normalize_code_user_groups(@_);

    my $setuid_coderef = sub {
        Cpanel::Sys::Setsid::Fast::fast_setsid();
        Cpanel::AccessIds::SetUids::setuids( $user, $group );
        return $code->(@_);
    };

    my $forksync = Cpanel::ForkSync->new_quiet($setuid_coderef);

    if ( my $deserialize_err = $forksync->retrieve_error() ) {
        die "Failed to deserialize result from child: $deserialize_err";
    }
    elsif ( ref $forksync->structured_exception ) {
        die $forksync->structured_exception;
    }
    elsif ( $forksync->exception ) {
        die $forksync->exception;
    }

    my $ret = $forksync->return;
    if ( 'ARRAY' eq ref $ret ) {
        if (wantarray) {
            return @$ret;
        }
        else {
            return $ret->[-1];
        }
    }

    return;    # Hopefully will never be reached
}


sub do_as_user_group {    ## no critic qw(Subroutines::RequireArgUnpacking)
    local $@;

    my ( $code, $user, $group ) = eval { Cpanel::AccessIds::Normalize::normalize_code_user_groups(@_) };

    return if !length $user;
    return if !length $group;

    if ( !$user || !$group ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Carp');
        die Cpanel::Carp::safe_longmess("do_as_user_group may not be called for root.");
    }

    if ( !$code || ref $code ne 'CODE' ) {
        Cpanel::Debug::log_warn("Failed to provide CODE");
        return;
    }

    my $setuid_coderef = sub {
        Cpanel::Sys::Setsid::Fast::fast_setsid();
        Cpanel::AccessIds::SetUids::setuids( $user, $group );
        return $code->(@_);
    };

    return Cpanel::ForkSync::do_in_child($setuid_coderef);
}

1;

} # --- END Cpanel/AccessIds.pm


{ # --- BEGIN Cpanel/Reseller.pm
package Cpanel::Reseller;


use strict;

use Try::Tiny;

# use Cpanel::LoadFile    ();
# use Cpanel::Autodie     ();
# use Cpanel::Debug       ();
# use Cpanel::ConfigFiles ();

our %RESELLER_PRIV_CACHE;
our %RESELLER_EXISTS_CACHE;

our $reseller_cache_fully_loaded;    # exposed for testing.
our $is_dnsadmin;

sub isreseller {
    my $user = shift;
    return 1 if ( !defined $user || $user eq 'cpanel' || $user eq 'root' || $user eq '' );    #must be first or caches may overwrite see case 53421
    return 0 if ( $reseller_cache_fully_loaded && !exists $RESELLER_PRIV_CACHE{$user} );

    _load_one_reseller($user) unless ( exists $RESELLER_PRIV_CACHE{$user} || exists $RESELLER_EXISTS_CACHE{$user} );
    if ( exists $RESELLER_PRIV_CACHE{$user} || exists $RESELLER_EXISTS_CACHE{$user} ) {
        return ( ( $RESELLER_EXISTS_CACHE{$user} || scalar keys %{ $RESELLER_PRIV_CACHE{$user} } ) ? 1 : 0 );
    }
    return 0;
}

sub hasresellerpriv {
    my ( $reseller, $priv ) = @_;

    if ( !$reseller || !$priv ) {
        return 0;
    }
    elsif ( $reseller eq 'root' ) {
        return 1;
    }

    if ( exists $RESELLER_EXISTS_CACHE{$reseller} && !$RESELLER_EXISTS_CACHE{$reseller} ) {
        return 0;
    }

    _load_one_reseller($reseller) unless ( exists $RESELLER_PRIV_CACHE{$reseller} && ref $RESELLER_PRIV_CACHE{$reseller} );

    if ( exists $RESELLER_PRIV_CACHE{$reseller} && ref $RESELLER_PRIV_CACHE{$reseller} ) {
        return 1 if exists $RESELLER_PRIV_CACHE{$reseller}->{'all'};
        return ( exists $RESELLER_PRIV_CACHE{$reseller}->{$priv} ? 1 : 0 );
    }

    return 0;
}

sub _load_one_reseller {
    my ($reseller) = @_;
    my $quotedreseller = $reseller . ':';

    my $res_fh;
    try {
        Cpanel::Autodie::open( $res_fh, '<', $Cpanel::ConfigFiles::RESELLERS_FILE );
    }
    catch {
        Cpanel::Debug::log_warn( $_->to_string() );
    };

    if ( fileno $res_fh ) {
        my $line;
        while ( $line = readline $res_fh ) {
            if ( index( $line, $quotedreseller ) == 0 ) {    # $line =~ /^$quotedreseller/ ) {
                close $res_fh;

                chomp $line;
                $line =~ tr{ \t}{}d;
                $RESELLER_PRIV_CACHE{$reseller} = { map { $_ => 1 } split( m{,}, ( split( m{:}, $line, 2 ) )[1] ) };
                delete $RESELLER_PRIV_CACHE{$reseller}{''};
                return ( $RESELLER_EXISTS_CACHE{$reseller} = 1 );
            }
        }
        close $res_fh;
        return 1;
    }

    return ( $RESELLER_EXISTS_CACHE{$reseller} = 0 );
}

sub get_one_reseller_privs {
    my $reseller = shift;
    return _load_one_reseller($reseller) ? $RESELLER_PRIV_CACHE{$reseller} || {} : {};
}

sub getresellersaclhash {
    if ( !-e $Cpanel::ConfigFiles::RESELLERS_FILE ) {
        return wantarray ? () : {};
    }

    if ($reseller_cache_fully_loaded) {
        return wantarray ? %RESELLER_PRIV_CACHE : \%RESELLER_PRIV_CACHE;
    }

    %RESELLER_PRIV_CACHE = ();
    my $data = Cpanel::LoadFile::load_if_exists($Cpanel::ConfigFiles::RESELLERS_FILE);
    foreach my $line ( split( m{\n}, $data ) ) {
        $line =~ tr{ \t}{}d;
        my ( $reseller, $acl ) = split m{:}, $line, 2;
        next if ( !length $reseller || index( $reseller, '#' ) == 0 || !defined $acl );
        $RESELLER_PRIV_CACHE{$reseller} = { map { $_ => 1 } split m{,}, $acl };
    }
    $reseller_cache_fully_loaded = 1;
    @RESELLER_EXISTS_CACHE{ keys %RESELLER_PRIV_CACHE } = (1) x scalar keys %RESELLER_PRIV_CACHE;

    return wantarray ? %RESELLER_PRIV_CACHE : \%RESELLER_PRIV_CACHE;
}

sub getresellerslist {
    return wantarray ? ( sort keys %{ getresellersaclhash() } ) : [ sort keys %{ getresellersaclhash() } ];
}

1;

} # --- END Cpanel/Reseller.pm


{ # --- BEGIN Cpanel/Features/Utils.pm
package Cpanel::Features::Utils;


use strict;
use warnings;

use cPstrict;
# use Cpanel::LoadModule ();


sub cpuser_data_has_feature {
    die 'Invalid cpuser data!'  if !length $_[0];
    die 'Invalid feature name!' if !length $_[1];
    return ( ( $_[0]->{ 'FEATURE-' . ( $_[1] =~ tr[a-z][A-Z]r ) } // '' ) eq '0' ) ? 0 : 1;
}

sub _make_feature_key {
    return 'FEATURE-' . $_[0] =~ tr{a-z}{A-Z}r;
}

sub calendar_delegation_available_for ($loggedInUser) {

    Cpanel::LoadModule::load_perl_module('Cpanel::Config::LoadCpUserFile');
    Cpanel::LoadModule::load_perl_module('Cpanel::Features');

    my $user_file    = Cpanel::Config::LoadCpUserFile::load($loggedInUser);
    my $feature_list = $user_file->{'FEATURELIST'};
    my $info_list    = Cpanel::Features::get_featurelist_information($feature_list);

    my $calendar_delegation_setting = 0;

    for ( my $i = 0; $i < @{$info_list}; $i++ ) {
        my $this_item = @{$info_list}[$i];
        if ( $this_item->{id} eq 'manage_calendar_access' ) {
            $calendar_delegation_setting = $this_item->{value} eq "1" ? 1 : 0;
            last;
        }
    }
    return $calendar_delegation_setting;
}

1;

} # --- END Cpanel/Features/Utils.pm


{ # --- BEGIN Cpanel/Team/Constants.pm
package Cpanel::Team::Constants;


use cPstrict;


our $MAX_TEAM_USERS = 7;

our $TEAM_CONFIG_DIR = '/var/cpanel/team';

our $MAX_TEAM_NOTES_SIZE = 100;

our $TEAM_FEATURES_DIR = '/usr/local/cpanel/etc/team/features';

our $MAX_CONFIG_FILE_SIZE = 12287;

our %TEAM_ROLES = (
    'email'    => 'Email',
    'web'      => 'Web',
    'database' => 'Database',
    'admin'    => 'Administrator',
    'default'  => 'Default'
);

1;

} # --- END Cpanel/Team/Constants.pm


{ # --- BEGIN Cpanel/Features/Load.pm
package Cpanel::Features::Load;


use strict;
use warnings;

# use Cpanel::Config::LoadConfig ();
# use Cpanel::Team::Constants    ();

our $feature_list_dir;
our $feature_list_team_dir;

BEGIN {
    $feature_list_dir      = '/var/cpanel/features';
    $feature_list_team_dir = $Cpanel::Team::Constants::TEAM_FEATURES_DIR;
}

sub featurelist_file {
    die "“$_[0]” is not a valid feature name!" if ( -1 != index( $_[0], '/' ) && index( $_[0], $feature_list_team_dir ) != 0 );
    if ( index( $_[0], $feature_list_team_dir ) == 0 ) {
        return $_[0];
    }
    return "$feature_list_dir/$_[0]";
}

my ( $fl_hr, $err ) = @_;

sub load_featurelist {
    $fl_hr = load_feature_file( $_[0], $_[1] );

    return wantarray ? %$fl_hr : $fl_hr if $fl_hr;

    if ( load_and_fix_perms( $_[0] ) ) {

        eval q{require Cpanel::AdminBin::Call};    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        $fl_hr = Cpanel::AdminBin::Call::call( 'Cpanel', 'feature', 'LOADFEATUREFILE', $_[0], $_[1] );
        return wantarray ? %$fl_hr : $fl_hr if $fl_hr;
    }

    return;
}

sub is_feature_list {
    return ( !$_[0] || $_[0] eq '.' || $_[0] eq '..' || $_[0] =~ tr{\0\r\n}{} || !-e featurelist_file( $_[0] ) ) ? undef : 1;
}

sub load_and_fix_perms {
    return ( $> != 0 && !-r featurelist_file( $_[0] ) );
}

sub load_feature_file {
    ( $fl_hr, undef, undef, $err ) = Cpanel::Config::LoadConfig::loadConfig( featurelist_file( $_[0] ), undef, $_[1] || '[=:]', undef, qr/\s+/ );
    warn $err if $err;
    return $fl_hr;
}

1;    # Magic true value required at end of module

} # --- END Cpanel/Features/Load.pm


{ # --- BEGIN Cpanel/Features/Cpanel.pm
package Cpanel::Features::Cpanel;


use strict;
# use Cpanel::ConfigFiles                  ();
# use Cpanel::StringFunc::Case             ();
# use Cpanel::Features::Load               ();
# use Cpanel::AdminBin::Serializer::FailOK ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::LoadModule                   ();

my %FEATURE_MEMORY_CACHE;
my %FEATURE_FILE_LIST_MEMORY_CACHE;

sub fetch_feature_file_list_from_featurelist {
    my ($featurelist) = @_;
    return [
        $featurelist
        ? (
            { 'file' => 'default',    'logic' => 'disabler' },
            { 'file' => $featurelist, 'logic' => 'accept', 'skip_names' => [ 'disabled', 'default' ] },
            { 'file' => 'disabled',   'logic' => 'disabler' }
          )
        : (
            { 'file' => 'default',  'logic' => 'disabler' },
            { 'file' => 'disabled', 'logic' => 'disabler' }
        )
    ];

}

sub fetch_feature_file_list {
    my $cpuser_ref = $_[0];
    return fetch_feature_file_list_from_featurelist( $cpuser_ref->{'FEATURELIST'} );
}

my $_now;

sub now {
    my $value = shift;
    if ( defined $value ) {
        if ( $value eq 'freeze' ) {
            $_now = time();
        }
        elsif ( $value eq 'unfreeze' ) {
            $_now = undef;
        }
        else {
            $_now = $value;
        }
    }

    return $_now || scalar time();
}

sub calculate_cache_file_name_and_maxmtime {    ##no critic qw(RequireArgUnpacking)
    my @FEATURE_FILES     = @{ $_[0] };
    my $max_feature_mtime = my $max_team_feature_mtime = 0;
    my ( $now, @feature_cache_name );

    for ( 0 .. $#FEATURE_FILES ) {
        my $file = $FEATURE_FILES[$_]->{'file'};
        next if ( $FEATURE_FILES[$_]->{'skip_names'} && ref $FEATURE_FILES[$_]->{'skip_names'} eq 'ARRAY' && grep { $_ eq $file } @{ $FEATURE_FILES[$_]->{'skip_names'} } );
        my $filename = Cpanel::Features::Load::featurelist_file($file);
        $FEATURE_FILES[$_]->{'mtime'} = ( stat($filename) )[9];
        if ( $FEATURE_FILES[$_]->{'mtime'} ) {
            $max_feature_mtime = $FEATURE_FILES[$_]->{'mtime'} if ( $max_feature_mtime < $FEATURE_FILES[$_]->{'mtime'} && $FEATURE_FILES[$_]->{'mtime'} < ( $now ||= now() ) );
            push @feature_cache_name, $file;
        }
    }
    my $team_info = '';
    if ( $ENV{'TEAM_USER'} ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Team::Features');    # hide it from updatenow.static
        $max_team_feature_mtime = Cpanel::Team::Features::get_max_team_feature_mtime( $ENV{'TEAM_OWNER'}, $ENV{'TEAM_USER'} );
        $team_info              = "_$ENV{'TEAM_OWNER'}_$ENV{'TEAM_USER'}";
        $max_feature_mtime      = $max_feature_mtime > $max_team_feature_mtime ? $max_feature_mtime : $max_team_feature_mtime;
    }

    return ( "$Cpanel::ConfigFiles::features_cache_dir/featurelist-" . join( '_', @feature_cache_name ) . "$team_info.v2.cache", $max_feature_mtime );
}

sub populate {
    my ( $feature_files_ref, $data_ref, $cache_ref ) = @_;
    my ( $uc_feature_name, $FEATURES );
    foreach my $feature_list_ref ( @{$feature_files_ref} ) {
        my $cPanel_user_FEATURES = Cpanel::Features::Load::load_featurelist( $feature_list_ref->{'file'} );
        $FEATURES = $cPanel_user_FEATURES;
        if ( $ENV{'TEAM_USER'} ) {
            Cpanel::LoadModule::load_perl_module('Cpanel::Team::Features');    # hide it from updatenow.static
            $FEATURES = Cpanel::Team::Features::load_team_feature_list( $FEATURES, $feature_list_ref->{'file'} );
        }
        if ( $feature_list_ref->{'logic'} eq 'disabler' ) {
            foreach my $feature_name ( keys %$FEATURES ) {
                $uc_feature_name = 'FEATURE-' . Cpanel::StringFunc::Case::ToUpper($feature_name);
                if ( $FEATURES->{$feature_name} ne '1' && $FEATURES->{$feature_name} ne '' ) {
                    $cache_ref->{$uc_feature_name} = $data_ref->{$uc_feature_name} = $FEATURES->{$feature_name};
                }
            }
        }
        else {
            foreach my $feature_name ( keys %$FEATURES ) {
                $uc_feature_name = 'FEATURE-' . Cpanel::StringFunc::Case::ToUpper($feature_name);
                if ( $FEATURES->{$feature_name} eq '1' ) {
                    delete $data_ref->{$uc_feature_name};
                    delete $cache_ref->{$uc_feature_name};
                }
                else {
                    $cache_ref->{$uc_feature_name} = $data_ref->{$uc_feature_name} = $FEATURES->{$feature_name};
                }
            }
        }
    }
    return 1;
}

sub augment_hashref_with_features {
    my ( $featurelist, $hashref, $now ) = @_;

    $now         ||= time();
    $featurelist ||= '';       # It is possible to have an empty feature list
    my $featurelistkey = $ENV{'TEAM_USER'} ? "${featurelist}_$ENV{'TEAM_OWNER'}_$ENV{'TEAM_USER'}" : $featurelist;

    my ( $feature_cache_ref, $feature_cache_file, $max_feature_mtime, $feature_files_ref );

    if ( exists $FEATURE_FILE_LIST_MEMORY_CACHE{$featurelistkey} ) {
        ( $feature_files_ref, $feature_cache_file, $max_feature_mtime ) = @{ $FEATURE_FILE_LIST_MEMORY_CACHE{$featurelistkey} };
    }
    else {
        $feature_files_ref = fetch_feature_file_list_from_featurelist($featurelist);
        ( $feature_cache_file, $max_feature_mtime ) = calculate_cache_file_name_and_maxmtime($feature_files_ref);
        $FEATURE_FILE_LIST_MEMORY_CACHE{$featurelistkey} = [ $feature_files_ref, $feature_cache_file, $max_feature_mtime ];
    }

    if ( exists $FEATURE_MEMORY_CACHE{$feature_cache_file} ) {
        if ( $FEATURE_MEMORY_CACHE{$feature_cache_file}{'mtime'} == $max_feature_mtime ) {
            $feature_cache_ref = $FEATURE_MEMORY_CACHE{$feature_cache_file}{'cache'};
        }
    }

    Cpanel::AdminBin::Serializer::FailOK::LoadModule() if !$INC{'Cpanel/AdminBin/Serializer.pm'};
    if ( !$feature_cache_ref && $INC{'Cpanel/AdminBin/Serializer.pm'} ) {
        my $feature_cache_file_mtime = ( stat($feature_cache_file) )[9];
        Cpanel::LoadModule::load_perl_module('Cpanel::Team::Config');    # hide it from updatenow.static
        my $team_cache_file_mtime = Cpanel::Team::Config::get_mtime_team_config( $ENV{'TEAM_USER'}, $ENV{'TEAM_OWNER'} );
        if ( $feature_cache_file_mtime && $feature_cache_file_mtime > $max_feature_mtime && $feature_cache_file_mtime < $now && $feature_cache_file_mtime > $team_cache_file_mtime ) {
            $feature_cache_ref = Cpanel::AdminBin::Serializer::FailOK::LoadFile($feature_cache_file);
            if ( $feature_cache_ref && ref $feature_cache_ref eq 'HASH' ) {
                $FEATURE_MEMORY_CACHE{$feature_cache_file} = { 'mtime' => $max_feature_mtime, 'cache' => $feature_cache_ref };
            }
        }
    }

    if ( $feature_cache_ref && ref $feature_cache_ref eq 'HASH' ) {
        if (%$hashref) {
            foreach my $key ( keys %{$feature_cache_ref} ) {
                $hashref->{$key} = $feature_cache_ref->{$key};
            }
        }
        else {
            %$hashref = %$feature_cache_ref;
        }
        return $FEATURE_MEMORY_CACHE{$feature_cache_file}->{'mtime'};
    }

    my $cache_ref = {};
    populate( $feature_files_ref, $hashref, $cache_ref );

    $FEATURE_MEMORY_CACHE{$feature_cache_file} = { 'mtime' => $max_feature_mtime, 'cache' => $cache_ref };

    if ( $INC{'Cpanel/JSON.pm'} && $cache_ref ) {
        if ( $> == 0 ) {
            if ( !-e $Cpanel::ConfigFiles::features_cache_dir ) {
                require Cpanel::SafeDir::MK;
                Cpanel::SafeDir::MK::safemkdir( $Cpanel::ConfigFiles::features_cache_dir, 0755 );
            }
            Cpanel::FileUtils::Write::JSON::Lazy::write_file( $feature_cache_file, $cache_ref, 0644 );
        }
        elsif ( !$INC{'Test/More.pm'} ) {


            eval q{require Cpanel::AdminBin::Call};    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
            if ( $INC{'Cpanel/AdminBin/Call.pm'} ) {

                if ( !%Cpanel::CPDATA || !$Cpanel::CPDATA{'SUSPENDED'} ) {
                    warn if !eval { Cpanel::AdminBin::Call::call( 'Cpanel', 'feature', 'REBUILDFEATURECACHE' ); 1 };
                }
            }
            else {
                warn;
            }
        }
    }
    return $FEATURE_MEMORY_CACHE{$feature_cache_file}->{'mtime'};
}

sub clear_memory_cache {
    %FEATURE_MEMORY_CACHE           = ();
    %FEATURE_FILE_LIST_MEMORY_CACHE = ();
    return 1;
}

1;    # Magic true value required at end of module

} # --- END Cpanel/Features/Cpanel.pm


{ # --- BEGIN Cpanel/App.pm
package Cpanel::App;


use strict;
use warnings;



our $appname;

BEGIN {
    $appname = 'cpanel';
}

our $context = q{};



sub is_cpanel {
    return ( $appname eq 'cpanel' || $appname eq 'cpaneld' ) ? 1 : 0;
}


sub is_webmail {
    return ( $appname eq 'webmail' || $appname eq 'webmaild' ) ? 1 : 0;
}


sub is_whm {
    return ( ( $appname eq 'whostmgr' ) || ( $appname eq 'whm' ) || ( $appname eq 'whostmgrd' ) ) ? 1 : 0;
}



sub get_normalized_name {
    return is_cpanel() ? 'cpanel' : is_whm() ? 'whostmgr' : is_webmail() ? 'webmail' : die "Unknown appname: “$appname”!";
}



sub get_context_display_name {
    if ( is_webmail() ) {
        return 'Webmail';
    }
    elsif ( is_whm() ) {
        return 'WHM';
    }
    else {
        return "cPanel";
    }
}

1;

} # --- END Cpanel/App.pm


{ # --- BEGIN Cpanel/Themes/Get.pm
package Cpanel::Themes::Get;


use strict;
use warnings;

# use Cpanel::ConfigFiles       ();
# use Cpanel::App               ();
# use Cpanel::Config::Constants ();

our @THEME_FILE_EXT_SORT_ORDER = (qw(php cpphp phpcp html htm html.tt));
our %EOL_THEMES                = (
    NO            => 1,
    Y             => 1,
    YES           => 1,
    advanced      => 1,
    default       => 1,
    iconic        => 1,
    mailonly      => 1,
    tree          => 1,
    y             => 1,
    x2            => 1,
    x             => 1,
    x3            => 1,
    x3mail        => 1,
    x4            => 1,
    x4mail        => 1,
    xmail         => 1,
    bluelagoon    => 1,
    monsoon       => 1,
    Xskin         => 1,
    n             => 1,
    no            => 1,
    tree          => 1,
    gorgo         => 1,
    paper_lantern => 1
);

our %CPANEL_DISTRIBUTED_THEMES = (
    'jupiter' => 1,
);

sub get_list {
    return reverse sort keys %Cpanel::Themes::Get::CPANEL_DISTRIBUTED_THEMES;
}

sub theme_has_reached_eol {
    my ($theme) = @_;
    return $EOL_THEMES{$theme} ? 1 : 0;
}

sub is_usable_theme {
    my ($theme) = @_;
    return 0 if !$theme;
    return 1 if $CPANEL_DISTRIBUTED_THEMES{$theme};
    return 0 if $theme =~ m{\.\.} || $theme =~ m{/} || $theme =~ m{[\r\n]};

    return 0 if theme_has_reached_eol($theme);
    return get_theme_entry_url($theme) ? 1 : 0;
}

sub get_theme_entry_url {
    my ( $theme, $appname ) = @_;

    $appname ||= $Cpanel::App::appname || $Cpanel::appname || 'cpaneld';

    my $basedir = $appname =~ m{^webmail} ? 'webmail' : 'frontend';

    my $basepath = "$Cpanel::ConfigFiles::CPANEL_ROOT/base/$basedir";

    foreach my $ext (@THEME_FILE_EXT_SORT_ORDER) {
        if ( -e "$basepath/$theme/index.$ext" ) {
            return "/$basedir/$theme/index.$ext";
        }
    }

    return;

}

sub webmail_default_theme {
    require Cpanel::Conf;

    return Cpanel::Conf->new()->default_webmail_theme;
}

sub cpanel_default_theme {
    return $Cpanel::Config::Constants::DEFAULT_CPANEL_THEME;
}

1;

} # --- END Cpanel/Themes/Get.pm


{ # --- BEGIN Cpanel.pm
package Cpanel;


use strict;
use warnings;

# use Cpanel::StringFunc::Case                    ();
# use Cpanel::PwCache                             ();
# use Cpanel::Config::LoadCpConf                  ();
# use Cpanel::Config::LoadCpUserFile::CurrentUser ();
# use Cpanel::Config::Constants                   ();
# use Cpanel::Config::CpUser::Object              ();
# use Cpanel::ConfigFiles                         ();
# use Cpanel::Cookies                             ();
# use Cpanel::Reseller                            ();
# use Cpanel::Features::Utils                     ();
# use Cpanel::Features::Cpanel                    ();
# use Cpanel::Themes::Get                         ();
# use Cpanel::GlobalCache                         ();
# use Cpanel::SV                                  ();
use Cwd                                         ();

our $VERSION       = 2.2;
our $cpanelhomedir = $Cpanel::ConfigFiles::ROOT_CPANEL_HOMEDIR;
our ( %FORM, %RESELLERCACHE, %LOADEDMODS, $httphost, $isreseller, $user, $abshomedir, $homedir, %CPERROR, %CPDATA, %USERDATA, %CONF, %CPCACHE, %NEEDSREMOTEPASS, $root, @DOMAINS, $appname, $authuser, $DEBUG, %CPVAR, %Cookies, $machine, $release, $rootlogin, $FEATURE_CACHE_MTIME );

$root = $Cpanel::ConfigFiles::CPANEL_ROOT;

sub initcp {    ## no critic qw(ProhibitExcessComplexity)
    my ($user) = @_;

    %Cpanel::NEEDSREMOTEPASS = ();
    %Cpanel::CPCACHE         = ();
    undef $Cpanel::user;

    if ( !$Cpanel::appname ) {
        $Cpanel::appname = 'cpaneld';
    }
    elsif ( $Cpanel::appname eq 'webmail' ) {
        $Cpanel::user = ( Cpanel::PwCache::getpwuid_noshadow($>) )[0];
    }

    ( $Cpanel::authuser, $Cpanel::user ) = ( $ENV{'REMOTE_USER'} || $user, ( $user || $Cpanel::user || $ENV{'REMOTE_USER'} ) );

    if ( $ENV{'HTTP_HOST'} ) {
        $Cpanel::httphost = ( split( m{:}, $ENV{'HTTP_HOST'}, 2 ) )[0];
    }

    if ( !$Cpanel::user || $Cpanel::user =~ tr/\@// ) {
        @Cpanel::USERDATA{ 'user', 'pass', 'uid', 'gid', 'name', 'home', 'shell' } = ( Cpanel::PwCache::getpwuid_noshadow($>) )[ 0, 1, 2, 3, 6, 7, 8 ];
        die "The password file entry for the uid “$>” is missing" if !$Cpanel::USERDATA{'user'};
        $Cpanel::user = $Cpanel::USERDATA{'user'};
    }
    else {
        @Cpanel::USERDATA{ 'user', 'pass', 'uid', 'gid', 'name', 'home', 'shell' } = ( Cpanel::PwCache::getpwnam_noshadow($Cpanel::user) )[ 0, 1, 2, 3, 6, 7, 8 ];
        die "The password file entry for the user “$Cpanel::user” is missing" if !$Cpanel::USERDATA{'user'};
        $Cpanel::USERDATA{'home'} = Cpanel::PwCache::gethomedir()             if $Cpanel::USERDATA{'uid'} != $>;    # Must be set to prevent writing to user's homedir
    }

    $ENV{'USER'} = $Cpanel::user = $Cpanel::USERDATA{'user'};
    Cpanel::SV::untaint($Cpanel::user);

    tie $isreseller, 'Cpanel::IsResellerTie', $Cpanel::user;

    if ( $Cpanel::user eq '' || $Cpanel::user eq 'root' || $Cpanel::user eq 'cpanel' ) {
        $Cpanel::rootlogin        = 1;
        $Cpanel::abshomedir       = resolvesymlinks( ( $ENV{'HOME'} = $Cpanel::homedir = $Cpanel::cpanelhomedir ) );
        $Cpanel::USERDATA{'home'} = $Cpanel::cpanelhomedir;
    }
    else {
        $Cpanel::homedir = $Cpanel::USERDATA{'home'};
        Cpanel::SV::untaint($Cpanel::homedir);
        $Cpanel::abshomedir = resolvesymlinks( ( $ENV{'HOME'} = $Cpanel::homedir ) );
    }
    $ENV{'TMPDIR'} = $Cpanel::homedir . '/tmp';

    tie %Cpanel::CONF, 'Cpanel::CPCONFTie' if !tied %Cpanel::CONF;

    my $cpdata_ref;

    if ($Cpanel::rootlogin) {
        $cpdata_ref = Cpanel::Config::CpUser::Object->adopt( {} );
    }
    else {
        $cpdata_ref = Cpanel::Config::LoadCpUserFile::CurrentUser::load($Cpanel::user);

        if ( !%$cpdata_ref ) {
            if ($Cpanel::isreseller) {
                $cpdata_ref = {};
            }
            else {
                die "Failed to load $Cpanel::user’s config file! (errno=$!)";
            }
        }
    }

    *Cpanel::CPDATA = $cpdata_ref;

    if ( !$Cpanel::CPDATA{'BWLIMIT'} || $Cpanel::CPDATA{'BWLIMIT'} eq 'unlimited' ) {
        $Cpanel::CPDATA{'BWLIMIT'} = 0;
    }

    if ( $Cpanel::user eq 'cpanel' ) {
        require Cpanel::Hostname;
        my $hostname = Cpanel::Hostname::gethostname();
        $Cpanel::CPDATA{'DOMAIN'}  = $hostname;
        $Cpanel::CPDATA{'DOMAINS'} = [$hostname];
    }

    $Cpanel::CPDATA{'DNS'} = $Cpanel::CPDATA{'DOMAIN'};
    *Cpanel::DOMAINS = $Cpanel::CPDATA{'DOMAINS'} if $Cpanel::CPDATA{'DOMAIN'};
    unshift @Cpanel::DOMAINS, $Cpanel::CPDATA{'DOMAIN'};


    if ( ( $Cpanel::CPDATA{'FEATURELIST'} || q<> ) =~ tr</><> ) {
        my $trimmed = $Cpanel::CPDATA{'FEATURELIST'} =~ tr</><>d;
        warn "Treating the FEATURELIST “$Cpanel::CPDATA{'FEATURELIST'}” as “$trimmed”.";
        $Cpanel::CPDATA{'FEATURELIST'} = $trimmed;
    }

    my $ref = {};
    $Cpanel::FEATURE_CACHE_MTIME = Cpanel::Features::Cpanel::augment_hashref_with_features( $Cpanel::CPDATA{'FEATURELIST'}, $ref );

    if ( my @keys_to_copy_from_ref = grep { !exists $Cpanel::CPDATA{$_} } keys %{$ref} ) {
        @Cpanel::CPDATA{@keys_to_copy_from_ref} = @{$ref}{@keys_to_copy_from_ref};
    }

    my $cpuser_rs = $Cpanel::CPDATA{'RS'} || q<>;

    if ( !grep { $_ eq $cpuser_rs } ( Cpanel::Themes::Get::get_list() ) ) {
        if ( !Cpanel::Themes::Get::is_usable_theme( $Cpanel::CPDATA{'RS'} ) ) {
            if ( $cpuser_rs && ( $cpuser_rs eq 'mailonly' || $cpuser_rs =~ m{mail$} ) ) {
                $Cpanel::CPDATA{'RS'} = $Cpanel::appname eq 'webmail' ? $Cpanel::Config::Constants::DEFAULT_WEBMAIL_MAILONLY_THEME : $Cpanel::Config::Constants::DEFAULT_CPANEL_MAILONLY_THEME;
            }
            else {
                $Cpanel::CPDATA{'RS'} = $Cpanel::appname eq 'webmail' ? Cpanel::Themes::Get::webmail_default_theme() : Cpanel::Themes::Get::cpanel_default_theme();
            }
        }

    }

    $CPVAR{'debug'}        = $DEBUG = $Cpanel::CPDATA{'DEBUG'} ? 1 : 0;
    $CPVAR{'featuredebug'} = $Cpanel::CPDATA{'FEATUREDEBUG'}   ? 1 : 0;

    if ( !$Cpanel::CPDATA{'LOCALE'} ) {

        require Cpanel::Locale::Utils::User;
        Cpanel::Locale::Utils::User::init_cpdata_keys( $Cpanel::user, $Cpanel::USERDATA{'uid'}, $Cpanel::USERDATA{'home'} );
    }

    if ( defined( $ENV{'CPSESSIONTHEME'} ) && $Cpanel::isreseller ) {
        $Cpanel::CPDATA{'RS'} = $ENV{'CPSESSIONTHEME'};
    }

    if ( $< == 0 ) {
        tie $homedir, 'Cpanel::HomeDirTie', $homedir;
    }
    return;
}

sub current_username {
    return $Cpanel::user || Cpanel::PwCache::getusername();
}

my %_global_cache_required_features = ( 'dnssec' => 'is_dnssec_supported', 'passengerapps' => 'has_modpassenger', 'sslinstall' => 'allowcpsslinstall' );

my %feature_has_override_module = map { $_ => undef } (
    'spamassassin',
);

sub hasfeature {

    return 1 if !$_[0];

    if ($Cpanel::rootlogin) {
        if ( Cpanel::StringFunc::Case::ToLower( $_[0] ) eq 'style' || Cpanel::StringFunc::Case::ToLower( $_[0] ) eq 'setlang' ) {
            return 1;
        }
        return 0;
    }
    elsif ( exists $feature_has_override_module{ $_[0] } ) {
        my $module_name = "Cpanel::Features::Override::$_[0]";

        local ( $!, $@ );
        require( ( $module_name =~ s<::></>rg ) . '.pm' );

        return 0 if $module_name->what_disables();
    }

    if ( Cpanel::Features::Utils::cpuser_data_has_feature( \%CPDATA, $_[0] ) ) {
        return $_global_cache_required_features{ $_[0] }
          ? Cpanel::GlobalCache::data( 'cpanel', $_global_cache_required_features{ $_[0] } )
          : 1;
    }

    return 0;
}

sub set_api_error {
    my $error  = shift;
    my $module = shift;
    $Cpanel::CPERROR{ $module || ( split( /::/, lc( ( caller() )[0] ) ) )[1] } = $error || 'Unknown error';
    return 0;
}

sub resolvesymlinks {
    return Cpanel::SV::untaint( Cwd::abs_path( $_[0] ) );    # case CPANEL-11199
}

*isreseller = *Cpanel::Reseller::isreseller;

sub loadcookies {
    %Cookies = %{ Cpanel::Cookies::get_cookie_hashref() };
    return;
}

{

    package Cpanel::IsResellerTie;

    my %isreseller;

    sub TIESCALAR {
        my ( $class, $isreseller ) = @_;
        return bless \$isreseller, __PACKAGE__;
    }

    sub FETCH {
        return exists $isreseller{$Cpanel::user} ? $isreseller{$Cpanel::user} : ( $isreseller{$Cpanel::user} = Cpanel::Reseller::isreseller($Cpanel::user) );
    }
    sub STORE { }
}
{

    package Cpanel::HomeDirTie;

    my $homedir;
    my $homedir_uid;
    my $current_euid;

    sub TIESCALAR {
        my ( $class, $original_homedir ) = @_;
        if ($original_homedir) {
            $homedir_uid = $>;
            $homedir     = $original_homedir;
        }
        return bless \$homedir, __PACKAGE__;
    }

    sub FETCH {
        if ( !defined $homedir_uid || $homedir_uid != ( $current_euid = $> ) || !defined $homedir ) {
            $homedir     = Cpanel::PwCache::gethomedir($current_euid);
            $homedir_uid = $current_euid;
        }
        return $homedir;
    }

    sub STORE {
        my $self = shift;
        $homedir     = shift;
        $homedir_uid = $>;
        return;
    }
}
{

    package Cpanel::CPCONFTie;

    sub TIEHASH {
        my $ref         = shift;
        my $cpconf_data = {};
        bless $cpconf_data, $ref;
        *FETCH = *_SLOWFETCH;
        return $cpconf_data;
    }

    sub _QUICKFETCH {    ## no critic(RequireArgUnpacking)
        return $_[0]->{'cpconf'}->{ $_[1] };
    }

    sub _SLOWFETCH {     ## no critic(RequireArgUnpacking)
        *FETCH = *_QUICKFETCH;
        $_[0]->{'cpconf'} = Cpanel::Config::LoadCpConf::loadcpconf_not_copy() if !exists $_[0]->{'cpconf'};
        return $_[0]->{'cpconf'}->{ $_[1] };
    }

    sub STORE {    ## no critic(RequireArgUnpacking)
        $_[0]->{'cpconf'} = Cpanel::Config::LoadCpConf::loadcpconf_not_copy() if !exists $_[0]->{'cpconf'};
        return $_[0]->{'cpconf'}->{ $_[1] } = $_[2];
    }

    sub DELETE {    ## no critic(RequireArgUnpacking)
        $_[0]->{'cpconf'} = Cpanel::Config::LoadCpConf::loadcpconf_not_copy() if !exists $_[0]->{'cpconf'};
        return delete $_[0]->{'cpconf'}->{ $_[1] };
    }

    sub FIRSTKEY {    ## no critic(RequireArgUnpacking)
        $_[0]->{'cpconf'} = Cpanel::Config::LoadCpConf::loadcpconf_not_copy() if !exists $_[0]->{'cpconf'};
        my $a = keys %{ $_[0]->{'cpconf'} };    # reset each() iterator
        return each %{ $_[0]->{'cpconf'} };
    }

    sub NEXTKEY {                               ## no critic(RequireArgUnpacking)

        return each %{ $_[0]->{'cpconf'} };
    }

    sub EXISTS {    ## no critic(RequireArgUnpacking)
        $_[0]->{'cpconf'} = Cpanel::Config::LoadCpConf::loadcpconf_not_copy() if !exists $_[0]->{'cpconf'};
        return exists $_[0]->{'cpconf'}->{ $_[1] };
    }

    sub CLEAR {     ## no critic(RequireArgUnpacking)
        $_[0]->{'cpconf'} = {};
        return;
    }
}

1;

} # --- END Cpanel.pm


{ # --- BEGIN Cpanel/Validate/EmailRFC.pm
package Cpanel::Validate::EmailRFC;



use strict;
use warnings;

# use Cpanel::StringFunc::Case     ();
# use Cpanel::StringFunc::Trim     ();
# use Cpanel::WildcardDomain::Tiny ();

sub is_valid {
    my ($name) = @_;
    return if !defined $name || index( $name, '@' ) == -1;

    my ( $local, $domain ) = get_name_and_domain($name);
    return unless defined $local and defined $domain;
    return is_localpart_valid($local) && is_domain_valid($domain);
}

sub is_valid_remote {
    my ($name) = @_;
    return if !defined $name || index( $name, '@' ) == -1;

    my ( $local, $domain ) = get_name_and_domain($name);
    return unless defined $local and defined $domain;
    return is_localpart_valid($local) && is_domain_valid_remote($domain);
}

sub is_valid_remote_or_die {
    my ($name) = @_;

    if ( !is_valid_remote($name) ) {
        local ( $@, $! );
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'InvalidParameter', '“[_1]” is not a valid email address.', [$name] );
    }

    return;
}

sub normalize {
    my ($name) = @_;
    return unless defined $name;
    $name =~ s/\0//g;

    $name = Cpanel::StringFunc::Trim::ws_trim($name);
    $name = Cpanel::StringFunc::Case::ToLower($name);

    return $name;
}

sub get_name_and_domain {
    my ($name) = @_;
    return unless defined $name;
    my ( $local, $domain ) = split( /\@/, $name, 2 );
    return ( $local ? $local : undef, $domain ? $domain : undef );
}

sub has_email_separator {
    my ($str) = @_;
    return scalar $str =~ /\@/;
}

sub is_localpart_valid {
    my ($local) = @_;
    return if !length $local;
    return $local =~ m/
        \A
        [a-zA-Z0-9!#\$%&'*+\-\/=?^_`{|}~]+
        (?:
            \.
            [a-zA-Z0-9!#\$%&'*+\-\/=?^_`{|}~]+
        )*
        \z
    /x;
}

sub is_domain_valid {
    my ($domain) = @_;
    return unless defined $domain;
    return 0 if Cpanel::WildcardDomain::Tiny::is_wildcard_domain($domain);
    return scalar $domain =~ m/
        \A
        [0-9a-zA-Z]
        (?:
            [0-9a-zA-Z-]*
            [0-9a-zA-Z]
        )?
        (?:
            \.
            [0-9a-zA-Z]
            (?:
                [0-9a-zA-Z-]*
                [0-9a-zA-Z]
            )?
        )*
        \z
    /x;
}

sub is_domain_valid_remote {
    my ($domain) = @_;
    return unless defined $domain;

    return unless scalar $domain =~ m/
        \A
        [0-9a-zA-Z]
        (?:
            [0-9a-zA-Z-]*
            [0-9a-zA-Z]
        )?
        (?:
            \.
            [0-9a-zA-Z]
            (?:
                [0-9a-zA-Z-]*
                [0-9a-zA-Z]
            )?
        )+
        \z
    /x;

    return Cpanel::StringFunc::Case::ToLower($domain) ne 'localhost.localdomain';
}

sub scrub {
    my ($name) = @_;
    return unless defined $name;
    $name = normalize($name);
    $name =~ s/\.\.+/./g;
    my ( $user, $domain ) = get_name_and_domain($name);
    return unless defined $user and defined $domain;
    $user =~ tr/a-z0-9!#$%&'*+\-\/=?^_`{|}~.//cd;

    $domain =~ tr/a-z0-9\-.//cd;
    return "$user\@$domain";
}

1;

} # --- END Cpanel/Validate/EmailRFC.pm


{ # --- BEGIN Cpanel/ContactInfo/Email.pm
package Cpanel::ContactInfo::Email;


use cPstrict;



# use Cpanel::Context            ();
# use Cpanel::Validate::EmailRFC ();



sub split_multi_email_string ($email_string) {
    Cpanel::Context::must_be_list();

    my @addr;

    if ( length $email_string ) {
        for my $email ( split m/\s*[;,]+\s*/, $email_string ) {
            if ( Cpanel::Validate::EmailRFC::is_valid_remote($email) ) {
                push @addr, $email;
            }
        }
    }

    return @addr;
}

1;

} # --- END Cpanel/ContactInfo/Email.pm


{ # --- BEGIN Cpanel/Validate/FilesystemPath.pm
package Cpanel::Validate::FilesystemPath;


use strict;

use Try::Tiny;

# use Cpanel::Exception                    ();
# use Cpanel::Validate::FilesystemNodeName ();

sub is_valid {
    my ($node) = @_;

    my $err;
    try { validate_or_die($node) } catch { $err = $_ };

    return !$err ? 1 : 0;
}

sub die_if_any_relative_nodes {
    my ($path) = @_;

    validate_or_die($path);

    if ( grep { $_ eq '.' || $_ eq '..' } split m</>, $path ) {
        die Cpanel::Exception::create( 'InvalidParameter', 'Relative filesystem nodes are invalid.' );
    }

    return 1;
}

sub validate_or_die {
    my ($path) = @_;

    if ( !length $path ) {
        die Cpanel::Exception::create('Empty');
    }

    my $original_name = $path;

    $path =~ tr</><>s;

    my $is_absolute_path = index( $path, '/' ) == 0;
    substr( $path, 0, 1, '' ) if $is_absolute_path;
    chop($path)               if substr( $path, -1 ) eq '/';

    my $depth = 0;
    for my $piece ( split m</>, $path ) {
        next if $piece eq '.';

        if ( $piece eq '..' ) {
            if ($is_absolute_path) {
                $depth--;
                if ( $depth < 0 ) {
                    die Cpanel::Exception::create( 'InvalidParameter', 'This absolute path references a nonexistent parent directory.' );
                }
            }
            next;
        }

        $depth++ if $is_absolute_path;

        try {
            Cpanel::Validate::FilesystemNodeName::validate_or_die($piece);
        }
        catch {
            if ( UNIVERSAL::isa( $_, 'Cpanel::Exception::TooManyBytes' ) ) {
                die Cpanel::Exception::create( 'InvalidParameter', 'The node “[_1]” is too long: [_2]', [ $_->get('value'), $_->to_string_no_id() ] );
            }

            die $_;
        };
    }

    return 1;
}

1;

} # --- END Cpanel/Validate/FilesystemPath.pm


{ # --- BEGIN Cpanel/MultiUserDirStore.pm
package Cpanel::MultiUserDirStore;


use strict;
use warnings;

# use Cpanel::Exception                    ();
# use Cpanel::PwCache                      ();
# use Cpanel::LoadModule                   ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Validate::FilesystemPath     ();

sub new {
    my ( $class, %OPTS ) = @_;

    foreach my $param (qw(dir subdir user)) {
        die Cpanel::Exception::create( 'MissingParameter', 'The required parameter “[_1]” is missing.', [$param] ) if !$OPTS{$param};
    }

    my $dir    = $OPTS{'dir'};
    my $user   = $OPTS{'user'};
    my $subdir = $OPTS{'subdir'};    # Should we name this something else?

    Cpanel::Validate::FilesystemNodeName::validate_or_die($subdir);
    Cpanel::Validate::FilesystemNodeName::validate_or_die($user);
    Cpanel::Validate::FilesystemPath::die_if_any_relative_nodes($dir);

    my $user_gid = ( Cpanel::PwCache::getpwnam($user) )[3];
    if ( !defined $user_gid ) {
        die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” with a value of “[_2]” must be a valid system user.', [ 'user', $user ] );
    }

    my $user_dir = "$dir/$user";
    if ( !-d $user_dir ) {
        if ( !-d $dir ) {
            Cpanel::LoadModule::load_perl_module('Cpanel::SafeDir::MK');
            Cpanel::SafeDir::MK::safemkdir( $dir, 0751 ) || die Cpanel::Exception::create( 'IO::DirectoryCreateError', [ path => $dir, error => $! ] );
        }

        Cpanel::LoadModule::load_perl_module('Cpanel::SafeDir::MK');
        Cpanel::SafeDir::MK::safemkdir( $user_dir, 0750 ) || die Cpanel::Exception::create( 'IO::DirectoryCreateError', [ path => $user_dir, error => $! ] );
        chown( 0, $user_gid, $user_dir ) || die Cpanel::Exception::create( 'IO::ChownError', [ path => [$user_dir], uid => 0, gid => $user_gid, error => $! ] );
    }

    my $path = $class->_init_path(%OPTS);

    return bless { 'dir' => $dir, 'subdir' => $subdir, 'user' => $user, 'path' => $path }, $class;
}

sub _init_path {
    my ( $class, %OPTS ) = @_;

    my ( $dir, $user, $subdir ) = @OPTS{qw(dir user subdir)};

    my $path = "$dir/$user/$subdir";

    if ( !-d $path ) {
        Cpanel::LoadModule::load_perl_module('Cpanel::SafeDir::MK');
        Cpanel::SafeDir::MK::safemkdir( $path, 0755 ) || die Cpanel::Exception::create( 'IO::DirectoryCreateError', [ path => $path, error => $! ] );
    }

    return $path;
}

1;

} # --- END Cpanel/MultiUserDirStore.pm


{ # --- BEGIN Cpanel/MultiUserDirStore/TimeIndexedData.pm
package Cpanel::MultiUserDirStore::TimeIndexedData;


use strict;
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Exception                    ();
# use Cpanel::FileUtils::Open              ();

# use Cpanel::MultiUserDirStore();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::MultiUserDirStore); }

sub new {
    my ( $class, %OPTS ) = @_;

    die Cpanel::Exception::create( 'MissingParameter', 'The required parameter “[_1]” is missing.',    ['keep_time'] ) if !$OPTS{'keep_time'};
    die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” must be a whole number.', ['keep_time'] ) if $OPTS{'keep_time'} !~ m{^[1-9][0-9]*$};

    my $obj = $class->SUPER::new(%OPTS);

    $obj->{'keep_time'} = $OPTS{'keep_time'};

    return $obj;
}

sub purge_expired {
    my ($self) = @_;

    my $expiretime = ( time() - $self->{'keep_time'} );
    my $path       = $self->{'path'};

    if ( opendir( my $dh, $path ) ) {
        my $cruntime;
        my @expired_files = map {
            $cruntime = ( split( m/_/, $_ ) )[0] || $expiretime;
            $cruntime < $expiretime ? "$path/$_" : ();
        } grep { substr( $_, 0, 1 ) =~ tr{0-9}{} } readdir($dh);

        unlink(@expired_files) if @expired_files;

        closedir($dh);

        return 1;
    }
    else {
        die Cpanel::Exception::create( 'IO::DirectoryOpenError', [ path => $path, error => $! ] );
    }

    return 0;
}


sub get_entry_target {
    my ( $self, %OPTS ) = @_;

    foreach my $param (qw(fields type)) {
        if ( !$OPTS{$param} ) {
            die Cpanel::Exception::create( 'MissingParameter', 'The required parameter “[_1]” is missing.', [$param] );
        }
    }

    my $time   = $OPTS{'time'} || time();
    my $fields = $OPTS{'fields'};
    my $type   = $OPTS{'type'};

    if ( ref $fields ne 'ARRAY' ) {
        die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” must be an arrayref.', ['fields'] );
    }
    Cpanel::Validate::FilesystemNodeName::validate_or_die($time);
    foreach my $field ( @{$fields} ) {
        Cpanel::Validate::FilesystemNodeName::validate_or_die($field) if length $field;
    }
    Cpanel::Validate::FilesystemNodeName::validate_or_die($type);

    my $filename  = join( '_', $self->_strip_underscores( $time, @{$fields} ) ) . '.' . $type;
    my $file_path = "$self->{'path'}/$filename";
    my $fh;

    Cpanel::FileUtils::Open::sysopen_with_real_perms( $fh, $file_path, 'O_WRONLY|O_CREAT', 0644 ) or die Cpanel::Exception::create( 'IO::FileOpenError', [ path => $file_path, error => $! ] );

    return {
        'fh'   => $fh,
        'path' => $file_path,
    };
}

sub _strip_underscores {
    my ( $self, @data ) = @_;

    tr<_><>d for @data;

    return @data;
}

1;

} # --- END Cpanel/MultiUserDirStore/TimeIndexedData.pm


{ # --- BEGIN Cpanel/MultiUserDirStore/VirtualUser.pm
package Cpanel::MultiUserDirStore::VirtualUser;


use strict;

# use Cpanel::AcctUtils::DomainOwner::Tiny ();
# use Cpanel::Exception                    ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::LoadModule                   ();

# use Cpanel::MultiUserDirStore();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::MultiUserDirStore); }

sub new {
    my ( $class, %OPTS ) = @_;

    foreach my $param (qw(virtual_user domain service)) {
        die Cpanel::Exception::create( 'MissingParameter', 'The required parameter “[_1]” is missing.', [$param] ) if !$OPTS{$param};
    }

    for my $param_value ( @OPTS{qw(virtual_user domain service)} ) {
        Cpanel::Validate::FilesystemNodeName::validate_or_die($param_value);
    }

    return $class->SUPER::new(%OPTS);
}

sub _init_path {
    my ( $class, %OPTS ) = @_;

    my ( $dir, $user, $subdir, $virtual_user, $domain, $service ) = @OPTS{qw( dir user subdir virtual_user domain service )};

    if ( Cpanel::AcctUtils::DomainOwner::Tiny::getdomainowner( $domain, { 'default' => q{} } ) ne $user ) {
        die Cpanel::Exception::create( 'DomainOwnership', 'The account “[_1]” does not own the domain “[_2]”.', [ $user, $domain ] );
    }

    Cpanel::LoadModule::load_perl_module('Cpanel::AcctUtils::Lookup::MailUser::Exists');
    if ( !Cpanel::AcctUtils::Lookup::MailUser::Exists::does_mail_user_exist("$virtual_user\@$domain") ) {
        die Cpanel::Exception::create( 'UserNotFound', 'The account “[_1]” does not own the email account “[_2]”.', [ $user, "$virtual_user\@$domain" ] );
    }

    my $user_dir = "$dir/$user";
    my $path     = "$user_dir/$domain/$service/$virtual_user/$subdir";
    for my $current_path ( "$user_dir/$domain", "$user_dir/$domain/$service", "$user_dir/$domain/$service/$virtual_user", $path ) {
        next if -d $current_path;
        Cpanel::LoadModule::load_perl_module('Cpanel::SafeDir::MK');
        Cpanel::SafeDir::MK::safemkdir( $current_path, 0755 ) || die Cpanel::Exception::create( 'IO::DirectoryCreateError', [ path => $current_path, error => $! ] );
    }

    return $path;
}

1;

} # --- END Cpanel/MultiUserDirStore/VirtualUser.pm


{ # --- BEGIN Cpanel/MultiUserDirStore/VirtualUser/TimeIndexedData.pm
package Cpanel::MultiUserDirStore::VirtualUser::TimeIndexedData;


use strict;

# use Cpanel::Exception ();

# use Cpanel::MultiUserDirStore::VirtualUser();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::MultiUserDirStore::VirtualUser); }
# use Cpanel::MultiUserDirStore::TimeIndexedData();
BEGIN { push @ISA, qw(Cpanel::MultiUserDirStore::TimeIndexedData); }

sub new {
    my ( $class, %OPTS ) = @_;

    die Cpanel::Exception::create( 'MissingParameter', 'The required parameter “[_1]” is missing.',    ['keep_time'] ) if !$OPTS{'keep_time'};
    die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” must be a whole number.', ['keep_time'] ) if $OPTS{'keep_time'} !~ m{^[1-9][0-9]*$};

    my $obj = $class->SUPER::new(%OPTS);

    $obj->{'keep_time'} = $OPTS{'keep_time'};

    return $obj;
}

1;

} # --- END Cpanel/MultiUserDirStore/VirtualUser/TimeIndexedData.pm


{ # --- BEGIN Cpanel/iContact/History.pm


package Cpanel::iContact::History;

use strict;

# use Cpanel::ConfigFiles                                     ();
# use Cpanel::MultiUserDirStore::TimeIndexedData              ();
# use Cpanel::MultiUserDirStore::VirtualUser::TimeIndexedData ();

our $USER_NOTIFICATIONS_HISTORY_STORAGE_DIR = 'history';
our $SECONDS_TO_KEEP_HISTORY_FOR_EACH_USER  = ( 10 * 86400 );    # 10 DAYS

sub get_user_contact_history {
    my (%OPTS) = @_;

    return Cpanel::MultiUserDirStore::TimeIndexedData->new(
        'keep_time' => $SECONDS_TO_KEEP_HISTORY_FOR_EACH_USER,
        'dir'       => $Cpanel::ConfigFiles::USER_NOTIFICATIONS_DIR,
        'subdir'    => $USER_NOTIFICATIONS_HISTORY_STORAGE_DIR,
        %OPTS,
    );
}

sub get_virtual_user_contact_history {
    my (%OPTS) = @_;

    return Cpanel::MultiUserDirStore::VirtualUser::TimeIndexedData->new(
        'keep_time' => $SECONDS_TO_KEEP_HISTORY_FOR_EACH_USER,
        'dir'       => $Cpanel::ConfigFiles::USER_NOTIFICATIONS_DIR,
        'subdir'    => $USER_NOTIFICATIONS_HISTORY_STORAGE_DIR,
        %OPTS,
    );
}

1;

} # --- END Cpanel/iContact/History.pm


{ # --- BEGIN Cpanel/iContact.pm
package Cpanel::iContact;


use strict;
use warnings;

use Try::Tiny;

# use Cpanel::AcctUtils::DomainOwner::Tiny ();
# use Cpanel::ArrayFunc::Uniq              ();
# use Cpanel::Exception                    ();
# use Cpanel::FHUtils::Tiny                ();
# use Cpanel::iContact::EventImportance    ();
# use Cpanel::iContact::Providers          ();
# use Cpanel::LoadModule::Custom           ();
# use Cpanel::Debug                        ();
# use Cpanel::Hostname                     ();
# use Cpanel::Validate::EmailCpanel        ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Validate::Domain::Tiny       ();
# use Cpanel::Validate::VirtualUsername    ();
# use Cpanel::StringFunc::Trim             ();
# use Cpanel::Config::LoadCpUserFile       ();
# use Cpanel::Config::HasCpUserFile        ();
# use Cpanel::Config::LoadWwwAcctConf      ();
# use Cpanel::iContact::Email              ();
# use Cpanel::PwCache                      ();
# use Cpanel::LoadModule                   ();
# use Whostmgr::UI                         ();    # PPI USE OK - it is being used below, at least a little.

my $NON_ROOT_EVENT_PRIORITY = $Cpanel::iContact::EventImportance::DEFAULT_IMPORTANCE;

our $VERSION = '1.4';
our @LAST_ERRORS;

my $LOG_KEEP_DAYS = 30;
my %CONTACTS;
my $optional_components;

sub clevels_file { return '/var/cpanel/clevels.conf' }

our %RECEIVES_NAME_TO_NUMBER = (
    'None'              => $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'Disabled'},
    'HighOnly'          => $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'High'},
    'HighAndMediumOnly' => $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'Medium'},
    'All'               => $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'Low'},
);

our %ICONTACT_PROVIDERS = (
    'CONTACTUIN'        => 'Oscar',
    'CONTACTPUSHBULLET' => 'Pushbullet',
    'CONTACTEMAIL'      => 'Email',
    'CONTACTPAGER'      => 'Pager',
    'CONTACTSMS'        => 'SMS',
);

sub icontact {    ## no critic (ProhibitExcessComplexity)
    my %AGS = @_;

    local $Cpanel::SQLite::AutoRebuildBase::SKIP_INTEGRITY_CHECK;
    $Cpanel::SQLite::AutoRebuildBase::SKIP_INTEGRITY_CHECK = 1;

    my $app = delete $AGS{'application'} || delete $AGS{'app'} || 'Notice';

    my $event_name = delete $AGS{'event_name'};

    my $prepend_domain_subject   = delete $AGS{'prepend_domain_subject'}   || !$AGS{'subject'};
    my $prepend_hostname_subject = delete $AGS{'prepend_hostname_subject'} || !$AGS{'subject'};

    my $subject             = delete $AGS{'subject'} || 'General Notice';
    my $to                  = delete $AGS{'to'};
    my $subaccount          = delete $AGS{'subaccount'};
    my $use_alternate_email = delete $AGS{'use_alternate_email'};
    my $domain              = delete $AGS{'domain'};
    my $email_ar            = delete $AGS{'email'};
    my $msg                 = delete $AGS{'message'}           || q{};
    my $plaintext_msg       = delete $AGS{'plaintext_message'} || q{};
    my $im_msg              = delete $AGS{'im_message'}        || q{};
    my $im_subject          = delete $AGS{'im_subject'}        || q{};
    my $quiet               = delete $AGS{'quiet'}             || $Whostmgr::UI::method && $Whostmgr::UI::method eq 'hide';    # PPI NO PARSE - Only will be set if loaded
    my $email_only          = delete $AGS{'email_only'};
    my $html_related        = delete $AGS{'html_related'};
    my $username            = delete $AGS{'username'};
    my $x_headers           = delete $AGS{'x_headers'};
    my $team_account        = delete $AGS{'team_account'};
    my $attach_files        = normalize_attach_files( delete $AGS{'attach_files'} );

    my $content_type = delete $AGS{'content-type'} || $Cpanel::iContact::Email::DEFAULT_CONTENT_TYPE;


    my $hostname = Cpanel::Hostname::gethostname();

    if ( defined $email_ar ) {
        if ( ( ref $email_ar ) eq 'ARRAY' ) {
            die "Invalid “email”: [@$email_ar]" if grep { tr<\r\n\f><> } @$email_ar;
        }
        else {
            die "“email” must be undef or an arrayref!";
        }
    }
    else {
        $email_ar = [];
    }

    $_ && s/[\r\n\f]*//g for ($subject);

    my $contactshash_ref;

    my $event_priority;

    if ( defined $to && length $to && ( !defined $subaccount || !length $subaccount ) ) {
        if ( $to ne 'root' && $to !~ m/\@/ ) {
            require Cpanel::Validate::Username::Core;

            $username = Cpanel::Validate::Username::Core::normalize($to);

            if ( !Cpanel::Config::HasCpUserFile::has_cpuser_file($username) ) {
                die "Nonexistent cPanel user specified in the “to” field: “$username”";
            }

            $contactshash_ref = _load_user_contactsettings($username);
        }

        elsif ( defined $team_account && $team_account ) {
            if ( $to =~ /\@/ && Cpanel::Validate::EmailCpanel::is_valid($to) ) {
                $contactshash_ref = _load_team_contactsettings($to);
            }
        }

        elsif ( $to =~ m{\@} && Cpanel::Validate::EmailCpanel::is_valid($to) ) {

            if ( !length $username ) {
                die "You must specify a cPanel user in the “username” field when the “to” field contains an “@”.";
            }

            $contactshash_ref = _load_email_contactsettings($to);

        }

        else {

            warn "Invalid “to”: $to";
            return;
        }

        $event_priority = $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'High'};
    }
    elsif ( length $subaccount ) {
        Cpanel::Validate::VirtualUsername::validate_or_die($subaccount);
        $contactshash_ref = _load_subaccount_contactsettings( $subaccount, $use_alternate_email );

        $event_priority = $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'High'};
    }

    else {
        $contactshash_ref = _loadcontactsettings();
    }

    if ( !$event_priority ) {
        my $importance_obj = Cpanel::iContact::EventImportance->new();

        if ( defined $event_name && length $event_name ) {
            $event_priority = $importance_obj->get_event_importance( $app, $event_name );
        }
        else {
            $event_priority = $importance_obj->get_application_importance($app);
        }
    }

    if (@$email_ar) {
        $contactshash_ref->{'CONTACTEMAIL'}{'contact'} = $email_ar;
        $contactshash_ref->{'CONTACTEMAIL'}{'level'} ||= $RECEIVES_NAME_TO_NUMBER{'All'};
        $contactshash_ref->{'CONTACTEMAIL'}{'send'} = 1;
    }

    my $from_domain = $hostname;

    if ($prepend_domain_subject) {

        if ( length $domain && Cpanel::Validate::Domain::Tiny::validdomainname( $domain, 1 ) ) {
            $from_domain = $domain;
        }
        elsif ( length $username ) {
            if ( $username =~ m{@} ) {
                $from_domain = ( split( m{@}, $username, 2 ) )[1];
            }
            else {
                require Cpanel::AcctUtils::Domain;
                $from_domain = Cpanel::AcctUtils::Domain::getdomain($username);
            }
        }

        $from_domain ||= $hostname;
    }

    $subject = "[$from_domain] $subject";
    if ($im_subject) {
        $im_subject = "[$from_domain] $im_subject";
    }

    my $default_email = qq{cpanel\@$from_domain};
    my $from          = $contactshash_ref->{'CONTACTEMAIL'}{'EMAILFROMNAME'} || $AGS{'from'} || qq{"cPanel on $from_domain"};
    my $replyto       = $contactshash_ref->{'CONTACTEMAIL'}{'EMAILREPLYTO'}  || $default_email;
    $replyto = "$from <$replyto>";
    $from    = "$from <$default_email>";

    if ( $ENV{'CPANEL_DEBUG_LEVEL'} && $ENV{'CPANEL_DEBUG_LEVEL'} >= 1 ) {
        print STDERR __PACKAGE__ . ": icontact app[$app\:\:$event_name] priority[$event_priority] from[$from] subject[$subject] msg[$msg] hostname[$hostname]\n";
    }

    return if !$event_priority;
    if ( $msg eq '' ) { $msg = $subject; }

    my @keys = sort keys %{$contactshash_ref};

    Cpanel::iContact::Providers::augment_icontact_providers( \%ICONTACT_PROVIDERS );

    my %provider_conf;
    foreach my $contact_type (@keys) {
        next if $contact_type eq 'mtime';

        if ( !exists( $ICONTACT_PROVIDERS{$contact_type} ) ) {
            delete $contactshash_ref->{$contact_type};
            next;
        }
        else {

            %provider_conf = Cpanel::iContact::Providers::get_settings() if !%provider_conf;
            if (   exists( $provider_conf{$contact_type} )
                && exists( $provider_conf{$contact_type}{'depends'} )
                && ref $provider_conf{$contact_type}{'depends'} eq 'ARRAY'
                && grep { !$contactshash_ref->{$contact_type}{$_} } @{ $provider_conf{$contact_type}{'depends'} } ) {
                delete $contactshash_ref->{$contact_type};
                next;
            }
        }

        next if defined( $contactshash_ref->{$contact_type}{'level'} ) && int( $contactshash_ref->{$contact_type}{'level'} ) < int($event_priority);

        next if ( @$email_ar || $email_only ) && $contact_type ne 'CONTACTEMAIL';

        $contactshash_ref->{$contact_type}{'send'} = 1;
    }

    my @log;
  CONTACT:
    foreach my $contact (@keys) {
        my @required = qw(contact);

        if ( $contact eq 'CONTACTUIN' ) {
            push @required, 'user', 'password';
        }

        for my $req (@required) {
            my $c = $contactshash_ref->{$contact};
            if (   ( ref $c->{$req} && !@{ $c->{$req} } )
                || !exists $c->{$req}
                || !defined $c->{$req}
                || !length $c->{$req} ) {
                delete $contactshash_ref->{$contact};
                next CONTACT;
            }
        }

        next if $quiet;

        my $type = Cpanel::StringFunc::Trim::begintrim( $contact, 'CONTACT' );
        if ( $contactshash_ref->{$contact}{'send'} ) {
            my $contacts_string = $contactshash_ref->{$contact}{'contact'};
            if ( 'ARRAY' eq ref($contacts_string) ) {

                $contacts_string = join( ', ', map { my $copy = $_; $copy =~ s/.{5}$/\*\*\*\*\*/; $copy; } @$contacts_string );
            }
            push @log, { 'app' => $app, 'contacts_string' => $contacts_string, 'type' => $type, 'eventimportance' => $event_priority };
        }
    }

    my $to_ar = $contactshash_ref->{'CONTACTEMAIL'}{'contact'};

    if ( 'ARRAY' ne ref $to_ar ) {
        $to_ar = [$to_ar];
    }

    my %email_args = (
        to           => $to_ar,
        'Reply-To'   => $replyto,
        subject      => $subject,
        from         => $from,
        html_related => $html_related,
        application  => $app,
        event_name   => $event_name,
        x_headers    => $x_headers,
    );

    my $main_content_ref = Cpanel::FHUtils::Tiny::is_a($msg) ? $msg : \$msg;

    if ( length $im_msg ) {
        $email_args{'im_message'} = $im_msg;
    }
    if ( length $im_subject ) {
        $email_args{'im_subject'} = $im_subject;
    }

    if ( $content_type =~ m<html> ) {
        $email_args{'html_body'} = $main_content_ref;

        if ( length $plaintext_msg ) {
            $email_args{'text_body'} = \$plaintext_msg;
        }
    }
    else {
        $email_args{'text_body'} = $main_content_ref;
    }

    try {
        $email_args{'history_file'} = _save_notification_to_log(
            'log_user'      => ( $username || 'root' ),
            'app'           => $app,
            'email_args_hr' => \%email_args,
        );
    }
    catch {
        $username //= '';
        Cpanel::Debug::log_info( "Failed to save notification for “$username” because of an error: " . Cpanel::Exception::get_string($_) );
    };

    return if !@$to_ar || !grep { $contactshash_ref->{$_}{'send'} } @keys;

    foreach my $log (@log) {

        my $log_level_name = $log->{'eventimportance'} == $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'High'} ? 'High' : $log->{'eventimportance'} == $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'Medium'} ? 'Medium' : $log->{'eventimportance'} == $Cpanel::iContact::EventImportance::NAME_TO_NUMBER{'Low'} ? 'Low' : 'Unknown';

        Cpanel::Debug::log_info( "$app\:\:" . ( $event_name || '' ) . " Notification => $log->{'contacts_string'} via $log->{'type'} [eventimportance => $log_level_name ($log->{'eventimportance'})]" );

    }

    my $notifications = _send_notifications( $contactshash_ref, \%email_args, $attach_files );

    return { 'notifications' => $notifications };
}

sub _send_notifications {
    my ( $contactshash_ref, $email_args_hr, $attach_files_ar ) = @_;

    my @NOTIFICATIONS;
    local $SIG{'PIPE'} = sub {
        print STDERR __PACKAGE__ . ": icontact broken pipe\n";
    };

    @LAST_ERRORS = ();
    foreach my $contact_type ( sort keys %{$contactshash_ref} ) {
        my $type = $contact_type;
        next if !( $type =~ s{^CONTACT}{} );
        next if $type !~ m{^[A-Za-z]+$};                          # only accept valid keys
        next if !$contactshash_ref->{$contact_type}{'send'};
        next if !$contactshash_ref->{$contact_type}{'contact'};

        my $to_ar = $contactshash_ref->{$contact_type}{'contact'};

        if ( 'ARRAY' ne ref $to_ar ) {
            $to_ar = [$to_ar];
        }
        $to_ar = [ map { "<$_>" } @$to_ar ] if $contact_type eq 'CONTACTEMAIL';
        $email_args_hr->{'to'} = $to_ar;

        my $module = $ICONTACT_PROVIDERS{$contact_type};

        push @NOTIFICATIONS, { 'type' => $type, 'contact' => $contactshash_ref->{$contact_type}{'contact'} };

        print STDERR __PACKAGE__ . ": icontact sending notification to $type.\n" if $ENV{'CPANEL_DEBUG_LEVEL'} && $ENV{'CPANEL_DEBUG_LEVEL'} >= 1;

        try {
            my $perl_module = "Cpanel::iContact::Provider::$module";
            Cpanel::LoadModule::Custom::load_perl_module($perl_module);
            my $obj = "$perl_module"->new(
                'contact'      => $contactshash_ref->{$contact_type},
                'args'         => $email_args_hr,
                'attach_files' => $attach_files_ar
            );
            $obj->send();
        }
        catch {
            my $err_str = "Failed to send notification of type “$type”: " . Cpanel::Exception::get_string($_);
            Cpanel::Debug::log_warn($err_str);

            push @LAST_ERRORS, $err_str;
        };
        delete $contactshash_ref->{$type}{'send'};
    }

    return \@NOTIFICATIONS;
}

sub reloadcontacts {
    %CONTACTS = %{ _loadcontactsettings(1) };
    return;
}

sub contact_descriptions {
    $INC{'Cpanel/Locale.pm'} or die("Cpanel::Locale is not loaded");    # DO NOT use L:MT in this file!!! This will cause a mess of undesireable dependencies.

    my $locale = shift or die("Not passed a \$locale object!");

    my $old_ctx = $locale->set_context_plain();

    my $two_gibibytes = 2 * ( 2**30 );


    my %contact_descriptions = (

        'Accounts' => {
            display_name => $locale->maketext('Digest Authentication Disabled Due to Account Rename'),
        },
        'Accounts::ChildDedistributionSuccess' => {
            display_name => $locale->maketext('Transfer Offloaded Functionality from a Child Node Success'),
        },
        'Accounts::ChildDedistributionFailure' => {
            display_name => $locale->maketext('Transfer Offloaded Functionality from a Child Node Failure'),
        },
        'Accounts::ChildDistributionSuccess' => {
            display_name => $locale->maketext('Offload Functionality to a Child Node Success'),
        },
        'Accounts::ChildDistributionFailure' => {
            display_name => $locale->maketext('Offload Functionality to a Child Node Failure'),
        },
        'Accounts::ChildRedistributionSuccess' => {
            display_name => $locale->maketext('Transfer Offloaded Functionality between Child Nodes Success'),
        },
        'Accounts::ChildRedistributionFailure' => {
            display_name => $locale->maketext('Transfer Offloaded Functionality between Child Nodes Failure'),
        },
        'AdminBin' => {
            display_name => $locale->maketext('Backup Failure'),
        },
        'Backup' => {
            display_name => $locale->maketext('[asis,cPanel] Backup'),
        },
        'Backup::Delayed' => {
            display_name => $locale->maketext('Backup Delayed'),
            help_text    => $locale->maketext('This option indicates that the backup process continues to run after 16 hours.'),
        },
        'Backup::Disabled' => {
            display_name => $locale->maketext('[asis,cPanel] Backup Destination Disabled'),
        },
        'Backup::Failure' => {
            display_name => $locale->maketext('Backup Failed To Finish'),
            help_text    => $locale->maketext('This option indicates that the backup failed.'),
        },
        'Backup::PartialFailure' => {
            display_name => $locale->maketext('Backup Finished With Partial Failure'),
            help_text    => $locale->maketext('This option indicates that the backup completed with errors.'),
        },
        'Backup::PreBackupNotice' => {
            display_name => $locale->maketext('Scheduled Backup Will Start Soon'),
        },
        'Backup::Success' => {
            display_name => $locale->maketext('Backup Successful'),    # case 192249 ensure the word backup comes first for sort order
        },
        'Backup::Transport' => {
            display_name => $locale->maketext('Backup Transport Error'),
            help_text    => $locale->maketext('This option indicates the system failed to transport the backup to the remote destination.'),
        },
        'BandwidthUsageExceeded' => {
            display_name => $locale->maketext('Bandwidth Limits'),
            help_text    => $locale->maketext(
                'This option will trigger no actions when the Tweak Setting “[_1]” has been disabled.',
                'Send bandwidth limit notification emails',    # Not translated
            ),
        },
        'ChangePassword' => {
            display_name => $locale->maketext('[asis,cPanel] Account Password'),
        },
        'Check::Biglog' => {
            display_name => $locale->maketext( 'System Log Approaches [format_bytes,_1]', $two_gibibytes ),
        },
        'Check::CpanelPackages' => {
            display_name => $locale->maketext('Altered Cpanel Packages Check'),
        },
        'Check::EximConfig' => {
            display_name => $locale->maketext('[asis,Exim] Update Failures'),
        },
        'Check::Hack' => {
            display_name => $locale->maketext('Root Compromise Checks'),
        },
        'Check::IP' => {
            display_name => $locale->maketext('[asis,IP] Address [asis,DNS] Check'),
        },
        'Check::ImmutableFiles' => {
            display_name => $locale->maketext('Update Failure Due to Immutable Files'),
        },
        'Check::InvalidDomains' => {
            display_name => $locale->maketext('Invalid Domains'),
        },
        'Check::MySQL' => {
            display_name => $locale->maketext('Corrupt Database Tables'),
        },
        'Check::MysqlConnection' => {
            display_name => $locale->maketext('Remote [asis,MySQL] Connection Failure'),
        },
        'Check::Oops' => {
            display_name => $locale->maketext('Kernel Crash Check'),
        },
        'Check::SSLCertExpired' => {
            display_name => $locale->maketext('Service [asis,SSL] Certificate Expiration'),
            help_text    => $locale->maketext("This option indicates that a system service SSL certificate is expired."),
        },
        'Check::SSLCertExpiresSoon' => {
            display_name => $locale->maketext('Service [asis,SSL] Certificate Expires Soon'),
            help_text    => $locale->maketext( "This option indicates that a system service SSL certificate will expire within [quant,_1,day,days].", 20 ),
        },
        'Check::Smart' => {
            display_name => $locale->maketext('Disk Integrity Check'),
        },
        'Check::ValidServerHostname' => {
            display_name => $locale->maketext('Invalid Hostname For Main [asis,IP] Address'),
        },
        'Check::UnmonitoredEnabledServices' => {
            display_name => $locale->maketext('Unmonitored Services'),
        },
        'Check::SecurityAdvisorStateChange' => {
            display_name => $locale->maketext('Security Advisor State Change'),
        },
        'Check::HostnameOwnedByUser' => {
            display_name => $locale->maketext('Hostname conflicts with a cPanel user account'),
        },
        'Check::Resolvers' => {
            display_name => $locale->maketext('[asis,DNS] Resolver Performance Issues'),
        },
        'Check::PdnsConf' => {
            display_name => $locale->maketext('Migrate [asis,PowerDNS] configuration upon upgrade'),
        },
        'Check::LocalConfTemplate' => {
            display_name => $locale->maketext('Local configuration template detected upon service upgrade'),
        },
        'CloudLinux' => {
            display_name => $locale->maketext('[asis,CloudLinux] License Detected'),
        },
        'Config' => {
            display_name => $locale->maketext('[asis,cPanel] Configuration Checks'),
        },
        'ConvertAddon' => {
            display_name => $locale->maketext('Convert Addon Domain to Account Notifications'),
        },
        'DAV::ChangeHostname' => {
            display_name => $locale->maketext('Hostname Change Notifications'),
        },
        'dbindex::Warn' => {
            display_name => $locale->maketext('[asis,dbindex] Cache File Out of Date'),
        },
        'DigestAuth' => {
            display_name => $locale->maketext('Forced Disable of Digest Auth'),
        },
        'DnsAdmin::ClusterError' => {
            display_name => $locale->maketext('[asis,DNS] Cluster Error'),
        },
        'DnsAdmin::UnreachablePeer' => {
            display_name => $locale->maketext('Lost Contact With [asis,DNS] Cluster'),
        },
        'DnsAdmin::DnssecError' => {
            display_name => $locale->maketext('[asis,DNSSEC] key synchronization failure'),
            help_text    => $locale->maketext("This option indicates that the system encountered an error during a [asis,DNSSEC] key synchronization on the [asis,cPanel] [asis,DNS] cluster."),
        },
        'Solr::Maintenance' => {
            display_name => $locale->maketext('[asis,Dovecot] [asis,Solr] maintenance task errors.'),
            help_text    => $locale->maketext("This option indicates that the system encountered an error during the [asis,Apache] [asis,Solr] maintenance task."),
        },
        'EasyApache' => {
            display_name => $locale->maketext('[asis,EasyApache] Configuration'),
        },
        'EasyApache::EA4_TemplateCheckUpdated' => {
            display_name => $locale->maketext('[asis,EasyApache 4] template updated'),
        },
        'EasyApache::EA4_ConflictRemove' => {
            display_name => $locale->maketext('[asis,EasyApache 4] conflict removed[comment,label text]'),
        },
        'Notice' => {
            display_name => $locale->maketext('Uncategorized'),
        },
        'Greylist' => {
            display_name => $locale->maketext('[asis,Greylist] System Changes'),
        },
        'ImportMyDNSdb::Failure' => {
            display_name => $locale->maketext('[asis,MyDNS] Zone Import Failure'),
        },
        'ImportMyDNSdb::InProgress' => {
            display_name => $locale->maketext('[asis,MyDNS] Zone Import In Progress'),
        },
        'ImportMyDNSdb::Success' => {
            display_name => $locale->maketext('[asis,MyDNS] Zone Import Successful'),
        },
        'InitialWebsite::Creation' => {
            display_name => $locale->maketext('Initial Website Creation'),
        },
        'Install::CheckcPHulkDB' => {
            display_name => $locale->maketext('[asis,cPHulk] Database Integrity Notices'),
        },
        'Install::PackageExtension' => {
            display_name => $locale->maketext('Package Extension Name Conflicts'),
        },
        'Install::FixcPHulkConf' => {
            display_name => $locale->maketext('[asis,cPHulk] Configuration Issues'),
        },
        'Install::CheckRemoteMySQLVersion' => {
            display_name => $locale->maketext('Remote [asis,MySQL] Server Notifications'),
        },
        'Logd' => {
            display_name => $locale->maketext('Bandwidth Data Processing Timeout'),
        },
        'Logger' => {
            display_name => $locale->maketext('Script Terminated Due to Deprecated Call'),
        },
        'Market' => {
            display_name => $locale->maketext('Notices concerning goods and services purchased via the [asis,cPanel] Market'),
        },
        'Market::SSLWebInstall' => {
            display_name => $locale->maketext('Installation of purchased [asis,SSL] certificates'),
            help_text    => $locale->maketext('This option indicates that an SSL certificate purchased via the SSL/TLS Wizard has been installed.'),
        },
        'Market::WHMPluginInstall' => {
            display_name => $locale->maketext('Installation of purchased [asis,WHM] Plugins.'),
        },

        'AutoSSL::CertificateExpiring' => {
            display_name => $locale->maketext('[asis,AutoSSL] cannot request a certificate because all of the website’s domains have failed [output,abbr,DCV,Domain Control Validation].'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] cannot request a certificate because all domains on the website have failed [output,abbr,DCV,Domain Control Validation].'), $locale->maketext('Manage AutoSSL') ),
        },
        'AutoSSL::CertificateExpiringCoverage' => {
            display_name => $locale->maketext('[asis,AutoSSL] has deferred normal certificate renewal because a domain on the current certificate has failed [output,abbr,DCV,Domain Control Validation].'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] defers certificate renewal because a domain on the current certificate has failed [output,abbr,DCV,Domain Control Validation].'), $locale->maketext('Manage AutoSSL') ),

        },
        'AutoSSL::CertificateRenewalCoverage' => {
            display_name => $locale->maketext('[asis,AutoSSL] will not secure new domains because a domain on the current certificate has failed [output,abbr,DCV,Domain Control Validation], and the certificate is not yet in the renewal period.'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] will not secure new domains because a domain on the current certificate has failed [output,abbr,DCV,Domain Control Validation].'), $locale->maketext('Manage AutoSSL') ),
        },
        'AutoSSL::CertificateInstalled' => {
            display_name => $locale->maketext('[asis,AutoSSL] has installed a certificate successfully.'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] has renewed a certificate successfully.'), $locale->maketext('Manage AutoSSL') ),
        },
        'AutoSSL::CertificateInstalledReducedCoverage' => {
            display_name => $locale->maketext('[asis,AutoSSL] has renewed a certificate, but the new certificate lacks at least one domain that the previous certificate secured.'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] has renewed a certificate and the new certificate lacks at least one domain that the previous certificate secured.'), $locale->maketext('Manage AutoSSL') ),
        },
        'AutoSSL::CertificateInstalledUncoveredDomains' => {
            display_name => $locale->maketext('[asis,AutoSSL] has renewed a certificate, but the new certificate lacks one or more of the website’s domains.'),
            help_text    => $locale->maketext( 'This setting takes effect only when “[_1]” is enabled in WHM’s “[_2]” interface.', $locale->maketext('Notify when [asis,AutoSSL] has renewed a certificate and the new certificate lacks one or more of the website’s domains.'), $locale->maketext('Manage AutoSSL') ),
        },
        'AutoSSL::DynamicDNSNewCertificate' => {
            display_name => $locale->maketext('[asis,AutoSSL] has provisioned a new certificate for a dynamic [asis,DNS] domain.'),
        },

        'SSL::CertificateExpiring' => {
            display_name => $locale->maketext('[asis,SSL] certificates expiring'),
            help_text    => $locale->maketext('This option indicates that a non-[asis,AutoSSL] certificate will expire soon.'),
        },
        'SSL::LinkedNodeCertificateExpiring' => {
            display_name => $locale->maketext('Hostname’s [asis,SSL] certificate expiring on a linked node'),
        },
        'SSL::CheckAllCertsWarnings' => {
            display_name => $locale->maketext('[asis,cPanel] service [asis,SSL] certificate warnings'),
            help_text    => $locale->maketext('This option indicates that a warning was generated while checking the [asis,cPanel] service [asis,SSL] certificates.'),
        },
        'Notice' => {
            display_name => $locale->maketext('Generic Notifications'),
        },
        'NSD' => {
            display_name => $locale->maketext('[asis,NSD] DNS Zones Corrupted'),
        },
        'OutdatedSoftware::Notify' => {
            display_name => $locale->maketext('Notifications of Outdated Software'),
        },
        'OverLoad::CpuWatch' => {
            display_name => $locale->maketext('Stalled Process Notifications'),
        },
        'OverLoad::LogRunner' => {
            display_name => $locale->maketext('Stalled Statistics and Bandwidth Process Notifications'),
        },
        'Quota::Broken' => {
            display_name => $locale->maketext('Filesystem quotas are currently broken.'),
        },
        'Quota::DiskWarning' => {
            display_name => $locale->maketext('User Disk Usage Warning'),
        },
        'Quota::RebootRequired' => {
            display_name => $locale->maketext('Reboot To Enable Filesystem Quotas Reminder'),
        },
        'Quota::SetupComplete' => {
            display_name => $locale->maketext('Filesystem Quotas Ready'),
        },
        'RPMVersions' => {
            display_name => $locale->maketext('Conversion of [asis,cpupdate.conf] settings to [asis,local.versions]'),
        },
        'StuckScript' => {
            display_name => $locale->maketext('Stuck Script'),
        },
        'SSHD::ConfigError' => {
            display_name => $locale->maketext('[asis,SSHD] Configuration Error'),
        },
        'TwoFactorAuth::UserEnable' => {
            display_name => $locale->maketext('User Enabled Two-Factor Authentication'),
        },
        'TwoFactorAuth::UserDisable' => {
            display_name => $locale->maketext('User Disabled Two-Factor Authentication'),
        },
        'Update::Blocker' => {
            display_name => $locale->maketext('Update Version Blocker'),
        },
        'Update::ServiceDeprecated' => {
            display_name => $locale->maketext('Update Blocker - Service Deprecation Notice'),
        },
        'Update::UpgradeRequired' => {
            display_name => $locale->maketext('Upgrade Required - Service Is Outdated'),
        },
        'Update::Now' => {
            display_name => $locale->maketext('Update Failures'),
        },
        'appconfig' => {
            display_name => $locale->maketext('[asis,AppConfig] Registration Notifications'),
        },
        'cPHulk' => {
            display_name => $locale->maketext('[asis,cPHulkd] Notifications'),
        },
        'cPHulk::BruteForce' => {
            display_name => $locale->maketext('[asis,cPHulkd] Brute Force'),
        },
        'cPHulk::Login' => {
            display_name => $locale->maketext('[asis,cPHulkd] Login Notifications'),
            help_text    => $locale->maketext('This option will trigger no actions when [asis,cPHulkd] is disabled.'),
        },
        'chkservd' => {
            display_name => $locale->maketext('Service failures ([asis,ChkServd])'),
        },
        'chkservd::DiskUsage' => {
            display_name => $locale->maketext('Disk Usage Warnings'),
        },
        'chkservd::Hang' => {
            display_name => $locale->maketext('Hung Service Checks'),
        },
        'MailServer::OOM' => {
            display_name => $locale->maketext('Mail Server Out of Memory'),
        },
        'Mail::ClientConfig' => {
            display_name => $locale->maketext('Email Client Configuration'),
        },
        'Mail::HourlyLimitExceeded' => {
            display_name => $locale->maketext('Maximum Hourly Emails Exceeded'),
        },
        'Mail::SendLimitExceeded' => {
            display_name => $locale->maketext('Outgoing Email Threshold Exceeded'),
        },
        'Mail::SpammersDetected' => {
            display_name => $locale->maketext('Large Amount of Outbound Email Detected'),
        },
        'chkservd::OOM' => {
            display_name => $locale->maketext('System Out of Memory'),
        },
        'cpbackup' => {
            display_name => $locale->maketext('[asis,cPanel] Backup (legacy notification)'),
        },
        'cpbackupdisabled' => {
            display_name => $locale->maketext('[asis,cPanel] Backup Destination Disabled (legacy notification)'),
        },
        'iContact' => {
            display_name => $locale->maketext('Instant Message Failure'),
        },
        'installbandwidth' => {
            display_name => $locale->maketext('Bandwidth File Conversion Disk Space Failure'),
        },
        'killacct' => {
            display_name => $locale->maketext('Account Removal'),
        },
        'parkadmin' => {
            display_name => $locale->maketext('Notification of New Addon Domains'),
        },
        'queueprocd' => {
            display_name => $locale->maketext('[asis,queueprocd] Critical Errors'),
        },
        'rpm.versions' => {
            display_name => $locale->maketext('Conversion of [asis,cpupdate.conf] Settings to [asis,local.versions] (legacy notification)'),
        },
        'suspendacct' => {
            display_name => $locale->maketext('Account Suspensions'),
        },
        'sysup' => {
            display_name => $locale->maketext('System Update Failures'),
        },
        'unsuspendacct' => {
            display_name => $locale->maketext('Account Unsuspensions'),
        },
        'upacct' => {
            display_name => $locale->maketext('Account Upgrades/Downgrades'),
        },
        'upcp' => {
            display_name => $locale->maketext('[asis,cPanel] Update Failures'),
        },
        'wwwacct' => {
            display_name => $locale->maketext('Account Creation'),
        },
        'Stats' => {
            display_name => $locale->maketext('Stats and Bandwidth Processing Errors'),
        },
        'PHPFPM::AccountOverquota' => {
            display_name => $locale->maketext('[asis,PHP-FPM] Account is over quota.'),
        },
        'Update::EndOfLife' => {
            display_name => $locale->maketext('[asis,cPanel] [output,amp] [asis,WHM] End of Life Notice'),
        },
        'Deprecated::API1' => {
            display_name => $locale->maketext('Deprecated API1 Calls List'),
        },
        'Deprecated::EA3RPMs' => {
            display_name => $locale->maketext('Legacy EA3 RPMs Installed List'),
        },
        'DemoMode::MailChildNodeExists' => {
            display_name => $locale->maketext('Accounts with demo mode restrictions enabled and mail distributed to a child node.'),
        },
        'Application' => {
            display_name => $locale->maketext('Uncategorized Notifications'),
        },
    );

    Cpanel::LoadModule::load_perl_module('Cpanel::Component');
    $optional_components ||= Cpanel::Component->init();
    my $additional_descriptions = $optional_components->contact_descriptions( 'whm', $locale );
    foreach my $system_name ( keys %$additional_descriptions ) {
        next if $contact_descriptions{$system_name};    # do not let plugins overwrite builtins
        $contact_descriptions{$system_name} = $additional_descriptions->{$system_name};
    }

    $locale->set_context($old_ctx);

    return %contact_descriptions;
}

sub _load_user_contactsettings {
    my $user    = shift;
    my $homedir = Cpanel::PwCache::gethomedir($user);
    my ( $uid, $gid ) = ( Cpanel::PwCache::getpwnam_noshadow($user) )[ 2, 3 ];
    my %USER_CONTACTS;
    return {} if !$uid;

    my $cpuser_data = Cpanel::Config::LoadCpUserFile::loadcpuserfile($user);

    $USER_CONTACTS{'CONTACTEMAIL'}{'level'}   = $RECEIVES_NAME_TO_NUMBER{'All'};
    $USER_CONTACTS{'CONTACTEMAIL'}{'contact'} = $cpuser_data->contact_emails_ar();

    if ( $cpuser_data->{'PUSHBULLET_ACCESS_TOKEN'} ) {
        $USER_CONTACTS{'CONTACTPUSHBULLET'}{'level'}   = $RECEIVES_NAME_TO_NUMBER{'All'};
        $USER_CONTACTS{'CONTACTPUSHBULLET'}{'send'}    = 1;
        $USER_CONTACTS{'CONTACTPUSHBULLET'}{'contact'} = [ $cpuser_data->{'PUSHBULLET_ACCESS_TOKEN'} ];
    }

    return \%USER_CONTACTS;
}

sub _load_email_contactsettings {
    my ($email) = @_;

    my %USER_CONTACTS = (
        'CONTACTEMAIL' => {
            'level'   => $RECEIVES_NAME_TO_NUMBER{'All'},
            'contact' => [$email],
            'send'    => 1,
        }
    );

    my ( $email_user, $domain ) = split( m{@}, $email, 2 );
    if ( Cpanel::Validate::FilesystemNodeName::is_valid($email_user) && Cpanel::Validate::FilesystemNodeName::is_valid($domain) ) {
        my $webmail_accounts_cpanel_user;
        try {
            require Cpanel::AcctUtils::Lookup;
            $webmail_accounts_cpanel_user = Cpanel::AcctUtils::Lookup::get_system_user($email);
        };
        if ($webmail_accounts_cpanel_user) {
            require Cpanel::AccessIds::ReducedPrivileges;
            require Cpanel::DataStore;
            my $homedir   = Cpanel::PwCache::gethomedir($webmail_accounts_cpanel_user);
            my $base_path = "$homedir/etc/$domain/$email_user";
            my $cf;

            Cpanel::AccessIds::ReducedPrivileges::call_as_user(
                $webmail_accounts_cpanel_user,
                sub {
                    $cf = Cpanel::DataStore::fetch_ref( $base_path . '/.cpanel/contactinfo' );
                }
            );

            if ($cf) {

                if ( $cf->{'pushbullet_access_token'} ) {
                    $USER_CONTACTS{'CONTACTPUSHBULLET'}{'level'}   = $RECEIVES_NAME_TO_NUMBER{'All'};
                    $USER_CONTACTS{'CONTACTPUSHBULLET'}{'send'}    = 1;
                    $USER_CONTACTS{'CONTACTPUSHBULLET'}{'contact'} = [ $cf->{'pushbullet_access_token'} ];
                }
                foreach my $email_key (qw(email second_email)) {
                    if ( $cf->{$email_key} && grep { $cf->{$email_key} ne $_ } @{ $USER_CONTACTS{'CONTACTEMAIL'}{'contact'} } ) {
                        push @{ $USER_CONTACTS{'CONTACTEMAIL'}{'contact'} }, $cf->{$email_key};
                    }
                }

            }
        }
    }

    return \%USER_CONTACTS;
}

sub _load_team_contactsettings {
    my ($email) = @_;
    my %USER_CONTACTS = (
        'CONTACTEMAIL' => {
            'level'   => $RECEIVES_NAME_TO_NUMBER{'All'},
            'contact' => [$email],
            'send'    => 1,
        }
    );
    return \%USER_CONTACTS;
}

sub _load_subaccount_contactsettings {
    my ( $full_username, $use_alternate_email ) = @_;
    my ( $username, $domain ) = split /\@/, $full_username, 2;
    my %SUBACCOUNT_CONTACTS;

    require Cpanel::AcctUtils::Lookup;
    my $owner_of_subaccount = Cpanel::AcctUtils::Lookup::get_system_user($full_username);
    if ($owner_of_subaccount) {

        require Cpanel::AccessIds;
        my (@contact_emails) = Cpanel::AccessIds::do_as_user(    # do not use call_as_user; only do_as_user
            $owner_of_subaccount,
            sub {
                my @email_addresses;
                {
                    eval 'require Cpanel::UserManager::Storage';    ## no critic qw(BuiltinFunctions::ProhibitStringyEval) -- hide from perlpkg

                    my $alternate_email;
                    my $subaccounts_local_email_address;
                    {
                        my $dbh = Cpanel::UserManager::Storage::dbh();

                        my $annotation_list  = Cpanel::UserManager::Storage::list_annotations( full_username => $full_username, 'dbh' => $dbh );
                        my $email_annotation = $annotation_list->lookup_by( $full_username, 'email' );
                        if ( $email_annotation && $email_annotation->merged ) {
                            $subaccounts_local_email_address = $full_username;
                        }

                        my $record_obj = Cpanel::UserManager::Storage::lookup_user(
                            username => $username,
                            domain   => $domain,
                            dbh      => $dbh
                        );
                        $alternate_email = $record_obj->alternate_email;
                    }

                    if ( $use_alternate_email || !$subaccounts_local_email_address ) {
                        push @email_addresses, $alternate_email;
                    }
                    else {
                        push @email_addresses, $subaccounts_local_email_address;
                    }

                    require Cpanel;

                    Cpanel::LoadModule::load_perl_module('Cpanel::CustInfo::Impl');

                    Cpanel::initcp();
                    my $results = Cpanel::CustInfo::Impl::fetch_addresses(
                        appname    => $Cpanel::appname || $Cpanel::appname,    # avoid warning used once
                        cpuser     => $Cpanel::user    || $Cpanel::user,       # avoid warning used once
                        cphomedir  => $Cpanel::homedir,
                        username   => $full_username,
                        no_default => 1,
                    );
                    foreach my $result (@$results) {
                        if ( $result->{name} eq 'email' ) {
                            push @email_addresses, $result->{value};
                        }
                        if ( $result->{name} eq 'second_email' ) {
                            push @email_addresses, $result->{value};
                        }
                    }
                }
                return @email_addresses;
            }
        );

        @contact_emails = grep { $_ } @contact_emails;
        @contact_emails = Cpanel::ArrayFunc::Uniq::uniq(@contact_emails);

        if (@contact_emails) {
            $SUBACCOUNT_CONTACTS{'CONTACTEMAIL'} = {
                'contact' => \@contact_emails,
                'send'    => 1,
                'level'   => $RECEIVES_NAME_TO_NUMBER{'All'},
            };
        }
    }
    if ( !%SUBACCOUNT_CONTACTS ) {
        die 'No contact email address could be found for ' . $full_username . "\n";
    }
    return \%SUBACCOUNT_CONTACTS;
}

sub _loadcontactsettings {
    require Cpanel::ContactInfo::Email;
    my $reload = shift || 0;

    if ( !$reload && exists( $CONTACTS{'mtime'} ) ) {

        my $mtime;
        foreach my $file ( keys %{ $CONTACTS{'mtime'} } ) {
            $mtime = ( stat($file) )[9];
            if ( !$mtime || $CONTACTS{'mtime'}{$file} != $mtime ) {
                $reload = 1;
                last;
            }
        }
        return \%CONTACTS;
    }

    my $wwwacct_ref = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
    foreach my $key ( keys %{$wwwacct_ref} ) {
        next if !length $wwwacct_ref->{$key};

        if ( $key =~ m/^CONTACT([A-Z]*)/ ) {
            my $type = $1;
            if ( $type eq 'EMAIL' || $type eq 'PAGER' ) {
                $CONTACTS{$key}{'contact'} = [ grep( !m/^\s*$/, Cpanel::ContactInfo::Email::split_multi_email_string( $wwwacct_ref->{$key} ) ) ];
            }
            else {
                $CONTACTS{$key}{'contact'} = [ grep( !m/^\s*$/, split( /\s*,\s*/, $wwwacct_ref->{$key} ) ) ];
            }
        }
    }

    Cpanel::iContact::Providers::augment_contact_settings( $wwwacct_ref, \%CONTACTS );

    if ( length $wwwacct_ref->{'ICQPASS'} && length $wwwacct_ref->{'ICQUSER'} ) {
        $CONTACTS{'CONTACTUIN'}{'password'} = $wwwacct_ref->{'ICQPASS'};
        $CONTACTS{'CONTACTUIN'}{'user'}     = $wwwacct_ref->{'ICQUSER'};
    }
    foreach (qw{EMAILREPLYTO EMAILFROMNAME}) {
        $CONTACTS{'CONTACTEMAIL'}{$_} = $wwwacct_ref->{$_} if length $wwwacct_ref->{$_};
    }

    augment_contacts_with_default_levels( \%CONTACTS );

    my $clevels = clevels_file();
    $CONTACTS{'mtime'}{$clevels} = ( stat($clevels) )[9];
    if ( open my $clevels_fh, '<', $clevels ) {
        while (<$clevels_fh>) {
            chomp;
            s/\r//g;
            if (m/^(CONTACT\S+)\s+(\S+)/) {
                my $contacttype = $1;
                my $level       = $2;
                next if ( $level eq '' );
                $CONTACTS{$contacttype}{'level'} = $level;
            }
        }
        close $clevels_fh;
    }

    my $hostname   = Cpanel::Hostname::gethostname();
    my $root_email = 'root@' . $hostname;

    $CONTACTS{'CONTACTEMAIL'}{'contact'} ||= [$root_email];

    return \%CONTACTS;
}

sub augment_contacts_with_default_levels {
    my ($contacts_ref) = @_;

    $contacts_ref->{'CONTACTEMAIL'}{'level'}      = $RECEIVES_NAME_TO_NUMBER{'All'};
    $contacts_ref->{'CONTACTPAGER'}{'level'}      = $RECEIVES_NAME_TO_NUMBER{'HighOnly'};
    $contacts_ref->{'CONTACTPUSHBULLET'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'HighAndMediumOnly'};
    $contacts_ref->{'CONTACTUIN'}{'level'}        = $RECEIVES_NAME_TO_NUMBER{'HighAndMediumOnly'};

    Cpanel::iContact::Providers::augment_contacts_with_default_levels($contacts_ref);
    return 1;
}

sub _reset_contacts_cache {
    return %CONTACTS = ();
}

sub normalize_attach_files {
    my ($attach_files) = @_;

    $attach_files ||= [];

    if ( ref $attach_files ne 'ARRAY' ) {
        die "'attach_files', if given, must be an arrayref, not “$attach_files”!";
    }

    return $attach_files;
}

sub _save_notification_to_log {
    my (%OPTS) = @_;

    require Cpanel::iContact::History;

    my $log_user      = $OPTS{'log_user'};
    my $email_args_hr = $OPTS{'email_args_hr'};
    my $app           = $OPTS{'app'};
    my $RESERVED      = '';

    my $datastore_obj;

    if ( $log_user !~ /@/ ) {
        $datastore_obj = Cpanel::iContact::History::get_user_contact_history( 'user' => $log_user );
    }
    else {
        my ( $virtual_user, $domain ) = split( '@', $log_user, 2 );
        my $system_user = Cpanel::AcctUtils::DomainOwner::Tiny::getdomainowner($domain);
        $datastore_obj = Cpanel::iContact::History::get_virtual_user_contact_history( 'user' => $system_user, 'virtual_user' => $virtual_user, 'domain' => $domain, 'service' => 'mail' );
    }

    $datastore_obj->purge_expired();

    my $filesys_safe_subject_header = $email_args_hr->{'subject'};
    $filesys_safe_subject_header =~ s{/}{_}g;
    $filesys_safe_subject_header =~ s{\0}{ }g;
    $filesys_safe_subject_header = substr( $filesys_safe_subject_header, 0, 200 );

    my $target = $datastore_obj->get_entry_target(
        'time'   => time(),
        'fields' => [ $app, $RESERVED, $RESERVED, $filesys_safe_subject_header ],
        'type'   => 'eml'
    );

    Cpanel::iContact::Email::write_email_to_fh( $target->{'fh'}, %{$email_args_hr} );

    return $target->{'path'};
}

1;

} # --- END Cpanel/iContact.pm


{ # --- BEGIN Cpanel/RPM/Versions/Directory.pm
package Cpanel::RPM::Versions::Directory;


use cPstrict;

use Carp;

use Try::Tiny;

# use Cpanel::Config::LoadCpConf        ();
# use Cpanel::LoadModule                ();
# use Cpanel::RPM::Versions::File::YAML ();
# use Cpanel::SafeDir::MK               ();
# use Cpanel::Update::Config            ();
# use Cpanel::Update::Logger            ();
# use Cpanel::Services::Enabled         ();
# use Cpanel::MariaDB                   ();
# use Cpanel::MysqlUtils::Versions      ();

our $RPM_VERSIONS_DIRECTORY = '/var/cpanel/rpm.versions.d';

sub new ( $class, $args = do { {} } ) {
    my $self = $class->init($args);

    bless $self, $class;

    if ( !-d $self->{'versions_directory'} ) {
        Cpanel::SafeDir::MK::safemkdir( $self->{'versions_directory'}, '0700', 2 );
    }

    $self->{'bootstrapping'} = -e '/usr/local/cpanel/cpanel' ? 0 : 1;

    $self->load_local_file();
    $self->load_directory();

    $self->set_legacy() unless ( $args->{'dont_set_legacy'} );

    $self->load_cpupdate_conf();

    $self->disable_mysql_deps_for_cpanel_bootstrap();

    return $self;
}

sub _need_object ($self) {
    $self->isa(__PACKAGE__) or do {
        my @caller = caller(1);
        die("You must call $caller[3] as a method at $caller[1] line $caller[2].\n");
    };
    return;
}

sub init ( $class, $args ) {


    return {
        'logger'             => $args->{'logger'}        || Cpanel::Update::Logger->new(),
        'versions_directory' => $args->{'directory'}     || $RPM_VERSIONS_DIRECTORY,
        'local_file_name'    => $args->{'local_file'}    || 'local.versions',
        'updisabledir'       => $args->{'updisabledir'}  || '/etc',
        'mysql_targets'      => $args->{'mysql_targets'} || [ Cpanel::MysqlUtils::Versions::get_rpm_target_names( Cpanel::MysqlUtils::Versions::get_installable_versions() ) ],
        'versions_store'     => {},
        'cpconfig'           => scalar Cpanel::Config::LoadCpConf::loadcpconf(),
    };
}

sub cpconfig ($self) {
    _need_object($self);
    return $self->{'cpconfig'};
}

sub versions_directory ($self) {
    _need_object($self);
    return $self->{'versions_directory'};
}

sub local_file_name ($self) {
    _need_object($self);
    return $self->{'local_file_name'};
}

sub set ( $self, $args = undef ) {
    _need_object($self);

    $self->{'local_file_data'}->set($args);

    return;
}

sub delete ( $self, $args = undef ) {
    _need_object($self);

    $self->{'local_file_data'}->delete($args);

    return;
}

sub save ($self) {
    _need_object($self);

    $self->{'local_file_data'}->save();

    my $updisablefiles = $self->{'updisablefiles'} || [];

    foreach my $file (@$updisablefiles) {
        unlink $file;
    }

    if ( $self->{'changed'} ) {
        Cpanel::Update::Config::save( $self->{'update_config'} );
    }

    return;
}

sub fetch ( $self, $args ) {
    _need_object($self);

    my $section = $args->{'section'};
    my $key     = $args->{'key'};

    if ($key) {    # Supply from local file if present
        if ( !$self->{'local_file_data'} ) {
            return $self->{'versions_store'}{$section}{$key};
        }

        my $in_local_file = $self->{'local_file_data'}->fetch( { 'section' => $section, 'key' => $key } );
        if ($in_local_file) {    # The key exists in the local file.
            return $in_local_file;
        }
        else {                   # Supply from vendor aggregation
            return $self->{'versions_store'}{$section}{$key};
        }
    }
    else {

        my %dir_section = %{ $self->{'versions_store'}{$section} || {} };

        return \%dir_section if ( !$self->{'local_file_data'} );

        my $local_section = $self->{'local_file_data'}->fetch( { 'section' => $section } );

        foreach my $key ( keys %{$local_section} ) {
            $dir_section{$key} = $local_section->{$key};
        }

        return \%dir_section;
    }
}

sub load_local_file ($self) {
    _need_object($self);

    my $local_file = $self->{'versions_directory'} . '/' . $self->local_file_name();
    $self->{'local_file_data'} = Cpanel::RPM::Versions::File::YAML->new( { file => $local_file } );

    my $data = $self->{'local_file_data'}->{'data'}->{'target_settings'};
    return unless $data && ref $data eq 'HASH';    # Nothing to do.
    foreach my $key ( sort keys %$data ) {
        my $value = $data->{$key};
        next if $value =~ m/^((un)?installed|unmanaged)$/;    # Nothing to clean up.
        delete $data->{$key};
        if ( $0 =~ m/update_local_rpm_versions/ ) {           # scripts/update_local_rpm_versions will actually save this change so our message needs to be different.
            $self->{'logger'}->warning("Unexpected value '$value' for target_settings.$key in $local_file. This is being fixed by removing the setting.");
        }
        else {                                                # Any reader will only remove the key for the life of this process. So we need to warn them and tell them how to fix it.
            $self->{'logger'}->warning("Unexpected value '$value' for target_settings.$key in $local_file. Ignoring this key.");
            $self->{'logger'}->warning("You can correct this by running: /usr/local/cpanel/scripts/update_local_rpm_versions --del target_settings.$key");
        }
    }

    return;
}

sub load_directory ($self) {
    _need_object($self);

    my $dir_fh;
    opendir( $dir_fh, $self->versions_directory() ) or do {
        my $message = 'Unable to load files in directory: ' . $self->versions_directory();
        $self->{'logger'}->fatal($message);
        die($message);
    };
    my @versions_files = map { $self->versions_directory() . '/' . $_ }
      grep { $self->local_file_name() ne $_ }
      grep { /\.versions$/ }
      grep { !/^\.\.?$/ } readdir($dir_fh);

    foreach my $file (@versions_files) {
        my $data;
        eval { $data = Cpanel::RPM::Versions::File::YAML->new( { file => $file } ) };

        if ( !$data or ref $data ne 'Cpanel::RPM::Versions::File::YAML' ) {
            $self->{'logger'}->error("$@");
            next;
        }

        $data = $data->{'data'};

        foreach my $key ( sort keys %{ $data->{'target_settings'} || {} } ) {
            my $value = $data->{'target_settings'}->{$key};
            next if $value =~ m/^((un)?installed|unmanaged)$/;
            delete $data->{'target_settings'}->{$key};
            $self->{'logger'}->warning("Unexpected value '$value' for target_settings.$key in $file. Ignoring this key.");
        }

        foreach my $section ( keys %{$data} ) {
            next if ( $section eq 'file_format' );    # All files have a file format key. This isn't a conflict.
            foreach my $key ( keys %{ $data->{$section} } ) {
                my $in_local_file = $self->{'local_file_data'}->fetch( { 'section' => $section, 'key' => $key } );
                if ( defined $self->{'versions_store'}{$section}{$key} && !$in_local_file ) {    # Not in the local file
                    if ( defined $data->{$section}{$key} ) {
                        if ( $section eq 'target_settings' && ( $self->{'versions_store'}{$section}{$key} eq 'uninstalled' && $data->{$section}{$key} eq 'installed' )
                            || ( $self->{'versions_store'}{$section}{$key} eq 'installed' && $data->{$section}{$key} eq 'uninstalled' ) ) {
                            my $message = "Conflict in section $section key $key [versions_store=$self->{'versions_store'}{$section}{$key}] [value=$data->{$section}{$key}] [file=$file]: installed will be used";
                            $self->{'logger'}->info($message);
                            $self->{'versions_store'}{$section}{$key} = 'installed';
                            next;
                        }
                        else {
                            my $message = "Conflict in section $section key $key [versions_store=$self->{'versions_store'}{$section}{$key}] [value=$data->{$section}{$key}] [file=$file]";
                            $self->{'logger'}->fatal($message);
                            die $message;
                        }
                    }
                }
                $self->{'versions_store'}{$section}{$key} = $data->{$section}{$key};
            }
        }
    }
    return;
}

sub disable_mysql_deps_for_cpanel_bootstrap ($self) {
    _need_object($self);

    return undef if !$self->{'bootstrapping'};

    my $versions_store_targets = $self->{'versions_store'}{'target_settings'};
    return 0 unless ( grep { m/^maria/i && $versions_store_targets->{$_} && $versions_store_targets->{$_} eq 'installed' } @{ $self->{'mysql_targets'} } );

    my @targets_which_want_mysql_first = qw/mydns/;
    foreach my $target (@targets_which_want_mysql_first) {
        $versions_store_targets->{$target} = 'unmanaged' if ( !$versions_store_targets->{$target} or $versions_store_targets->{$target} eq 'installed' );
    }

    return 1;
}

sub set_legacy ($self) {
    _need_object($self);

    $self->set_dns_targets();
    $self->set_ftp_targets();
    $self->set_mysql_targets();

    return;
}

sub set_mysql_targets ($self) {
    _need_object($self);

    my $enabled_target = $self->cpconfig()->{'mysql-version'} || '';
    $enabled_target =~ s/\.//g;
    $enabled_target = ( Cpanel::MariaDB::version_is_mariadb($enabled_target) ? 'MariaDB' : 'MySQL' ) . $enabled_target;

    foreach my $target ( @{ $self->{'mysql_targets'} } ) {

        my $local_setting = $self->fetch( { 'section' => 'target_settings', 'key' => $target } );

        if ( $enabled_target ne $target && $local_setting ) {
            $local_setting =~ s/\binstalled\b/unmanaged/;
        }

        $self->{'versions_store'}{'target_settings'}{$target} = $local_setting || ( $enabled_target eq $target ? 'installed' : 'uninstalled' );
    }

    return;
}

sub set_dns_targets ($self) {
    _need_object($self);

    my $enabled_target = ( Cpanel::Services::Enabled::is_enabled('dns') && !$self->{'bootstrapping'} ) ? ( $self->cpconfig()->{'local_nameserver_type'} || 'bind' ) : 'none';

    foreach my $target (qw/powerdns mydns nsd/) {

        my $local_setting = $self->fetch( { 'section' => 'target_settings', 'key' => $target } );

        $self->{'versions_store'}{'target_settings'}{$target} = $local_setting || ( $enabled_target eq $target ? 'installed' : 'uninstalled' );
    }

    return 1;
}

sub set_ftp_targets ($self) {
    _need_object($self);

    my $enabled_target = Cpanel::Services::Enabled::is_enabled('ftp') ? ( $self->cpconfig()->{'ftpserver'} || '' ) : 'none';

    foreach my $target (qw/pure-ftpd proftpd/) {

        my $local_setting = $self->fetch( { 'section' => 'target_settings', 'key' => $target } );

        $self->{'versions_store'}{'target_settings'}{$target} = $local_setting || ( $enabled_target eq $target ? 'installed' : 'uninstalled' );
    }

    return 1;
}

sub load_cpupdate_conf ($self) {
    _need_object($self);

    my @local_keys;

    my $config = Cpanel::Update::Config::load();

    my %update_is_disabled = map { tr/A-Z/a-z/; $_ =~ s/up$//; $_ => 1 } grep { $config->{$_} eq 'never' } keys %$config;

    $self->{'updisablefiles'} = [];

    foreach my $service (qw/ftp mydns mysql nameserver nsd exim/) {
        my $file = "$self->{'updisabledir'}/${service}updisable";
        if ( -e $file ) {
            $update_is_disabled{$service} = 1;
            push @{ $self->{'updisablefiles'} }, $file;
            $self->{'changed'} = 1;
        }
    }

    for my $target (qw/nsd mydns/) {
        push @local_keys, $target if ( ( $update_is_disabled{$target} || $update_is_disabled{'nameserver'} ) && $self->cpconfig()->{'local_nameserver_type'} eq $target );
    }

    push @local_keys, 'exim' if ( $update_is_disabled{'exim'} );

    my $ftp_server = $self->cpconfig()->{'ftpserver'};
    push @local_keys, $ftp_server if ( Cpanel::Services::Enabled::is_enabled('ftp') && $update_is_disabled{'ftp'} );

    if ( $update_is_disabled{'mysql'} ) {
        my $version = $self->cpconfig()->{'mysql-version'};
        $version =~ s/\.//;
        push @local_keys, "MySQL$version";
    }

    foreach my $key (@local_keys) {
        $self->set( { 'section' => 'target_settings', 'key' => $key, 'value' => 'unmanaged' } );
    }

    if (@local_keys) {
        my $message = "The following changes were made to your $self->{'versions_directory'}/local.versions file automatically due to =never settings in /etc/cpupdate.conf or *updisable touchfiles in /etc:\n\n";
        $message .= "$_: unmanaged\n" foreach (@local_keys);
        $message .= "\n cpupdate.conf is no longer the place to disable updates, nor is creating *updisable touchfiles in /etc an acceptable way to disable updates.\n";
        $message .= "If this was not your intention, you should remove this from local.versions.\n\n";
        $message .= "Example: In order to re-enable updates for nsd you would do: /usr/local/cpanel/scripts/update_local_rpm_versions -del target_settings.nsd\n\n";
        $message .= "Please refer to our documentation at https://go.cpanel.net/rpmversions for more information.\n";

        $self->{'logger'}->warning("Sending notification about changed settings in cpupdate.conf:\n\n$message\n");

        if ( try( sub { Cpanel::LoadModule::load_perl_module("Cpanel::iContact::Class::RPMVersions::Notify") } ) ) {
            require Cpanel::Notify;
            Cpanel::Notify::notification_class(
                'class'            => 'RPMVersions::Notify',
                'application'      => 'RPMVersions::Notify',
                'constructor_args' => [
                    'origin'             => 'RPMVersions::Directory',
                    'versions_directory' => $self->{'versions_directory'},
                    'local_keys'         => \@local_keys
                ]
            );
        }
        else {
            require Cpanel::iContact;
            Cpanel::iContact::icontact(
                'application' => 'rpm.versions',
                'subject'     => 'cpupdate.conf settings converted to local.versions',
                'message'     => $message,
            );
        }

    }

    foreach my $key ( keys %$config ) {
        next if ( $key =~ m/^(CPANEL|RPMUP|SARULESUP|UPDATES|STAGING_DIR)$/ );
        $self->{'changed'} = 1;
        delete $config->{$key};
    }

    $self->{'update_config'} = $config;

    return 1;
}

sub config_changed ($self) {
    _need_object($self);

    return $self->{'changed'} ? 1 : 0;
}

1;

} # --- END Cpanel/RPM/Versions/Directory.pm


{ # --- BEGIN Cpanel/Fuser.pm
package Cpanel::Fuser;



use cPstrict;

sub check (@files) {
    my @procs = running_processes();

    my %fuser_data;
    foreach my $pid ( sort @procs ) {
        my @open_files = proc_has_open_files( $pid, @files ) or next;
        foreach my $file (@open_files) {
            $fuser_data{$file} ||= [];
            push $fuser_data{$file}->@*, $pid;
        }
    }
    return %fuser_data;
}


sub running_processes () {
    opendir( my $fh, '/proc' ) or return;
    return grep { m{^[0-9]+$} } readdir $fh;
}


sub proc_has_open_files ( $pid, @files_to_find ) {

    opendir( my $dfh, "/proc/$pid/fd" ) or return;
    my @fds = grep { m{^[0-9]+$} } readdir $dfh;
    my %files_found;
    foreach my $fd (@fds) {
        my $file_open = readlink("/proc/$pid/fd/$fd") or next;
        $files_found{$file_open}++ if grep { $file_open eq $_ } @files_to_find;
    }

    my @files = sort keys %files_found;

    return @files;
}

1;

} # --- END Cpanel/Fuser.pm


{ # --- BEGIN Cpanel/CPAN/IO/Callback/Write.pm
package Cpanel::CPAN::IO::Callback::Write;



use strict;

use Symbol ();

sub new {
    my ( $class, $callback ) = @_;

    my $self = bless Symbol::gensym(), ref($class) || $class;
    tie *$self, $self;

    *$self->{'_callback'} = $callback;

    return $self;
}

sub TIEHANDLE {
    return $_[0] if ref( $_[0] );
    my $class = shift;
    my $self = bless Symbol::gensym(), $class;
    return $self;
}

sub fileno {
    return -1;    #This is what fileno() on a scalar ref filehandle returns.
}

sub close { }

sub write {
    my $self = shift;

    my $slen = length( $_[0] );
    my $len  = $slen;
    my $off  = 0;
    if ( @_ > 1 ) {
        my $xlen = defined $_[1] ? $_[1] : 0;
        $len = $xlen if $xlen < $len;
        die "Negative length" if $len < 0;
        if ( @_ > 2 ) {
            $off = $_[2] || 0;
            if ( $off >= $slen and $off > 0 and ( $] < 5.011 or $off > $slen ) ) {
                die "Offset outside string";
            }
            if ( $off < 0 ) {
                $off += $slen;
                die "Offset outside string" if $off < 0;
            }
            my $rem = $slen - $off;
            $len = $rem if $rem < $len;
        }
    }
    if ($len) {
        *$self->{'_callback'}( substr $_[0], $off, $len );
    }
    return $len;
}

sub print {
    my $self = shift;

    my $result;
    if ( defined $\ ) {
        if ( scalar @_ == 1 ) {
            $result = $self->WRITE( $_[0] . $\ );
        }
        elsif ( defined $, ) {
            $result = $self->WRITE( join( $,, @_ ) . $\ );
        }
        else {
            $result = $self->WRITE( join( "", @_ ) . $\ );
        }
    }
    else {
        if ( scalar @_ == 1 ) {
            $result = $self->WRITE( $_[0] );
        }
        elsif ( defined $, ) {
            $result = $self->WRITE( join( $,, @_ ) );
        }
        else {
            $result = $self->WRITE( join( "", @_ ) );
        }
    }

    return unless defined $result;
    return 1;
}

sub printf {
    my $self   = shift;
    my $fmt    = shift;
    my $result = $self->WRITE( sprintf( $fmt, @_ ) );
    return unless defined $result;
    return 1;
}

*CLOSE  = *close;
*FILENO = *fileno;
*PRINT  = *print;
*PRINTF = *printf;
*WRITE  = *write;

1;

} # --- END Cpanel/CPAN/IO/Callback/Write.pm


{ # --- BEGIN Cpanel/Destruct/DestroyDetector.pm
package Cpanel::Destruct::DestroyDetector;


use cPstrict;


our $_DEBUG;

our $_DESTRUCT_PHASE;
BEGIN { $_DESTRUCT_PHASE = 'DESTRUCT'; }

sub DESTROY ($self) {
    warn "destroy: $self (${^GLOBAL_PHASE})\n" if $_DEBUG;

    if ( ${^GLOBAL_PHASE} eq $_DESTRUCT_PHASE ) {
        warn "PID $$ ($0): $self destroyed at global destruct!";
    }

    return;
}

1;

} # --- END Cpanel/Destruct/DestroyDetector.pm


{ # --- BEGIN Cpanel/IOCallbackWriteLine/Buffer.pm
package Cpanel::IOCallbackWriteLine::Buffer;


use cPstrict;



# use Cpanel::Destruct::DestroyDetector();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Destruct::DestroyDetector); }



sub new ( $class, $line_callback ) {

    return bless [ q<>, $line_callback ], $class;
}


my $recsep_idx;

sub feed {    # ($self, $new_str)

    my $self = $_[0];

    substr( $self->[0], length( $self->[0] ), 0, $_[1] );

    while ( -1 != ( $recsep_idx = index( $self->[0], $/ ) ) ) {
        $self->[1]->( substr( $self->[0], 0, length($/) + $recsep_idx, q<> ) );
    }

    return 1;
}


sub clear ($self) {

    if ( length $self->[0] ) {
        $self->[1]->( substr( $self->[0], 0, length( $self->[0] ), q<> ) );
    }

    return 1;
}

sub DESTROY ($self) {

    if ( length $self->[0] ) {

        warn "DESTROY with content left in buffer: “$self->[0]”";
    }

    $self->SUPER::DESTROY();

    return;
}

1;

} # --- END Cpanel/IOCallbackWriteLine/Buffer.pm


{ # --- BEGIN Cpanel/IOCallbackWriteLine.pm
package Cpanel::IOCallbackWriteLine;


use strict;
use warnings;



# use Cpanel::CPAN::IO::Callback::Write();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::CPAN::IO::Callback::Write); }

# use Cpanel::IOCallbackWriteLine::Buffer ();


my %BUFFER_OBJ;

sub new {
    my ( $class, $line_callback ) = @_;

    my $buffer_obj = Cpanel::IOCallbackWriteLine::Buffer->new($line_callback);

    my $self = $class->SUPER::new( sub { $buffer_obj->feed( $_[0] ) } );

    $BUFFER_OBJ{$self} = $buffer_obj;

    return $self;
}

sub clear {
    my ($self) = @_;

    $BUFFER_OBJ{$self}->clear();

    return 1;
}

sub CLOSE {
    my ($self) = @_;

    $self->clear();

    delete $BUFFER_OBJ{$self};

    return 1;
}

sub DESTROY {
    my ($self) = @_;

    if ( $BUFFER_OBJ{$self} ) {
        $self->CLOSE();
    }

    return;
}

1;

} # --- END Cpanel/IOCallbackWriteLine.pm


{ # --- BEGIN Cpanel/Binaries/Cmd.pm
package Cpanel::Binaries::Cmd;



use cPstrict;

# use Cpanel::Fcntl::Constants    ();
# use Cpanel::Fuser               ();
# use Cpanel::IOCallbackWriteLine ();
# use Cpanel::OS                  ();
# use Cpanel::SafeRun::Object     ();
# use Cpanel::TimeHiRes           ();

use constant DEFAULT_LOCK_TIMEOUT               => 90 * 60;
use constant DEFAULT_LOCK_TIMEOUT_FRESH_INSTALL => 2 * DEFAULT_LOCK_TIMEOUT;

our $_DIR_PATH = '/var/cpanel/easylock';

sub new {
    my ( $class, %opts ) = @_;

    my %hash = %opts;

    my $self = \%hash;
    bless $self, $class;

    return $self;
}

sub lock_timeout ($self) {
    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {

        return $self->{'lock_timeout'} //= DEFAULT_LOCK_TIMEOUT_FRESH_INSTALL;
    }

    return $self->{'lock_timeout'} //= DEFAULT_LOCK_TIMEOUT;
}


sub bin_path ($self) { die "unimplemented" }


sub locks_to_wait_for { return }


sub lock_to_hold { return }


sub needs_lock ( $self, @args ) {
    return 0;
}


sub bin ($self) {
    die q[Method call] unless ref $self;

    return $self->{'bin'} if length $self->{'bin'};

    my $bin = $self->bin_path or die q[No bin_path set for ] . ref $self;
    -x $bin                   or die("Cannot find $bin on this system.");

    return $self->{'bin'} = $bin;
}


sub cmd ( $self, @args ) {
    return $self->cmd_with_logger( undef, @args );
}

sub cmd_but_warn_on_fail ( $self, @args ) {
    my $out = $self->cmd(@args);
    warn '[' . $self->bin() . " @args] exited $out->{'status'} ($out->{'output'})" if $out->{'status'};
    return $out;
}


sub cmd_with_logger ( $self, $logger, @args ) {
    return $self->_cmd_with_logger( 1, $logger, @args );
}

sub cmd_with_logger_no_timeout ( $self, $logger, @args ) {
    return $self->_cmd_with_logger( 0, $logger, @args );
}

sub _cmd_with_logger ( $self, $enable_timeout, $logger, @args ) {
    my $output_buffer = '';
    my $cb_write_line = Cpanel::IOCallbackWriteLine->new(
        sub ($line) {
            return unless length $line;
            $output_buffer .= $line;
            $logger->info($line) if $logger;
            return;
        }
    );


    my $run = $self->run(
        args   => \@args,
        stdout => $cb_write_line,
        stderr => $cb_write_line,
        $enable_timeout ? () : (
            timeout      => 0,
            read_timeout => 0,
        ),
        logger => $logger,
    );

    if ( $logger && $run->CHILD_ERROR() ) {
        my $msg = join( q< >, $run->autopsy(), $output_buffer );
        $logger->warning($msg);
    }

    return { 'output' => $output_buffer, 'status' => $run->CHILD_ERROR() };
}


sub run_or_die ( $self, @args ) {
    return $self->run( args => \@args, die_on_error => 1 );
}


sub run ( $self, %opts ) {
    my $bin = $self->bin;

    if ( $> == 0 && $bin =~ m{bin/rpm$} && Cpanel::OS::retry_rpm_cmd_no_tty_hack() ) {
        require IO::Pty;
        $opts{stdin} = eval { IO::Pty->new } || undef;    # If new fails, we will be vulnerable to pid conflicts but we already have protections against that at a module level.
    }

    my %saferun_args = (
        program      => $bin,
        before_exec  => sub { $self->_setenv },
        args         => $opts{args}         // [],
        die_on_error => $opts{die_on_error} // 0,
    );

    foreach my $param (qw{stdout stderr stdin timeout read_timeout}) {
        next unless exists $opts{$param};
        $saferun_args{$param} = $opts{$param};
    }

    my $method = $opts{die_on_error} ? 'new_or_die' : 'new';

    my $logger = $opts{'logger'};

    my $lock_to_hold = $self->get_lock_for_cmd( $logger, $saferun_args{args} );

    return Cpanel::SafeRun::Object->$method(%saferun_args);
}


sub special_lang_env_vars {
    return qw/LANG LANGUAGE LC_ALL LC_MESSAGES LC_CTYPE/;
}


sub lang { return 'C' }

sub _setenv ($self) {
    my $lang = $self->lang;
    my @keys = special_lang_env_vars();
    @ENV{@keys} = ($lang) x scalar @keys;
    $ENV{'PYTHONIOENCODING'} ||= 'UTF-8:backslashreplace';
    $ENV{'DEBIAN_FRONTEND'} = 'noninteractive';    # doesn't hurt non-ubuntu systems, but absolutely required for them
    return;
}


sub hold_lock ( $self, $logger, $args ) {
    my $lock_file = $self->lock_to_hold() or return;
    $lock_file =~ m{/} and die "lock file name only please, not an absolute path";

    my $dir_path = $_DIR_PATH;

    if ( !-d $dir_path ) {
        mkdir $dir_path, 0700;
    }
    -d $dir_path or die("Cannot create a lock without $dir_path being present");

    $lock_file = "$dir_path/$lock_file";

    my $lock_timeout = $self->lock_timeout;

    sysopen( my $fh, $lock_file, $Cpanel::Fcntl::Constants::O_RDONLY | $Cpanel::Fcntl::Constants::O_CREAT ) or die("Cannot open $lock_file for locking");
    my $start = time;
    my $cnt   = 0;
    while ( time - $start < $lock_timeout ) {
        flock( $fh, $Cpanel::Fcntl::Constants::LOCK_EX | $Cpanel::Fcntl::Constants::LOCK_NB ) and do {
            return $fh;
        };

        if ($logger) {
            $logger->info( "Waiting for lock to execute: " . join( " ", $self->bin, @$args ) ) if $cnt == 0;
            $cnt++;

            if ( $cnt % 40 == 0 ) {
                $logger->info( "Waiting for exclusive lock to run " . $self->bin );
            }
        }

        $self->_sleep_randomly;
    }

    my $msg = "Failed to get exclusive lock to run " . $self->bin;
    $logger && $logger->error($msg);

    return die $msg;
}

sub get_lock_for_cmd ( $self, $logger, $args ) {
    return unless $self->needs_lock(@$args);

    my $lock = $self->hold_lock( $logger, $args );
    $self->wait_for_locks($logger);

    return $lock;
}


sub wait_for_locks ( $self, $logger = undef ) {
    my @lock_files = $self->locks_to_wait_for;

    my $lock_timeout = $self->lock_timeout;

    my $start = time;
    my $cnt   = 0;
    while ( time - $start < $lock_timeout ) {
        my %locks = Cpanel::Fuser::check(@lock_files) or return 1;

        if ( $logger && ( $cnt++ % 40 ) == 0 ) {
            my $open_locks = %locks;
            $logger->info( "Waiting for $open_locks related locks to clear for " . $self->bin );
        }

        $self->_sleep_randomly;
    }

    return die "Timeout waiting for distro lock files related to " . $self->bin;
}

sub _sleep_randomly {
    Cpanel::TimeHiRes::sleep( ( 100 + rand(50) ) / 1000 );
    return;
}

1;

} # --- END Cpanel/Binaries/Cmd.pm


{ # --- BEGIN Cpanel/Binaries/Debian.pm
package Cpanel::Binaries::Debian;



use cPstrict;

# use Cpanel::Binaries::Cmd();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Cmd); }

sub _setenv ($self) {
    $self->SUPER::_setenv;

    $ENV{'DEBIAN_FRONTEND'} = 'noninteractive';
    $ENV{'DEBIAN_PRIORITY'} = 'critical';

    return;
}


sub locks_to_wait_for {
    return qw{
      /var/lib/dpkg/lock
      /var/lib/dpkg/lock-frontend
      /var/cache/apt/archives/lock
      /var/lib/apt/lists/lock
      /run/unattended-upgrades.lock
    };
}


sub lock_to_hold { return 'apt' }

1;

} # --- END Cpanel/Binaries/Debian.pm


{ # --- BEGIN Cpanel/Binaries/Debian/Dpkg.pm
package Cpanel::Binaries::Debian::Dpkg;



use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path ($self) {
    return '/usr/bin/dpkg';
}


sub needs_lock ( $self, $action, @args ) {
    return 1 if grep { $action eq $_ } qw/-i -P -r/;
    return 0;
}


sub what_owns ( $self, $file ) {
    return unless length $file;
    return unless $file =~ m{^/};

    my $r = $self->cmd( '-S', $file );
    if (   $r->{'status'}
        && $file !~ m{^/usr/local/cpanel}
        && $file =~ s{^/usr/}{/} ) {

        $r = $self->cmd( '-S', $file );
    }

    return if $r->{'status'};

    my $package = $r->{'output'} // '';
    $package =~ s/:.+//ms;    # passwd: /usr/bin/passwd
    return $package;
}


sub what_owns_files_no_errors ( $self, @files ) {
    @files = grep { length $_ && m{^/} } @files;    # Strip files without a leading slash you can't query on that.
    return unless scalar @files;

    my $r = $self->cmd( '-S', @files ) // {};

    my @lines = split "\n", $r->{'output'} // '';

    my %packages;

    foreach my $l (@lines) {
        next if $l =~ m{^dpkg-query: no path found};
        next if $l =~ m{^diversion by };

        if ( $l =~ qr/^([^:]+):/ ) {
            my $pkg = $1;
            $packages{$pkg} //= 1;
        }
    }

    return unless keys %packages;

    return [ sort keys %packages ];
}


sub installed_packages ($self) {
    my $installed = $self->cmd( '--list', '--no-pager' );
    $installed->{'status'} and die sprintf( "Error (%s) running %s: %s", $installed->{'status'} >> 8, $self->bin, $installed->{'output'} );

    my @lines = split( "\n", $installed->{'output'} // '' );

    shift @lines while ( @lines && $lines[0] !~ m/^\Q+++-=====\E/ );
    shift @lines;    # Strip off the last header line.

    my %results;
    foreach my $line (@lines) {
        my $attributes = substr( $line, 0, 3 );
        my ( $package, $ver_release, $arch, $description ) = split( " ", substr( $line, 3 ), 4 );
        $results{$package} = {
            ver_rel     => $ver_release,
            arch        => $arch,
            description => $description,
            _parse_attributes($attributes),
        };
    }

    return \%results;
}

sub _parse_attributes ($attr) {
    length $attr == 3 or die("Unexpected length of attributes");
    my ( $user, $state, $error ) = split( "", $attr );

    $error =~ s/\s+//;    # Strip spaces from this field as the norm is for it to be empty.
    return ( user_requested => $user, current_state => $state, package_errors => $error );
}

sub whatprovides ( $self, $filename ) {
    my @args = ( '-S', $filename );
    my $out  = $self->cmd(@args);
    return if $out->{'status'};
    return substr( $out->{'output'}, 0, index( $out->{'output'}, ':' ) );
}

1;

} # --- END Cpanel/Binaries/Debian/Dpkg.pm


{ # --- BEGIN Cpanel/Binaries/Debian/DpkgQuery.pm
package Cpanel::Binaries::Debian::DpkgQuery;



use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path ($self) {

    return '/usr/bin/dpkg-query';
}


sub query {
    my ( $self, @filter ) = @_;
    $self                    or _croak('query() method called without arguments.');
    ref $self eq __PACKAGE__ or _croak("query() must be called as a method.");

    my $answer = $self->cmd( "-W", "-f=" . $self->_get_format_string(), @filter );
    return _format_query_response($answer);
}

sub _get_format_string {
    my ($self) = @_;

    my $arch_str = $self->{'with_arch_suffix'} ? '.${Architecture}' : '';
    return '${binary:Package} ${Version}' . $arch_str . ' ${db:Status-Abbrev}\n';
}

sub _format_query_response {
    my ($answer) = @_;
    my $out = $answer->{output};
    return {
        map { ( split( m{\s+}, $_ ) )[ 0, 1 ] }
          grep {

            my $str = $_;

            $str =~ s/\s+$//g;
                 index( $str, 'is not installed' ) == -1
              && index( $str, " " )
              && index( $str, "no packages found" ) == -1
              && substr( $str, -2 ) eq 'ii';    # Filter out all but installed
          } split( "\n", $out )
    };
}

1;

} # --- END Cpanel/Binaries/Debian/DpkgQuery.pm


{ # --- BEGIN Cpanel/Parser/DpkgQuery.pm
package Cpanel::Parser::DpkgQuery;


use cPstrict;
# use Cpanel::Binaries::Debian::DpkgQuery ();

sub parse_string ($string) {
    my ( %packages, $cur_package );
    my $take_first_as = sub ($name) {
        return sub { $packages{$cur_package}{$name} = shift };
    };

    my $take_joined_as = sub ($name) {
        return sub { $packages{$cur_package}{$name} = join ' ', @_ };
    };

    my $take_all_as = sub ($name) {
        return sub { $packages{$cur_package}{$name} = [@_] },;
    };

    my $take_deplist_as = sub ($name) {
        return sub {


            my $deplist_string = join ' ', @_;
            my @pkgs = split /[,|]/xms, $deplist_string;
            s/^\s+//xms for @pkgs;
            s/\s+$//xms for @pkgs;

            my %depends;
            foreach my $pkg (@pkgs) {
                if ( $pkg =~ /^ ([A-Za-z0-9_.\-]+) \s+ \( ( [^)]+ ) \) $/xms ) {
                    $depends{$1} = $2;
                }
                else {
                    $depends{$pkg} = '';
                }
            }

            $packages{$cur_package}{$name} = \%depends;
        };
    };

    my %actions = (
        'Package' => sub ($name) {
            $packages{$name}{'package'} = $cur_package = $name;
        },

        'Status'               => $take_all_as->('status'),
        'Priority'             => $take_first_as->('priority'),
        'Section'              => $take_first_as->('section'),
        'Installed-Size'       => $take_first_as->('installed_size'),
        'Efi-Vendor'           => $take_joined_as->('efi_vendor'),
        'Ruby-Versions'        => $take_joined_as->('ruby_versions'),
        'Maintainer'           => $take_joined_as->('maintainer'),
        'Architecture'         => $take_first_as->('arch'),
        'Multi-Arch'           => $take_first_as->('multi_arch'),
        'Version'              => $take_first_as->('version'),
        'Essential'            => $take_first_as->('essential'),
        'Important'            => $take_first_as->('important'),
        'Original-Vcs-Browser' => $take_first_as->('original_vcs_browser'),
        'Original-Vcs-Git'     => $take_first_as->('original_vcs_git'),
        'Cnf-Visible-Pkgname'  => $take_first_as->('cnf_visible_pkgname'),
        'Config-Version'       => $take_first_as->('config_version'),
        'Triggers-Pending'     => $take_first_as->('triggers_pending'),
        'Depends'              => $take_deplist_as->('depends'),
        'Pre-Depends'          => $take_deplist_as->('pre_depends'),
        'Recommends'           => $take_deplist_as->('recommends'),
        'Replaces'             => $take_deplist_as->('replaces'),
        'Breaks'               => $take_deplist_as->('breaks'),
        'Enhances'             => $take_deplist_as->('enhances'),
        'Suggests'             => $take_deplist_as->('suggests'),
        'Provides'             => $take_deplist_as->('provides'),
        'Conflicts'            => $take_deplist_as->('conflicts'),
        'Built-Using'          => $take_deplist_as->('built_using'),
        'Description'          => $take_joined_as->('description'),
        'Source'               => $take_joined_as->('source'),
        'Homepage'             => $take_first_as->('homepage'),
        'Original-Maintainer'  => $take_joined_as->('original_maintainer'),

        'Conffiles' => sub (@args) {
            my %conffiles;
            for ( my $i = 0; $i < @args; $i++ ) {
                my $path = $args[$i];
                $conffiles{$path} = { 'hash' => $args[ $i + 1 ] };
                $i++;

                if ( ( $args[ $i + 1 ] // '' ) eq 'obsolete' ) {
                    $conffiles{$path}{'obsolete'} = 1;
                    $i++;
                }
            }

            $packages{$cur_package}{'conffiles'} = \%conffiles;
        },
    );

    my ( $cur_key, @cur_content );
    my $maybe_process_content_cb = sub {

        $cur_key and @cur_content
          or return;

        my $cb = $actions{$cur_key}
          or return;

        $cb->(@cur_content);
    };

    chomp( my @lines = split /\n/xms, $string );
    foreach my $line (@lines) {
        if ( $line =~ /^ ([A-Za-z0-9\-]+) : (.+)? $/xms ) {
            my ( $key, $value ) = ( $1, $2 // '' );
            s/^\s+//xms for $key, $value;
            s/\s+$//xms for $key, $value;

            $maybe_process_content_cb->();

            $cur_key     = $key;
            @cur_content = split /\s+/xms, $value;
        }
        elsif ( substr( $line, 0, 1 ) eq ' ' ) {

            push @cur_content, split /\s+/xms, $line =~ s/^\s+//xmsr;
        }
    }

    $maybe_process_content_cb->();

    return \%packages;
}

sub parse () {
    my $dpkg    = Cpanel::Binaries::Debian::DpkgQuery->new();
    my $content = $dpkg->cmd('--status');
    return parse_string( $content->{'output'} );
}

1;


} # --- END Cpanel/Parser/DpkgQuery.pm


{ # --- BEGIN Cpanel/SafeChdir.pm


package Cpanel::SafeChdir;


use strict;
use Cwd            ();
# use Cpanel::Logger ();

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

sub new {
    my ( $class, $path ) = @_;

    my $self = {
        'current_directory' => Cwd::getcwd(),
    };

    die "$path does not exist.\n" if !-d $path;

    chdir($path) or die "Unable to change to $path.\n";

    return bless $self, $class;
}

sub DESTROY {
    my ($self) = @_;

    my $original_dir = $self->{'current_directory'};
    chdir($original_dir) or $logger->warn("Unable to change back to $original_dir");
}

1;

} # --- END Cpanel/SafeChdir.pm


{ # --- BEGIN Cpanel/RPM/Versions/Pkgr/DEB.pm
package Cpanel::RPM::Versions::Pkgr::DEB;



use cPstrict;
# use Cpanel::RPM::Versions::Pkgr();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::RPM::Versions::Pkgr); }

# use Cpanel::Binaries::Debian::Dpkg      ();
# use Cpanel::Binaries::Debian::DpkgQuery ();
# use Cpanel::Parser::DpkgQuery           ();
# use Cpanel::SafeChdir                   ();

use Digest::MD5 ();
use List::Util  ();

use constant package_extension => '.deb';
use constant dpkg_info_dir     => '/var/lib/dpkg/info';


sub pkgr ($self) { return $self->{'dpkg'} ||= Cpanel::Binaries::Debian::Dpkg->new }    # not required, here as a security


sub installed_packages ($self) {
    return $self->{'installed_packages'} if $self->{'installed_packages'};

    my $installed_packages = $self->pkgr->installed_packages;
    my %installed;
    foreach my $package ( keys %$installed_packages ) {

        next if ( $installed_packages->{$package}->{'user_requested'} // '' ) eq 'r' && ( $installed_packages->{$package}->{'current_state'} // '' ) eq 'c';
        $installed{$package} = $installed_packages->{$package}->{'ver_rel'};
    }
    return $self->{'installed_packages'} = \%installed;
}


sub test_install ( $self, $download_dir, $pkg_files, $uninstall_hash ) {    ## no critic qw(ManyArgs) - mis-parse
    my $chdir = Cpanel::SafeChdir->new($download_dir);

    $self->acquire_lock;

    $self->logger->info("Testing Deb transaction");

    my $dpkg_query_output   = Cpanel::Binaries::Debian::DpkgQuery->new->cmd('--status');
    my $installed_dpkg_data = Cpanel::Parser::DpkgQuery::parse_string( $dpkg_query_output->{'output'} // '' );

    delete $installed_dpkg_data->@{ keys $uninstall_hash->%* };

    my %data_per_file;
    foreach my $filename ( $pkg_files->@* ) {
        my $output      = $self->pkgr->cmd( '-I', $filename );
        my $dpkg_string = ( $output->{'output'} // '' ) =~ s/^\s//xmsgr;
        my $dpkg_data   = Cpanel::Parser::DpkgQuery::parse_string($dpkg_string);

        values $dpkg_data->%* == 0
          and die "Found no packages when checking file '$filename'";

        values $dpkg_data->%* >= 2
          and die "Found multiple packages when checking one file";

        my $pkg_data = ( values $dpkg_data->%* )[0];
        $installed_dpkg_data->{ $pkg_data->{'package'} } = $pkg_data;
        $data_per_file{$filename} = $pkg_data;
    }

    foreach my $pkg_name ( keys $installed_dpkg_data->%* ) {
        $installed_dpkg_data->{$_} = {} for keys %{ $installed_dpkg_data->{$pkg_name}{'provides'} // {} };
    }

    foreach my $filename ( $pkg_files->@* ) {
        my $pkg_data = $data_per_file{$filename};
        my @packages = map { keys $pkg_data->{$_}->%* } qw< depends recommends suggests pre_depends >;

        @packages
          or next;

        my @unavailable = grep !$installed_dpkg_data->{$_}, @packages
          or next;

        my $error_message = sprintf "Test install failed for '%s' with missing dependencies: %s",
          $filename, join ', ', @unavailable;

        $self->logger->fatal($error_message);
        die $error_message;
    }

    $self->logger->info('Deb transaction succeeded!');
    return;
}


sub install ( $self, $download_dir, $preinstall, $pkg_files ) {
    my $chdir = Cpanel::SafeChdir->new($download_dir);

    my @to_install = sort { $a cmp $b } List::Util::uniq(@$pkg_files);

    $self->logger->info( 'Installing new packages: ' . join( ' ', @to_install ) );

    my $result = $self->run_with_logger( qw/-i --force-confold --force-confmiss/, @to_install );

    my $errors = $self->_parse_dpkg_errors($result);
    if ($errors) {
        $self->logger->error("The following possible errors were detected while installing packages:");
        $self->logger->error($errors);
        $self->logger->set_need_notify() unless $preinstall;    # Notify on completion of these errors but only on the main transaction.
    }

    return $errors;
}


sub uninstall ( $self, $packages ) {
    my @to_erase = sort { $a cmp $b } List::Util::uniq(@$packages);
    $self->logger->info( 'Uninstalling unneeded packages: ' . join( ' ', @to_erase ) );

    my $result = $self->run_with_logger( '--purge', '--force-all', @to_erase );

    my $errors = $self->_parse_dpkg_errors($result);

    if ($errors) {
        $self->logger->error("The following possible errors were detected while uninstalling packages:");
        $self->logger->error($errors);
        $self->logger->set_need_notify();
    }
    $self->clear_installed_packages_cache;

    return scalar @to_erase;
}


sub uninstall_leave_files ( $self, @packages ) {

    my @to_erase = sort { $a cmp $b } List::Util::uniq(@packages);

    $self->logger->info( "Removing " . scalar @to_erase . " broken packages: " . join( ', ', @to_erase ) );

    $self->run_with_logger( qw{--remove --force-remove-reinstreq --force-depends}, @to_erase );

    $self->clear_installed_packages_cache;

    return;
}


sub what_owns ( $self, $file ) {
    return $self->pkgr->what_owns($file);
}


sub get_dirty_packages ( $self, $installed_array, $skip_digest_check ) {    ## no critic qw(ManyArgs) - mis-parse
    my $install_info = $self->pkgr->installed_packages;

    my %broken_packages;
    foreach my $package ( sort { $a cmp $b } keys %$install_info ) {
        next unless grep { $_ eq $package } @$installed_array;    #don't report on it if it's not installed.
        my $info = $install_info->{$package};

        next if $info->{'user_requested'} eq 'r' && $info->{'current_state'} eq 'c';

        my $response = $self->_check_package_stability( $package, $skip_digest_check );
        if ($response) {
            $broken_packages{$package} = [$response];
            next;
        }

        next
          if $info->{'user_requested'} eq 'i'
          && $info->{'current_state'} eq 'i'
          && !$info->{'package_errors'};

        my $reason = sprintf( "%s%s%s", $info->{'user_requested'}, $info->{'current_state'}, $info->{'package_errors'} // '' );
        $broken_packages{$package} = [ [ 'all' => $reason ] ];
    }

    return \%broken_packages;

}

sub _check_package_stability ( $self, $package, $skip_digest_check = 0 ) {

    my %expected_md5;

    open( my $mdfh, '<', dpkg_info_dir . "/$package.md5sums" )
      or return [ sprintf( "%s/%s.md5sums", dpkg_info_dir, $package ), 'All package md5 info is missing' ];

    while ( my $line = <$mdfh> ) {
        chomp $line;
        my ( $md5, $file ) = split( " ", $line, 2 );
        $file = "/$file" if index( $file, '/' ) != 0;
        $expected_md5{$file} = $md5;
        lstat($file) and next;
        return [ $file, 'File is missing' ];
    }
    close $mdfh;

    open( my $lstfh, '<', dpkg_info_dir . "/$package.list" )
      or return [ sprintf( "%s/%s.list", dpkg_info_dir, $package ), 'Package list is missing' ];

    while ( my $file = <$lstfh> ) {
        chomp $file;
        $file = "/$file" if index( $file, '/' ) != 0;
        next             if $expected_md5{$file};       # we already checked this as it's mentioned in the md5sums file.
        lstat($file) and next;
        return [ $file, 'File is missing' ];
    }
    close $lstfh;

    return if $skip_digest_check;

    my $digest = Digest::MD5->new;
    foreach my $file ( sort keys %expected_md5 ) {
        open( my $md5fh, '<', $file ) or return [ $file, 'File is not readable' ];
        $digest->addfile($md5fh);
        $digest->hexdigest eq $expected_md5{$file} or return [ $file, "The MD5 digest (" . $digest->hexdigest . ") has changed" ];
    }

    return;
}

sub _parse_dpkg_errors ( $self, $result ) {
    return if !$result->{'output'};

    my @errors;
    foreach my $line ( split( /\n/, $result->{'output'} ) ) {
        next unless $line =~ /^error:\s*([^:]+)/;

        my $error = $1;
        $error =~ s/\s+$//;    # Strip trailing space.
        push @errors, $error;
    }

    if (@errors) {
        my $errors = join ' ', @errors;
        return $errors;
    }
    else {
        return;
    }

}

1;

} # --- END Cpanel/RPM/Versions/Pkgr/DEB.pm


{ # --- BEGIN Cpanel/Binaries/Gpg.pm
package Cpanel::Binaries::Gpg;



use cPstrict;

# use Cpanel::Binaries::Cmd();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Cmd); }



use constant CPANEL_FINGERPRINT => q[83D9 FE12 C401 AE53 434F 4889 CB0C 590A 361C D137];

sub bin_path ($self) {
    return '/usr/bin/gpg';
}


sub is_file_signed_by_cpanel ( $self, $file ) {

    my $answer = $self->cmd( '--verify', $file );

    return unless defined $answer->{output};

    my $key = CPANEL_FINGERPRINT;
    $key =~ s{\s}{}g;

    return $answer->{output} =~ qr{using RSA key \Q$key\E$}mi;
}

1;

} # --- END Cpanel/Binaries/Gpg.pm


{ # --- BEGIN Cpanel/Binaries/Rpm.pm


package Cpanel::Binaries::Rpm;


use cPstrict;

# use Cpanel::Binaries::Cmd();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Cmd); }

# use Cpanel::Binaries::Gpg ();
use List::Util            ();


sub bin_path {

    return -x '/usr/bin/rpm' ? '/usr/bin/rpm' : -x '/bin/rpm' ? '/bin/rpm' : die("Unable to find the rpm binary to install packages");
}

sub locks_to_wait_for { return qw{/var/lib/rpm/.rpm.lock /var/run/yum.pid} }
sub lock_to_hold      { return 'rpmdb' }

sub needs_lock ( $self, $action, @args ) {
    return 0 if $action eq '--query';
    return 0 if $action eq '-q' && grep { $_ eq '-p' } @args;    # `rpm -q -p` acts directly on an rpm file. We don't need a lock for this.
    return 1;
}


sub query ( $self, @filter ) {
    ref $self eq __PACKAGE__ or _croak("query() must be called as a method.");

    my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--queryformat', $self->_get_format_string(), @filter );
    return _format_query_response($answer);
}


sub installed_packages ( $self, @filter ) {
    ref $self eq __PACKAGE__ or _croak("installed_packages() must be called as a method.");

    my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--queryformat', $self->_get_format_string(), '-a', @filter );

    return {} if $answer->{status} != 0;

    return _format_query_response($answer);

}

sub _format_query_response ($answer) {
    my $out = $answer->{output};

    return { map { ( split( m{\s+}, $_ ) )[ 0, 1 ] } grep { $_ !~ /not installed/i } split( "\n", $out ) };
}


sub what_owns ( $self, @filter ) {

    return $self->_what_owns( my $error = 1, @filter );
}


sub what_owns_no_errors ( $self, @filter ) {

    return $self->_what_owns( my $error = 0, @filter );
}


sub _what_owns ( $self, $raise_error, @filter ) {

    _croak("what_owns() must be called as a method.")         unless ref $self eq __PACKAGE__;
    _croak('what_owns() requires at least one search filter') unless @filter;

    my $answer = $self->cmd(
        '--query', '--nodigest', '--nosignature', '--queryformat',    #
        $self->_get_format_string(), '-f', @filter                    #
    );

    if ($raise_error) {
        if ( $answer->{'status'} && $answer->{'output'} ) {

            my @not_owned = ( $answer->{'output'} =~ m/^file (.+?) is not owned by any package$/gm );
            _croak( 'The system could not find any RPM owner for the following file(s): ' . join( ', ', @not_owned ) )
              if @not_owned;
        }
        if ( $answer->{status} != 0 ) {
            _croak( 'The system could not find query for the specfied file(s): ' . join( ', ', @filter ) );
        }
    }

    my @lines = split( "\n", $answer->{'output'} );
    if ( !$raise_error ) {
        @lines = grep { $_ !~ qr{(?:is not owned by any package|No such file or directory)} } @lines;
    }

    my %rpmfiles = map { m/^(\S+)\s+(.+?)$/ } @lines;

    return \%rpmfiles;
}


sub qR ( $self, @filter ) {
    ref $self eq __PACKAGE__ or _croak("qR() must be called as a method.");

    _croak('qR() requires at least one search filter')
      if !@filter;

    my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--queryformat', $self->_get_format_string(), '-R', @filter );
    if ( $answer->{'status'} && $answer->{'output'} ) {

        my @not_installed = ( $answer->{'output'} =~ m/^package (.+?) is not installed$/gm );
        _croak( 'The system could not find the following RPM(s): ' . join( ', ', @not_installed ) )
          if @not_installed;
        _croak( 'The system could not query the dependencies of the package(s): ' . join( ', ', @filter ) );
    }
    elsif ( $answer->{status} != 0 ) {
        return {};
    }

    my %rpmquery = map { my $line = $_; m/^(\S+?)\s+(.+?)$/ ? ( $1, $2 ) : ( $line, undef ) } split( /\n/, $answer->{'output'} );
    return \%rpmquery;
}


sub list_files_from_package_path ( $self, $rpm_file_path ) {
    my @args = ( '--query', '--list', '--package', '--', $rpm_file_path );
    my $out  = $self->cmd_but_warn_on_fail(@args);
    return if $out->{'status'};
    return split( m<(?:\r?\n)+>, $out->{'output'} );
}

sub list_files_from_installed_package ( $self, $rpm_name ) {
    my @args = ( '--query', '--list', $rpm_name );
    my $out  = $self->cmd_but_warn_on_fail(@args);
    return if $out->{'status'};
    return split( m<(?:\r?\n)+>, $out->{'output'} );
}

sub what_provides ( $self, $search ) {
    return unless $search;
    my @args = ( '--query', '--queryformat', '%{NAME}\n', '--whatprovides', $search );
    my $run  = $self->run( args => \@args );
    if ( $run->CHILD_ERROR() ) {
        if ( 0 == index( $run->stdout(), 'no package provides' ) ) {
            return;
        }

        $run->die_if_error();
    }
    my $pkg = $run->stdout();
    chomp($pkg);
    return $pkg;
}

sub what_provides_with_details ( $self, $search ) {

    my $field_separator  = ":,:";
    my $record_separator = ":-:";

    my @fields       = ( 'name', 'version', 'release', 'arch', 'group', 'summary', 'description' );
    my $query_format = join( $field_separator, map { "\%{$_}" } @fields ) . $record_separator;

    my @args = ( '--query', '--qf', $query_format, '--whatprovides', $search );

    my $out = $self->cmd(@args);
    return if $out->{'status'};

    my $output = $out->{'output'};

    my @records;
    for my $rpm_record ( split /\Q$record_separator\E/, $output ) {
        my %record;
        ( @record{@fields} = split /\Q$field_separator\E/, $rpm_record ) == scalar @fields or next;
        chomp @record{@fields};
        push @records, \%record;
    }

    return \@records;
}

sub what_requires ( $self, $pkg ) {
    my @args = ( '--query', '--requires', $pkg );
    my $out  = $self->cmd(@args);
    return () if $out->{'status'};
    my @lines = split( /\n/, $out->{output} // '' );
    my %perl_deps;
    foreach my $l (@lines) {
        next unless $l =~ m/^(\S+)(?: (.+))?/;
        my ( $dep, $rule ) = ( $1, $2 );
        $perl_deps{$dep} = $rule // '0';
    }
    return \%perl_deps;
}


sub add_repo_keys ( $self, @keys2import ) {
    my @args   = ( '--import', '--', @keys2import );
    my $import = $self->cmd_but_warn_on_fail(@args);
    return 0 if $import->{'status'};
    return 1;
}


sub get_version ( $self, @filter ) {
    ref $self eq __PACKAGE__ or _croak("q() must be called as a method.");

    _croak('q() requires at least one search filter')
      if !@filter;

    my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--queryformat', $self->_get_format_string(), @filter );

    my %rpmquery = map {
        my $line = $_;
        m/^(\S+?)\s+(.+?)$/ ? ( $1, $2 ) : ( $line, undef )
    } grep {
        my $line = $_;
        $line !~ m/^package (.+?) is not installed$/gm
    } split( /\n/, $answer->{'output'} );
    return \%rpmquery;
}


sub has_rpm ( $self, $search = undef ) {
    ref $self eq __PACKAGE__ or _croak("has_rpm() must be called as a method.");

    _croak('has_rpm() requires a search filter')
      if !$search;

    my $q = $self->installed_packages($search);
    return $q && $q->{$search} ? 1 : 0;
}


sub install_or_upgrade_from_file ( $self, @rpm_paths ) {
    $self->run_or_die(
        '--upgrade',
        '--verbose',
        '--hash',
        '--oldpackage',
        @rpm_paths,
    );
    return;
}


sub verify_package ( $self, $package, $file = undef ) {
    return 0 if !length $package;

    return 0 if length $file && !-e $file;

    my $answer = $self->cmd( '--query', '--verify', '--verbose', $package );

    my $output = $answer->{output} // '';

    return 1 if $output =~ m/^package \Q$package\E is not installed/;    # If it's not installed, we consider that unaltered.

    if ( length $file ) {

        $output = join "\n", grep { m{ \Q$file\E$} } split( "\n", $output );
    }

    return 0 if $output =~ m{^\.*[^. ]}m;
    return 1;
}


sub package_file_is_signed_by_cpanel ( $self, $file ) {

    my $answer = $self->cmd( '--query', '--queryformat', '%{SIGPGP:pgpsig}\n', '--file', $file );
    my $sig    = $answer->{output} or return 0;

    my $cpanel_rpm_fingerprint = Cpanel::Binaries::Gpg::CPANEL_FINGERPRINT();
    $cpanel_rpm_fingerprint =~ s{\s}{}g;
    $cpanel_rpm_fingerprint =~ s{^.+(.{16})$}{$1};

    return $sig =~ qr/Key ID \Q$cpanel_rpm_fingerprint\E$/i;
}

sub _get_format_string ($self) {

    return $self->{'with_arch_suffix'} ? '%{NAME} %{VERSION}-%{RELEASE}.%{ARCH}\n' : '%{NAME} %{VERSION}-%{RELEASE}\n';
}


sub get_rpm_scripts ( $self, @rpms ) {
    scalar @rpms or return;

    my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--scripts', @rpms );

    return unless $answer->{'status'} || length $answer->{'output'};

    if ( scalar @rpms == 1 ) {
        return if $answer->{'status'};    # error response
        return { $rpms[0] => $answer->{'output'} };
    }

    my %scripts;
    foreach my $rpm (@rpms) {
        my $answer = $self->cmd( '--query', '--nodigest', '--nosignature', '--scripts', $rpm );
        next if $answer->{'status'};      # error response
        length $answer or next;
        $scripts{$rpm} = $answer->{'output'};
    }

    return \%scripts;
}


sub installed_obsoletes ($self) {
    my $answer    = $self->cmd( '--query', '--all', '--obsoletes' );
    my @obsoletes = List::Util::uniq( sort { $a cmp $b } map { s/ [>=<].*//; $_ } split( "\n", $answer->{'output'} // '' ) );    ## no critic(ProhibitMutatingListFunctions);

    $answer = $self->cmd( '--query', @obsoletes );
    my @installed_obsoletes = sort { $a cmp $b } grep { $_ !~ m/^package .+ is not installed/ } split( "\n", $answer->{'output'} // '' );

    return \@installed_obsoletes;
}


sub remove_packages_nodeps ( $self, @rpms ) {
    @rpms or return '';    # Nothing to do!
    my $answer = $self->cmd( '--erase', '--nodeps', @rpms );
    return $answer->{'output'} // '';
}

sub _croak {
    require Carp;
    goto \&Carp::croak;
}

1;

} # --- END Cpanel/Binaries/Rpm.pm


{ # --- BEGIN Cpanel/RPM/Versions/Pkgr/RPM.pm
package Cpanel::RPM::Versions::Pkgr::RPM;



use cPstrict;
# use Cpanel::RPM::Versions::Pkgr();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::RPM::Versions::Pkgr); }

# use Cpanel::Binaries            ();
# use Cpanel::IOCallbackWriteLine ();
# use Cpanel::Binaries::Rpm       ();
# use Cpanel::SafeChdir           ();


sub pkgr ($self) { return $self->{'rpm'} ||= Cpanel::Binaries::Rpm->new }    # not required, here as a security

use constant package_extension => '.rpm';
use constant WARN_IF_ERRORS    => 1;


sub installed_packages ($self) {
    return $self->{'installed_packages'} ||= $self->pkgr->installed_packages;
}


sub test_install ( $self, $download_dir, $pkg_files, $uninstall_hash ) {    ## no critic qw(ManyArgs) - mis-parse
    my $chdir = Cpanel::SafeChdir->new($download_dir);

    $self->acquire_lock;

    $self->logger->info("Testing RPM transaction");

    my $result = $self->pkgr->cmd( '-U', '--test', '--replacepkgs', '--oldpackage', @$pkg_files );

    my $child_error = $result->{'status'} >> 8;

    my @output = split( "\n", $result->{'output'} );

    my $legacy_major_perl_version = Cpanel::Binaries::PERL_LEGACY_MAJOR();
    my $removing_legacy_perl      = grep { $_ =~ m/cpanel-perl-${legacy_major_perl_version}-/ } keys %$uninstall_hash;

    if ( $removing_legacy_perl && scalar @output ) {
        my $new_major_perl_version = Cpanel::Binaries::PERL_MAJOR();

        if ( $removing_legacy_perl && $child_error ) {
            @output = grep { $_ !~ m{^\s+file \S+ from install of cpanel-perl-$new_major_perl_version\S+ conflicts with file from package cpanel-perl-$legacy_major_perl_version\S} } @output;
        }
    }

    if (@output) {

        splice( @output, 0, 1 ) if $output[0] =~ m{error: Failed dependencies:};
        foreach my $rpm ( keys %$uninstall_hash ) {
            @output = grep { $_ !~ m{is needed by \(installed\) \Q$rpm\E\S} } @output;
        }
    }
    $child_error = 0 if ( !@output );

    $self->logger->info( join( "\n", @output ) );
    $self->logger->warning("Exit Code: $child_error") if $child_error > 0;
    if ( $child_error > 0 ) {
        my $err = "Test install failed: $result->{output}";
        $self->logger->fatal($err);
        die $err;
    }

    $self->logger->info("RPM transaction succeeded!");
    return;    # We die if it goes wrong.
}


sub install ( $self, $download_dir, $preinstall, $pkg_files ) {    ## no critic qw(ManyArgs) - mis-parse
    my $chdir = Cpanel::SafeChdir->new($download_dir);

    $self->acquire_lock;

    my @args = ( '-Uv', '--replacepkgs', '--oldpackage', @$pkg_files );

    $self->logger->info( 'Installing new rpms: ' . join( ' ', sort { $a cmp $b } @$pkg_files ) );

    my $result = $self->run_with_logger_no_timeout(@args);

    return $self->_parse_rpm_errors( $result->{'output'}, $preinstall );
}


sub uninstall ( $self, $packages ) {
    $self->acquire_lock;

    $self->logger->info( 'Uninstalling unneeded rpms: ' . join( ' ', @$packages ) );

    my @to_erase = $self->_rpm_q_dedup(@$packages);

    my $result = $self->run_with_logger_no_timeout( '-e', '--nodeps', @to_erase );

    $self->_parse_rpm_errors( $result->{'output'} );

    $self->clear_installed_packages_cache;

    return scalar @to_erase;
}


sub uninstall_leave_files ( $self, @packages ) {
    $self->acquire_lock;

    my @rpms_to_remove = $self->_rpm_q_dedup(@packages);

    $self->logger->info( "Removing " . scalar @rpms_to_remove . " broken rpms: " . join( ', ', @rpms_to_remove ) );

    $self->run_with_logger_no_timeout( qw{-e --nodeps --justdb}, @rpms_to_remove );
    $self->clear_installed_packages_cache;

    return;
}


sub what_owns ( $self, $file ) {
    my $files = $self->pkgr->what_owns_no_errors($file);    # lol

    return $files->{$file};
}


sub get_dirty_packages ( $self, $installed_array, $skip_digest_check ) {    ## no critic qw(ManyArgs) - mis-parse
    my $broken_files = $self->_fetch_altered_files( $installed_array, $skip_digest_check );
    return {} if ( !@$broken_files );

    return $self->_fetch_altered_rpms( $installed_array, $broken_files );

}



sub _fetch_altered_files ( $self, $installed_array, $skip_digest_check = 0 ) {    ## no critic qw(ManyArgs) - mis-parse

    $self->logger->info("Looking for RPMs with modified files other than timestamp or permissions changes");
    my @broken_files;

    my @rpm_options = ( $ENV{'CPANEL_RPM_NO_DIGEST'} || $skip_digest_check ) ? qw{ --nosignature --nodigest --nomd5} : ();
    push @rpm_options, '--noscripts', '--nodeps';

    my $run = $self->pkgr->run( 'args' => [ '-V', @rpm_options, @$installed_array ] );

    my %lock;
    foreach my $line ( split( m{\n}, ${ $run->stdout_r() } ) ) {
        if ( $line =~ m{^\.M\.\.\.\.\.[T.]\.\s+/} ) {    # Warn if permissions changed only on non-doc/config files.
            $self->logger->warning("Permissions mis-match (ignored): $line");
        }
        next if ( $line =~ m/^\.[.M]\.\.\.\.\.[T.]/ );    # Skip clean rpms and ignore mtime or time changes to the files.
        next if ( $line =~ m/^\S{8,9}\s+[cdg]\s/ );       # Skip config or doc files.
        chomp $line;

        next unless ( $line =~ m/^(\S{8,9}|missing\s+[cdg]|missing)\s+(\S.*)$/ );    # Doesn't look like an rpm -V row?
        my ( $reason, $file ) = ( $1, $2 );

        if ( substr( $file, 0, 1 ) =~ tr{a-z}{} && substr( $file, 1, 1 ) eq ' ' ) {
            $reason .= " " . substr( $file, 0, 2, '' );
        }
        next if $lock{$file};
        $lock{$file} = 1;
        push @broken_files, [ $file, $reason ];
    }

    $self->logger->warn( $run->stderr() ) if $run->stderr();


    return \@broken_files;
}


sub _fetch_altered_rpms ( $self, $installed_array, $broken_files_array ) {    ## no critic qw(ManyArgs) - mis-parse

    my %all_broken_files = map { $_->[0] => $_->[1] } @$broken_files_array;
    if ( scalar keys %all_broken_files ) {
        return $self->_get_rpm_list_for_files( \%all_broken_files, $installed_array );
    }
    return {};
}

sub _get_rpm_list_for_files ( $self, $all_broken_files_with_reasons_hr, $cpanel_rpm_list ) {    ## no critic qw(ProhibitManyArgs) - needs refactor


    my %seen_pkg;
    my $current_pkg;
    $self->pkgr->run(
        'stdout' => Cpanel::IOCallbackWriteLine->new(
            sub {
                chomp $_[0];
                if ( rindex( $_[0], '---', 0 ) == 0 ) {
                    $current_pkg = substr( $_[0], 3 );
                }
                elsif ( exists $all_broken_files_with_reasons_hr->{ $_[0] } ) {

                    push @{ $seen_pkg{$current_pkg} }, [ $_[0], $all_broken_files_with_reasons_hr->{ $_[0] } ];
                }
            }
        ),
        'args' => [ '-q', '--list', '--nodigest', '--nosignature', '--queryformat', '---%{NAME},%{VERSION},%{RELEASE}\\n', @$cpanel_rpm_list ],
    );
    return \%seen_pkg;
}

sub _rpm_q_dedup ( $self, @rpms ) {
    my %seen;

    my $rpm_q = $self->pkgr->cmd( '-q', @rpms ) || {};

    my @list = grep { $_ && !$seen{$_}++ } ( $rpm_q->{'output'} // '' ) =~ m/^(\S+)$/mg;
    @list = @rpms if $? || !@list;

    @list = sort { $a cmp $b } @list;
    return @list;
}

sub _parse_failed_rpm_dependencies ( $self, $output = undef ) {
    return [] unless defined $output;

    my %rpms;
    foreach my $line ( split( /\n/, $output ) ) {
        my ( $try, $blocker ) = split qr{is needed by \(installed\)\s+}i, $line;
        next unless defined $blocker;
        my @name = split '-', $blocker;
        next unless scalar @name > 2;
        pop(@name) for 1 .. 2;
        my $rpm = join '-', @name;
        $rpms{$rpm} = 1;
    }

    return [ sort keys %rpms ];
}

sub _parse_rpm_errors ( $self, $output, $preinstall = 0 ) {
    return if !$output;

    my @errors;
    foreach my $line ( split( /\n/, $output ) ) {
        if ( $line =~ /^error:\s*([^:]+)\s*/ ) {
            push @errors, $1 if $1;
        }
    }

    return unless @errors;

    my $errors = join ' ', @errors;

    $self->logger->error("The following possible errors were detected while installing RPMs:");
    $self->logger->error($errors);
    $self->logger->set_need_notify() unless $preinstall;    # Notify on completion of these errors but only on the main transaction.

    if ( -e q{/var/cpanel/dev_sandbox} ) {
        my $rpms_to_remove = $self->_parse_failed_rpm_dependencies($output);
        $self->logger->error( "Try to run:\n> rpm -e --nodeps " . join( ' ', @$rpms_to_remove ) ) if $rpms_to_remove && scalar @$rpms_to_remove;
    }

    return;
}

1;

} # --- END Cpanel/RPM/Versions/Pkgr/RPM.pm


{ # --- BEGIN Cpanel/RPM/Versions/Pkgr.pm
package Cpanel::RPM::Versions::Pkgr;



use cPstrict;

# use Cpanel::OS                       ();
# use Cpanel::Fcntl::Constants         ();
# use Cpanel::RPM::Versions::Pkgr::DEB ();    # PPI USE OK -- Needed during updatenow.static. Let's not try to dynamically load this.b
# use Cpanel::RPM::Versions::Pkgr::RPM ();    # PPI USE OK -- Needed during updatenow.static. Let's not try to dynamically load this.b

use constant PKGR_INSTALL_IN_PROGRESS => '/var/cpanel/install_rpms_in_progress';


sub new ( $class, %args ) {

    my $pkgr;
    if ( $class =~ m/^Cpanel::RPM::Versions::Pkgr::(\S+)/ ) {
        $pkgr = $1;
    }
    else {
        $pkgr = determine_package_system();
    }

    $args{'packaging'} = lc($pkgr);

    my $new_class = "Cpanel::RPM::Versions::Pkgr::${pkgr}";

    my $self = bless \%args, $new_class;

    return $self;
}


sub pkgr ($self) { die "unimplemented" }


sub logger ($self) { return $self->{'logger'} }


sub clear_installed_packages_cache ($self) {
    delete $self->{'installed_packages'};
    return;
}


sub run_with_logger ( $self, @args ) {

    return $self->pkgr->cmd_with_logger( $self->logger, @args );
}


sub run_with_logger_no_timeout ( $self, @args ) {

    return $self->pkgr->cmd_with_logger_no_timeout( $self->logger, @args );
}


sub determine_package_system {

    return 'RPM' if Cpanel::OS::is_rpm_based();
    return 'DEB' if Cpanel::OS::is_apt_based();

    die("Unable to determine the packaging system for this OS");
}


sub acquire_lock ($self) {

    return if $self->{'nolock'};

    return 1 if $self->{'lock_fh'} && ref $self->{'lock_fh'};

    open( my $fh, '>>', PKGR_INSTALL_IN_PROGRESS )
      or die 'Failed to create install in progress file (' . PKGR_INSTALL_IN_PROGRESS . "): $!";

    my $loop = 0;
    while ( !flock( $fh, $Cpanel::Fcntl::Constants::LOCK_EX | $Cpanel::Fcntl::Constants::LOCK_NB ) ) {
        $self->logger->warning( sprintf( "Waiting for lock file %s to be released. Try `fuser %s`", PKGR_INSTALL_IN_PROGRESS, PKGR_INSTALL_IN_PROGRESS ) ) if ( $loop++ % 60 == 4 );
        sleep 1;
    }

    flock( $fh, $Cpanel::Fcntl::Constants::LOCK_EX )
      or die 'Failed to lock install in progress file (' . PKGR_INSTALL_IN_PROGRESS . "): $!";

    $self->{'lock_fh'} = $fh;

    return 2;
}


sub DESTROY ($self) {
    return unless $self->{'lock_fh'};

    delete $self->{'lock_fh'};
    unlink PKGR_INSTALL_IN_PROGRESS;
    return 1;
}

1;

} # --- END Cpanel/RPM/Versions/Pkgr.pm


{ # --- BEGIN Cpanel/Sync/Digest.pm
package Cpanel::Sync::Digest;


use strict;

# use Cpanel::SafeRun::Simple ();

our %digest_algorithms = (
    'md5' => {
        module => 'Digest::MD5',
        ctx    => sub { return Digest::MD5->new() },
        cmd    => 'md5sum',
    },
    'sha512' => {
        module => 'Digest::SHA',
        ctx    => sub { return Digest::SHA->new(512) },
        cmd    => 'sha512sum',
    },
);

for my $algo ( keys %digest_algorithms ) {
    my $module_file = $digest_algorithms{$algo}->{'module'};
    $module_file =~ s/::/\//g;
    $module_file = $module_file . '.pm';

    if ( eval { require $module_file } ) {
        $digest_algorithms{$algo}->{'module_loaded'} = 1;
    }
}

sub digest {
    my ( $file, $opts ) = @_;
    return undef if ( !$file );

    my $algo = $opts->{'algo'} ||= 'md5';
    return undef if ( !exists( $digest_algorithms{$algo} ) );

    if ( $digest_algorithms{$algo}->{'module_loaded'} ) {
        my $ctx = $digest_algorithms{$algo}->{'ctx'}->();

        if ( open( my $ctx_fh, '<', $file ) ) {
            binmode $ctx_fh;
            $ctx->addfile($ctx_fh);
            close($ctx_fh);
            return $ctx->hexdigest();
        }
        else {
            return undef;
        }
    }
    else {
        my $cmd      = $digest_algorithms{$algo}->{'cmd'};
        my $out      = Cpanel::SafeRun::Simple::saferunnoerror( $cmd, $file );
        my ($digest) = $out =~ /^([a-f0-9]+)\s+/;
        return $digest;
    }
}

1;

} # --- END Cpanel/Sync/Digest.pm


{ # --- BEGIN Cpanel/URL.pm
package Cpanel::URL;


sub parse {
    my $url = shift;
    return {} if !$url;

    my ( $host, $uri ) = ( split m{/+}, $url, 3 )[ 1, 2 ];
    $uri = '/' . ( $uri || '' );
    $uri =~ s{[^/]+/+\.\./}{}g;
    $uri =~ s/\.\.//g;
    my ($filename) = $uri =~ m{/([^/]+)$};

    return { 'file' => $filename, 'host' => $host, 'uri' => $uri };
}

1;

} # --- END Cpanel/URL.pm


{ # --- BEGIN Cpanel/OSSys/Env.pm
package Cpanel::OSSys::Env;


use strict;
use warnings;

our $VERSION = 1.0;

sub get_envtype {
    my ($envtype);
    if ( open( my $env_fh, '<', '/var/cpanel/envtype' ) ) {
        $envtype = readline($env_fh);
        close($env_fh);
        chomp($envtype);
    }
    return $envtype || 'standard';
}

1;

} # --- END Cpanel/OSSys/Env.pm


{ # --- BEGIN Cpanel/Sys/Hardware/Memory/Linux.pm
package Cpanel::Sys::Hardware::Memory::Linux;


use strict;

our $meminfo_file = '/proc/meminfo';

sub _format_mib {
    my ($num) = @_;
    return $num ? int( $num / 1024 ) : 'unknown';
}

sub get_installed {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'installed'} );
}

sub get_available {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'available'} );
}

sub get_used {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'used'} - $mem_info->{'buffers'} - $mem_info->{'cached'} );
}

sub get_swap {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'swaptotal'} );
}

sub _load_meminfo {
    my ($self) = @_;
    my %mem_p;

    open( my $bc_fh, '<', $meminfo_file ) or do {
        die "Could not open “$meminfo_file” for reading: $!";
    };

    while ( my $line = <$bc_fh> ) {
        if ( $line =~ /^\s*([^\:]+):\s+(\d+)/ ) {
            $mem_p{ lc($1) } = $2;    #NOTE: Kernel reports usage in KiB.
        }
    }
    close($bc_fh);

    $mem_p{'installed'} = $mem_p{'memtotal'};
    $mem_p{'used'}      = sprintf( '%u', $mem_p{'memtotal'} - $mem_p{'memfree'} );
    $mem_p{'available'} = $mem_p{'memfree'} + $mem_p{'buffers'} + $mem_p{'cached'};

    return \%mem_p;
}

1;

} # --- END Cpanel/Sys/Hardware/Memory/Linux.pm


{ # --- BEGIN Cpanel/Sys/Hardware/Memory/Vzzo.pm
package Cpanel::Sys::Hardware::Memory::Vzzo;


use strict;

our $bean_counters_file = '/proc/user_beancounters';

my $usage_key = 'privvmpages';

sub get_installed {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'installed'} );
}

sub get_available {
    my $mem_info = _load_meminfo();

    return 'unlimited' if ( $mem_info->{'installed'} && _is_unlimited( $mem_info->{'installed'} ) );

    return _format_mib( $mem_info->{'available'} );
}

sub get_used {
    my $mem_info = _load_meminfo();

    return _format_mib( $mem_info->{'used'} );
}

sub get_swap {
    my $mem_info = _load_meminfo('swappages');

    return _format_mib( $mem_info->{'installed'} );
}

sub _format_mib {
    my ($num) = @_;
    return 'unknown' if ( !$num );

    return ( _is_unlimited($num) ) ? 'unlimited' : int( 4 * $num / 1024 );
}

sub _is_unlimited {
    my ($num) = @_;

    return 1 if $num == '9223372036854775807' + 0;
    return 0;
}

sub _load_meminfo {
    my $key = shift;
    $key ||= $usage_key;

    open( my $bc_fh, '<', $bean_counters_file ) or do {
        die "Could not open “$bean_counters_file” for reading: $!";
    };

    my %mem_p;
    while ( my $line = readline($bc_fh) ) {
        next if $line !~ m/^\s*\Q$key\E\s+(.*)/;

        my $parm = $1;
        chomp($parm);
        my ( $held, $maxheld, $barrier, $limit, $failcnt ) = split( /\s+/, $parm );
        last if $held eq '-';

        my $available = ( $barrier - $held );
        $available = 0 if $available < 0;

        $mem_p{'available'} = $available;
        $mem_p{'installed'} = $barrier;
        $mem_p{'used'}      = $held;

        last;
    }
    close($bc_fh);

    return \%mem_p;
}

1;

} # --- END Cpanel/Sys/Hardware/Memory/Vzzo.pm


{ # --- BEGIN Cpanel/Sys/Hardware/Memory.pm
package Cpanel::Sys::Hardware::Memory;


use strict;
use warnings;

# use Cpanel::OSSys::Env                   ();
# use Cpanel::Sys::Hardware::Memory::Linux ();
# use Cpanel::Sys::Hardware::Memory::Vzzo  ();    # PPI USE OK - used by get_module / _dispatch

sub get_module {
    my ($env_type) = @_;
    $env_type ||= Cpanel::OSSys::Env::get_envtype();
    my $module = 'Cpanel::Sys::Hardware::Memory::Linux';
    $module = 'Cpanel::Sys::Hardware::Memory::Vzzo' if ( $env_type eq 'virtuozzo' || $env_type eq 'vzcontainer' );

    return $module;
}

sub _dispatch {
    my ( $func, @args ) = @_;

    my $module = get_module();
    my $call   = $module->can($func) or die "Can’t find function “$func”!";

    my $value = $call->(@args);

    if ( $module eq 'Cpanel::Sys::Hardware::Memory::Vzzo' && $value =~ m/^un/ ) {
        $call  = Cpanel::Sys::Hardware::Memory::Linux->can($func) or die "Can’t find function “Cpanel::Sys::Hardware::Memory::Linux::$func”!";
        $value = $call->(@args);
    }

    return $value;
}

sub get_installed {
    return _dispatch('get_installed');
}

sub get_available {
    return _dispatch('get_available');
}

sub get_used {
    return _dispatch('get_used');
}

sub get_swap {
    return _dispatch('get_swap');
}

1;

} # --- END Cpanel/Sys/Hardware/Memory.pm


{ # --- BEGIN Cpanel/Cpu.pm
package Cpanel::Cpu;


# use Cpanel::Config::LoadCpConf ();

sub getcpucount {
    my $cpunum = get_physical_cpu_count(@_);

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

    $cpunum += $cpconf_ref->{'extracpus'} || 0;

    return $cpunum;
}

our $physical_cpu_count_cache;

sub get_physical_cpu_count {
    return $physical_cpu_count_cache if defined $physical_cpu_count_cache;

    my $cpunum = 1;

    if ( open my $cpuinfo, '<', CPUINFO() ) {
        while ( my $line = readline $cpuinfo ) {
            if ( $line =~ m/^processor\s*:\s*(\d+)/i ) {
                $cpunum = $1;
            }
        }
        close $cpuinfo;
        $cpunum++;
    }
    elsif ( open my $procstat, '<', PROC_STAT() ) {
        while ( my $line = readline $procstat ) {
            if ( $line =~ m/^cpu([0-9]+)/ ) {
                $cpunum = $1;
            }
        }
        close $procstat;
        $cpunum++;
    }

    return $physical_cpu_count_cache = $cpunum;
}

sub CPUINFO   { return '/proc/cpuinfo'; }
sub PROC_STAT { return '/proc/stat'; }
1;

} # --- END Cpanel/Cpu.pm


{ # --- BEGIN Cpanel/Update/Base.pm
package Cpanel::Update::Base;


use strict;
use warnings;


our $VERSION = '1.00';
our $MAX_NUM_SYNC_CHILDREN;                                                                                   # will be calculated below
our $MAX_NUM_SYNC_CHILDREN_WITHOUT_FAST_UPDATE = 1;
our $MAX_NUM_SYNC_CHILDREN_WITH_FAST_UPDATE    = 16;
our $SYNC_CHILD_MAX_MEMORY_NEEDED              = 80;                                                          # In MegaBytes (this has a lot of buffer built in)
our $FAST_UPDATE_NEVER_EVER_FLAG_FILE          = '/var/cpanel/never_ever_use_fast_update_not_even_a_check';


sub calculate_max_sync_children {
    my ($self) = @_;
    require Cpanel::Sys::Hardware::Memory;
    my $available_memory_in_megabytes                   = Cpanel::Sys::Hardware::Memory::get_available();
    my $max_num_of_sync_children_this_system_can_handle = int( ( $available_memory_in_megabytes - $SYNC_CHILD_MAX_MEMORY_NEEDED ) / $SYNC_CHILD_MAX_MEMORY_NEEDED );
    $max_num_of_sync_children_this_system_can_handle = 1 unless $max_num_of_sync_children_this_system_can_handle >= 1;

    my $max_num_client = $self->_get_max_num_client();
    if ( $max_num_of_sync_children_this_system_can_handle > $max_num_client ) {
        $max_num_of_sync_children_this_system_can_handle = $max_num_client;
    }
    $self->logger()->info("Maximum sync children set to $max_num_of_sync_children_this_system_can_handle based on ${available_memory_in_megabytes}M available memory.");
    return $max_num_of_sync_children_this_system_can_handle;
}

sub logger {
    my $self = shift or die;
    return $self->{'logger'};
}

sub _get_max_num_client {
    my ($self) = @_;

    return $MAX_NUM_SYNC_CHILDREN_WITHOUT_FAST_UPDATE unless $self->_can_use_fastupdate();
    return $MAX_NUM_SYNC_CHILDREN if $MAX_NUM_SYNC_CHILDREN;

    require Cpanel::Cpu;
    my $cpu = Cpanel::Cpu::getcpucount();

    $MAX_NUM_SYNC_CHILDREN = 8 * int($cpu);

    $MAX_NUM_SYNC_CHILDREN = 16 if $MAX_NUM_SYNC_CHILDREN > 16;
    return $MAX_NUM_SYNC_CHILDREN;
}

sub _can_use_fastupdate {
    return 1 if ( !-e $FAST_UPDATE_NEVER_EVER_FLAG_FILE );
    return 0;
}

1;

} # --- END Cpanel/Update/Base.pm


{ # --- BEGIN Cpanel/ConfigFiles/RpmVersions.pm
package Cpanel::ConfigFiles::RpmVersions;


use strict;

our $RPM_VERSIONS_FILE         = q{/usr/local/cpanel/etc/rpm.versions};
our $RPM_VERSIONS_SANDBOX_FILE = q{/usr/local/cpanel/build-tools/rpm.versions.sandbox/sandbox.versions};

1;

} # --- END Cpanel/ConfigFiles/RpmVersions.pm


{ # --- BEGIN Cpanel/ArrayFunc/Shuffle.pm
package Cpanel::ArrayFunc::Shuffle;


use strict;
use warnings;


sub shuffle {
    my $element_to_shuffle = scalar @{ $_[0] };
    my $element_to_exchange;
    while ( $element_to_shuffle-- ) {
        $element_to_exchange = int rand( $element_to_shuffle + 1 );
        @{ $_[0] }[ $element_to_shuffle, $element_to_exchange ] = @{ $_[0] }[ $element_to_exchange, $element_to_shuffle ];
    }
    return $_[0];
}
1;

} # --- END Cpanel/ArrayFunc/Shuffle.pm


{ # --- BEGIN Cpanel/Alarm.pm
package Cpanel::Alarm;



use strict;
use warnings;

# use Cpanel::Destruct ();

sub new {
    my $class              = shift or die("Cpanel::Alarm::new is a method call.");
    my $local_alarm_length = shift || 0;
    my $action             = shift;

    my $self = bless( {}, $class );

    $self->{'previous_alarm_time_left'} = $self->set($local_alarm_length);

    $self->{'creation_time'}   = $self->{'local_alarm_start'};
    $self->{'previous_action'} = $SIG{'ALRM'};

    if ( defined $action ) {
        $SIG{'ALRM'} = $action;
    }
    return $self;
}

sub get_length { return shift->{'local_alarm_length'} }

sub set {    ## no critic qw(Unpack)
    $_[0] or die 'Need argument!';
    $_[0]->{'local_alarm_length'} = $_[1];
    $_[0]->{'local_alarm_start'}  = time();

    if ( $_[1] =~ tr<.><> ) {

        require Time::HiRes;
        return Time::HiRes::alarm( $_[1] );
    }

    return alarm( $_[1] );    # This is the total length of the alarm since new()
}

sub get_remaining {
    my $self = shift or die;
    return ( $self->{'local_alarm_length'} - ( time - $self->{'local_alarm_start'} ) );
}

sub DESTROY {
    my $self = shift or return;

    return if Cpanel::Destruct::in_dangerous_global_destruction();

    $SIG{'ALRM'} = $self->{'previous_action'} || 'DEFAULT';

    alarm(0);

    return if ( !$self->{'previous_alarm_time_left'} );

    my $new_alarm = int( $self->{'previous_alarm_time_left'} - ( time() - $self->{'creation_time'} ) );

    ( $new_alarm <= 0 ) ? alarm(1) : alarm($new_alarm);
}

1;

} # --- END Cpanel/Alarm.pm


{ # --- BEGIN Cpanel/SocketIP.pm
package Cpanel::SocketIP;


use strict;
use Socket        ();
# use Cpanel::Alarm ();

our $VERSION = '1.3';

sub _resolveIpAddress {
    my ( $host, %p_options ) = @_;

    return if !$host;

    my $timeout = defined $p_options{'timeout'} && length $p_options{'timeout'} ? $p_options{'timeout'} : undef;

    do { require Carp; Carp::croak("no ipv6 support on perl < 5.14: $]") }
      if $p_options{'ipv6'} && $] < 5.014;

    my @trueaddresses;
    my $alarm;
    my @type = $p_options{'any_proto'} ? () : $p_options{'ipv6'} ? Socket::AF_INET6() : Socket::AF_INET();

    eval {
        $alarm = Cpanel::Alarm->new( $timeout, sub { local $SIG{'__DIE__'}; die; } )
          if $timeout;    # this is not a fatal event so we shouldn't log the die.
        my %seen;
        my @addresses;
        if ( $] < 5.014 ) {
            @addresses = gethostbyname($host);
        }
        else {
            @addresses = Socket::getaddrinfo( $host, @type );
        }
        foreach my $r ( reverse @addresses ) {
            last if !$r;
            my $address;
            if ( ref($r) ne ref( {} ) ) {
                $address = Socket::inet_ntoa($r);
            }
            elsif ( $r->{'family'} == Socket::AF_INET6() ) {
                next if !$p_options{'ipv6'} && !$p_options{'any_proto'};
                $address = Socket::inet_ntop( $r->{'family'}, ( Socket::unpack_sockaddr_in6( $r->{'addr'} ) )[1] );
            }
            elsif ( $r->{'family'} == Socket::AF_INET ) {
                next if $p_options{'ipv6'} && !$p_options{'any_proto'};
                $address = Socket::inet_ntop( $r->{'family'}, ( Socket::unpack_sockaddr_in( $r->{'addr'} ) )[1] );
            }
            next if exists $seen{$address};
            push @trueaddresses, $address;
            $seen{$address} = 1;
        }
    };

    undef $alarm;

    if ( $#trueaddresses == -1 ) {
        return wantarray ? @trueaddresses : 0;
    }
    else {
        return wantarray ? @trueaddresses : $trueaddresses[0];
    }
}

1;

} # --- END Cpanel/SocketIP.pm


{ # --- BEGIN Cpanel/UrlTools.pm
package Cpanel::UrlTools;


use strict;
# use Cpanel::Debug ();

sub urltofile {
    my ($url) = @_;
    my (@URL) = split( /\//, $url );
    return ( $URL[$#URL] );
}

sub buildurlfromuri {
    my ( $rHOSTS, $uri ) = @_;
    if ( substr( $uri, 0, 1 ) ne '/' ) { $uri = '/' . $uri; }
    my (@URLS);
    foreach my $host ( @{$rHOSTS} ) {
        push @URLS, 'http://' . $host . $uri;
    }
    return wantarray ? @URLS : \@URLS;
}

sub extracthosts {
    my ($rURLS) = @_;
    my @HOSTS;
    foreach my $url ( @{$rURLS} ) {
        if ( $url =~ m/https?\:\/\/([^\/]+)\// ) {
            push @HOSTS, $1;
        }
        else {
            Cpanel::Debug::log_warn( 'Invalid URL: ' . $url );
        }
    }
    return wantarray ? @HOSTS : \@HOSTS;
}

sub extract_host_uri {
    my ($url) = @_;
    if ( $url =~ m/https?\:\/\/([^\/]+)(\/.*)/ ) {
        return ( $1, $2 );
    }
    else {
        Cpanel::Debug::log_warn( 'Invalid URL: ' . $url );
    }

    return;
}

1;

} # --- END Cpanel/UrlTools.pm


{ # --- BEGIN Cpanel/Sync/Common.pm
package Cpanel::Sync::Common;



use strict;

our $BZ_OK;
our $BZ_STREAM_END;
our $hasbzip2 = 0;
eval {
    require Compress::Raw::Bzip2;
    $BZ_OK         = Compress::Raw::Bzip2::BZ_OK();
    $BZ_STREAM_END = Compress::Raw::Bzip2::BZ_STREAM_END();
    $hasbzip2      = 1;
};

our $BZIP2_CONSUME_INPUT    = 1;
our $BZIP2_OVERWRITE_OUTPUT = 0;
our $BZIP2_APPEND_OUTPUT    = 1;

our $LZMA_OK;
our $LZMA_STREAM_END;
our $haslzma = 0;
eval {
    require Compress::Raw::Lzma;
    $LZMA_OK         = Compress::Raw::Lzma::LZMA_OK();
    $LZMA_STREAM_END = Compress::Raw::Lzma::LZMA_STREAM_END();
    $haslzma         = 1;
};

our $cpanelsync_excludes       = '/etc/cpanelsync.exclude';
our $cpanelsync_chmod_excludes = '/etc/cpanelsync.no_chmod';

sub unbzip2 {
    my ($file) = @_;

    die "unbzip2 requires a file" if !length $file;
    lstat($file);

    die "$file is a symlink" if -l _;
    die "$file does not exist" unless -e _;
    die "$file is a directory" if -d _;
    die "$file is not a file"  if !-f_;

    my $outfile = $file;
    $outfile =~ s/\.bz2$//;
    return if ( $outfile eq $file );

    die "cannot decompress $file. $outfile is a directory" if -d $outfile;
    unlink $outfile                                        if -e _;

    if ($hasbzip2) {
        my ( $out_fh, $in_fh );
        open( $out_fh, '>', $outfile ) or die("cpanelsync: unbzip2: error opening $outfile for writing: $!");
        open( $in_fh,  '<', $file )    or die("cpanelsync: unbzip2: error opening $file for reading: $!");
        my ( $bzip2,  $err ) = Compress::Raw::Bunzip2->new( $BZIP2_APPEND_OUTPUT, $BZIP2_CONSUME_INPUT );
        my ( $output, $status );
        my $buf = '';

        while ( read( $in_fh, $buf, 65535, length $buf ) ) {    #65535 is about 35% faster then 512
            $status = $bzip2->bzinflate( $buf, $output );
            if ( $status != $BZ_OK && $status != $BZ_STREAM_END ) {
                die "Inflation Error: Failed to decompress $file. bzinflate failed with status: $status";
            }
            print {$out_fh} $output;
            $output = '';
        }
        close($out_fh);
        close($in_fh);
        unlink($file);
    }
    else {
        system( 'bzip2', '-df', $file );
        if ( $? != 0 ) {
            die "Inflation Error: Failed to decompress $file. bzip2 exited with signal: " . ( $? & 127 ) . " and code: " . ( $? >> 8 );
        }
    }
    return 1;
}

sub get_excludes {
    my ($file) = @_;

    return if ( !-e $file || -z _ );

    my @excludes;
    open( EX, '<', $file ) or return;
    while (<EX>) {
        next if m/^\s*$/;
        chomp;
        s!/$!!;
        push @excludes, $_;
    }
    close(EX);

    return @excludes;
}

sub normalize_path {
    my ($path) = @_;
    $path =~ s{/\./}{/}g;
    $path =~ s{//+}{/}g;
    return $path;
}

sub get_digest_from_cache {
    my ( $cache_hr, $file_hr ) = @_;
    return undef if ( !( defined($file_hr) && defined($cache_hr) ) );

    my $path = normalize_path( $file_hr->{'path'} );
    return undef if ( !defined( $cache_hr->{$path} ) );
    return undef if ( !$cache_hr->{$path}->{'md5'} );


    for my $field (qw(size mtime)) {
        return undef if ( !defined( $cache_hr->{$path}->{$field} ) );
        return undef if ( $cache_hr->{$path}->{$field} != $file_hr->{$field} );
    }


    return $cache_hr->{$path}->{'md5'};
}

1;

} # --- END Cpanel/Sync/Common.pm


{ # --- BEGIN Cpanel/URI/Escape/Fast.pm
package Cpanel::URI::Escape::Fast;


use strict;
use warnings;


my %escapes;

BEGIN {
    %escapes = map { chr($_) => sprintf( '%%%02x', $_ ) } ( 0 .. 47, 58 .. 64, 91 .. 94, 96, 123 .. 255 );
}

sub uri_escape {
    return defined $_[0] && $_[0] =~ tr{A-Za-z0-9_.~-}{}c ? ( $_[0] =~ s/([^A-Za-z0-9\-_\.~])/$escapes{$1}/gr ) : $_[0];
}

1;

} # --- END Cpanel/URI/Escape/Fast.pm


{ # --- BEGIN Cpanel/Encoder/URI.pm
package Cpanel::Encoder::URI;


use strict;
use warnings;

BEGIN {
    eval {
        local $SIG{'__DIE__'};
        local $ENV{'PERL_URI_XSESCAPE'} = 0;
        require    # Cpanel::Static OK - optional package
          URI::XSEscape;
    };
    if ($@) {
        require Cpanel::URI::Escape::Fast;
        *uri_encode_str = *Cpanel::URI::Escape::Fast::uri_escape;
        *uri_decode_str = *_uri_decode_str_slow;
    }
    else {
        *uri_encode_str = *_uri_encode_str_fast;
        *uri_decode_str = *_uri_decode_str_fast;
    }

}

our $VERSION = '1.2';

our $URI_SAFE_CHARS = 'A-Za-z0-9\-_.!~*';



sub _uri_encode_str_fast {
    return defined $_[0] ? URI::XSEscape::uri_escape( $_[0] . '' ) : undef;    # force . ''  is to force pOK
}

sub _uri_decode_str_slow {
    return defined $_[0] ? ( ( ( $_[0] =~ tr<+>< >r ) =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/egr ) ) : ();
}

sub _uri_decode_str_fast {
    return defined $_[0] ? URI::XSEscape::uri_unescape( $_[0] =~ tr<+>< >r ) : ();
}

sub uri_decode_str_noform {
    return if !defined $_[0];
    return $_[0] =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/egr;
}

sub uri_encode_dirstr {
    return join( '/', ( map { uri_encode_str($_) } split( m{/}, shift ) ) );
}

1;

} # --- END Cpanel/Encoder/URI.pm


{ # --- BEGIN Cpanel/HttpTimer.pm
package Cpanel::HttpTimer;


use strict;
use warnings;

our $VERSION      = 1.3;
our $MAX_SIZE     = 1024**2;
our $TIMEOUT      = 5;
our $READ_TIMEOUT = 15;

use Socket               ();
# use Cpanel::UrlTools     ();
# use Cpanel::SocketIP     ();
# use Cpanel::IP::Loopback ();
# use Cpanel::TimeHiRes    ();

sub _setupsocket {
    my ( $self, $host, $addr, $port, $quiet ) = @_;

    if ( exists $self->{'httpsocket'}
        && $self->{'httpsocket'} ) {
        close $self->{'httpsocket'};
    }

    my $connected = 0;
    eval {
        local $SIG{'__DIE__'} = 'DEFAULT';

        local $SIG{'PIPE'} = local $SIG{'ALRM'} = sub {
            print STDERR "..Timeout on connect.." unless $quiet;
            die;
        };

        alarm $TIMEOUT;

        my $proto = getprotobyname('tcp') || do {
            print "..Cannot resolve protocol tcp.." unless $quiet;
            die;
        };
        socket( $self->{'httpsocket'}, Socket::AF_INET, Socket::SOCK_STREAM, $proto ) || do {
            print "..Cannot create socket.." unless $quiet;
            die;
        };
        my $iaddr = Socket::inet_aton("$addr") || do {
            print "...Unable to translate IP address for host: ${host}..." unless $quiet;
            die;
        };
        $port ||= getservbyname( 'http', 'tcp' ) || do {
            print "..Cannot lookup port for http.." unless $quiet;
            die;
        };
        my $sin = Socket::sockaddr_in( $port, $iaddr ) || do {
            print "..ERROR: $! .." unless $quiet;
            die;
        };
        connect( $self->{'httpsocket'}, $sin ) || die "Unable to connect: $!";
        alarm 0;
        $connected = 1;
    };
    alarm 0;
    return $connected;
}

sub timedrequest {    ## no critic(Subroutines::ProhibitExcessComplexity)  -- Refactoring this function is a project, not a bug fix
    my (%REQ) = @_;

    my $url = $REQ{'url'};
    my ( $host, $uri ) = Cpanel::UrlTools::extract_host_uri($url);
    unless ( $host && $uri ) {
        print "Unable to extract host and URI from URL: $url\n" if !$REQ{'quiet'};
        return { 'status' => 0, 'speed' => 0 };
    }

    my $self = {};
    bless $self, __PACKAGE__;

    my $addr;
    if ( $host =~ m/(\d+\.\d+\.d\+\d+)/ ) {
        $addr = $host;
    }
    else {
        $addr = Cpanel::SocketIP::_resolveIpAddress($host);
        if ( !$addr ) {
            print "Unable to resolve $host. Check /etc/resolv.conf\n" if !$REQ{'quiet'};
            return { 'status' => 0, 'speed' => 0 };
        }
    }

    if ( exists $REQ{'nolocal'} && Cpanel::IP::Loopback::is_loopback($addr) ) {
        return { 'status' => 0, 'speed' => 0 };
    }

    if ( !$self->_setupsocket( $host, $addr, $REQ{'port'}, $REQ{'quiet'} ) ) {
        return { 'status' => 0, 'speed' => 0 };
    }

    my $filename;
    my $storef_fh;
    if ( $REQ{'store'} ) {
        if   ( !length $REQ{'filename'} ) { $filename = Cpanel::UrlTools::urltofile($uri); }
        else                              { $filename = $REQ{'filename'}; }
        open( $storef_fh, '>', $filename ) || die "Failed to open “$filename” for writing: $!";
    }

    my $bytes      = 0;
    my $start_time = Cpanel::TimeHiRes::time();
    my $buffer     = '';
    eval {
        local $SIG{'__DIE__'} = 'DEFAULT';
        local $SIG{'PIPE'}    = local $SIG{'ALRM'} = sub {
            print STDERR '..Timeout on receive..' if !$REQ{'quiet'};
            die;
        };

        alarm($READ_TIMEOUT);    #set alarm to prevent death
        send $self->{'httpsocket'}, "GET $uri HTTP/1.0\r\nConnection: close\r\nUser-Agent: Cpanel::HttpTimer/$VERSION\r\nHost: $host\r\n\r\n", 0;
        while ( read( $self->{'httpsocket'}, $buffer, 131072, length $buffer ) && length $buffer < $MAX_SIZE ) {
        }
        alarm(0);
    };
    if ($@) {
        print "Error ($@) while fetching url ${url}\n" if !$REQ{'quiet'};
        return { 'status' => 0, 'speed' => 0 };

    }
    $bytes = length $buffer;
    my $end_time = Cpanel::TimeHiRes::time();
    my $telap    = ( $end_time - $start_time );
    $telap ||= 0.00001;    #clock drift
    my $bps = sprintf( "%.2f", ( $bytes / $telap ) );

    my ( $headers, $body ) = split( /\r?\n\r?\n/, $buffer );

    if ( $headers && ( $headers =~ m/SSL-enabled/ || $headers =~ m/location: https:\/\//i ) ) {

    }
    elsif ( $headers && $headers =~ /^HTTP\/\S+\s+(\d+)/ ) {
        my $status = $1;
        if ( $status =~ /^([345]\d+)/ ) {
            print "Error ($status) while fetching url ${url}\n" if !$REQ{'quiet'};
            return { 'status' => 0, 'speed' => 0 };
        }
    }
    else {
        print "Error (no valid headers) while fetching url ${url}\n" if !$REQ{'quiet'};
        return { 'status' => 0, 'speed' => 0 };

    }
    if ( $REQ{'store'} ) {
        print {$storef_fh} $body;
        close($storef_fh);
    }

    if ( $REQ{'return_body'} ) {
        return { 'status' => 1, 'speed' => $bps, 'body' => $body };
    }
    else {
        return { 'status' => 1, 'speed' => $bps };
    }
}

1;

} # --- END Cpanel/HttpTimer.pm


{ # --- BEGIN Cpanel/MirrorSearch.pm
package Cpanel::MirrorSearch;


use strict;

# use Cpanel::HttpTimer ();
use IO::Handle        ();

use Carp ();

our $VERSION = '2.2';

sub remove_mirror {
    my %REQ  = @_;
    my $key  = $REQ{'key'};
    my $addr = $REQ{'addr'};
    $key  =~ s/\///g;
    $addr =~ s/\///g;

    my $homedir = ( getpwuid($>) )[7];
    unlink("$homedir/.MirrorSearch/$key/pingtimes/$addr");
    if ( open( my $mspeeds_fh, '+<', "$homedir/.MirrorSearch/$key/mirrors.speeds" ) ) {
        my @mspeeds = grep( !/^\Q$addr\E=/, <$mspeeds_fh> );
        seek( $mspeeds_fh, 0, 0 );
        print {$mspeeds_fh} join( '', @mspeeds );
        truncate( $mspeeds_fh, tell($mspeeds_fh) );
        close($mspeeds_fh);
    }
}

sub findfastest {
    my (%REQ) = @_;

    my $now     = time();
    my $days    = $REQ{'days'};
    my $key     = $REQ{'key'};
    my $count   = $REQ{'count'};
    my @urls    = @{ $REQ{'urls'} };
    my $urllist = join( "\n", @urls );

    die 'You must specify the number of days to cache a host speed (days)' if ( $days eq '' );
    die 'You must specify a key to use for this host (key)'                if ( $key eq '' );
    die 'You must specify a number of hosts to return (count)'             if ( $count eq '' );
    die 'You must specify an array of urls to try (urls)'                  if ( $urllist eq '' );

    $key =~ s/\///g;

    my %URLS;
    foreach my $url (@urls) {
        if ( $url =~ /(?:ftp|http)\:\/\/([^\/]+)\// ) {
            my $host = $1;
            $URLS{$host} = $url;
        }
        else {
            Carp::confess 'Invalid Url';
        }
    }

    my @GOODURLS = _fetchgoodhosts( $key, $REQ{'port'}, $days, $count, {}, \%URLS, 1, $REQ{'port'} );
    if ( $#GOODURLS >= ( $count - 1 ) ) {

        if ( !$REQ{'quiet'} ) { print "...loaded mirror speeds from cache..."; }
        return @GOODURLS;
    }

    my %PINGTIMES;
    my $homedir = ( getpwuid($>) )[7];

    mkdir $homedir . '/.MirrorSearch',         0700 if !-e $homedir . '/.MirrorSearch';
    mkdir $homedir . '/.MirrorSearch/' . $key, 0700 if !-e $homedir . '/.MirrorSearch/' . $key;

    my $need_pings = 0;
    foreach my $host ( keys %URLS ) {
        my $cache_mtime = ( stat("$homedir/.MirrorSearch/${key}/pingtimes/${host}") )[9] || 0;
        next if ( ( $cache_mtime + ( 86400 * $days ) ) > $now );
        $need_pings++;
        $PINGTIMES{$host} = 1000;    #if ping is broken
    }

    if ($need_pings) {
        local $^F = 1000;            #prevent cloexec on pipe
        my $read_fd  = IO::Handle->new();
        my $write_fd = IO::Handle->new();
        pipe( $read_fd, $write_fd );
        syswrite( $write_fd, $urllist );
        close($write_fd);

        if ( $REQ{'quiet'} ) {
            require Cpanel::SafeRun::Errors;
            Cpanel::SafeRun::Errors::saferunallerrors( '/usr/local/cpanel/scripts/MirrorSearch_pingtest', $key, $days, fileno $read_fd, $REQ{'port'} );
        }
        else {
            print "Testing connection speed for $key ($need_pings servers)...(using fast method)...";
            system '/usr/local/cpanel/scripts/MirrorSearch_pingtest', $key, $days, fileno $read_fd, $REQ{'port'};
            print ".Done\n";
        }
        close($read_fd);
    }

    opendir( PT, "$homedir/.MirrorSearch/${key}/pingtimes" );
    while ( my $pt = readdir(PT) ) {
        next if ( $pt =~ /^\./ );
        open( my $pingtimes_fh, '<', "$homedir/.MirrorSearch/$key/pingtimes/$pt" );
        $PINGTIMES{$pt} = <$pingtimes_fh>;
        chomp $PINGTIMES{$pt};
        close($pingtimes_fh);
    }
    closedir(PT);

    return _fetchgoodhosts( $key, $REQ{'port'}, $days, $count, \%PINGTIMES, \%URLS, 0, $REQ{'quiet'} );
}

sub _fetchgoodhosts {
    my $key       = shift;
    my $port      = shift;
    my $days      = shift;
    my $count     = shift;
    my $PINGTIMES = shift;
    my $URLS      = shift;
    my $cacheonly = shift;
    my $quiet     = shift || 0;

    $key =~ s/\///g;
    my $now = time();
    my %MIRRORSPEED;
    my %MIRRORTIME;
    my @GOODURLS;

    my $homedir = ( getpwuid($>) )[7];
    if ( open my $mirrorspeeds_fh, '<', "$homedir/.MirrorSearch/${key}/mirrors.speeds" ) {
        while (<$mirrorspeeds_fh>) {
            chomp;
            my ( $mirror, $speed, $lastcheck ) = split( /=/, $_ );

            next if ( $lastcheck < ( $now - ( 86400 * $days ) ) );

            $MIRRORTIME{$mirror}  = $lastcheck;
            $MIRRORSPEED{$mirror} = $speed;
        }
        close $mirrorspeeds_fh;
    }
    if ($cacheonly) {
        foreach my $host ( sort { $MIRRORSPEED{$b} <=> $MIRRORSPEED{$a} } keys %MIRRORSPEED ) {
            push( @GOODURLS, $$URLS{$host} ) if $$URLS{$host};
        }
    }
    else {
        my $usable_mirror_count = 0;
        my %URLS_BY_SPEED;
        foreach my $host ( sort { $$PINGTIMES{$a} <=> $$PINGTIMES{$b} } keys %{$PINGTIMES} ) {
            if ( $$URLS{$host} ) {
                if ( !defined $MIRRORSPEED{$host} || $MIRRORSPEED{$host} eq '' ) {
                    print "Ping:$$PINGTIMES{$host} (seconds) " if !$quiet;
                    ( $MIRRORSPEED{$host} ) = _testmirrorspeed( $$URLS{$host}, $quiet, $port );
                    $MIRRORTIME{$host} = $now;
                }

                if ( $MIRRORSPEED{$host} > 1 ) {
                    $URLS_BY_SPEED{ $$URLS{$host} } = $MIRRORSPEED{$host};
                    if ( ++$usable_mirror_count >= $count ) {
                        print "$count usable mirrors located\n" if !$quiet;
                        last;
                    }
                }
            }
        }

        if ( $usable_mirror_count < $count ) { print "...$usable_mirror_count usable mirrors located. (less then expected)..." if !$quiet; }

        @GOODURLS = sort { $URLS_BY_SPEED{$b} <=> $URLS_BY_SPEED{$a} } keys %URLS_BY_SPEED;

        if ($usable_mirror_count) {    # dump the cache so we retry next time around
            if ( open my $mirrorspeeds_fh, '>', "$homedir/.MirrorSearch/${key}/mirrors.speeds" ) {
                foreach my $mirror ( keys %MIRRORSPEED ) {
                    print {$mirrorspeeds_fh} "${mirror}=$MIRRORSPEED{$mirror}=$MIRRORTIME{$mirror}\n";
                }
                close $mirrorspeeds_fh;
            }
            else {
                warn "Unable to write $homedir/.MirrorSearch/${key}/mirrors.speeds: $!";
            }
        }
        else {
            unlink("$homedir/.MirrorSearch/$key/mirrors.speeds");
        }
    }
    return @GOODURLS;
}

sub _testmirrorspeed {
    my ( $url, $quiet, $port ) = @_;

    my ($host) = $url =~ /(?:ftp|http)\:\/\/([^\/]+)\//;

    Carp::confess( 'Invalid Url : ' . $url ) if !$host;

    print "Testing connection speed to $host using pureperl..." if !$quiet;
    my $RES = Cpanel::HttpTimer::timedrequest( 'url' => $url, 'port' => $port, 'nolocal' => 1, 'quiet' => 1 );    # fix hang on mirrors pointing to localhost
    if ( !$RES->{'speed'} ) {
        print "test failed...Done\n" if !$quiet;
        return 0;
    }
    else {
        print "($RES->{'speed'} bytes/s)...Done\n" if !$quiet;
        return $RES->{'speed'};
    }
}

1;

} # --- END Cpanel/MirrorSearch.pm


{ # --- BEGIN Cpanel/Crypt/GPG/VendorKeys/TimestampCache.pm
package Cpanel::Crypt::GPG::VendorKeys::TimestampCache;


use strict;
use warnings;

# use Cpanel::CachedDataStore ();

sub _cache_file {
    return '/var/cpanel/gpg/timestamp.cache';
}

sub new {
    my ($obj) = @_;
    my $self = {};
    bless $self, $obj;

    $self->{'cache'} = _load_cache();

    return $self;
}

sub _load_cache {
    return Cpanel::CachedDataStore::fetch_ref( _cache_file() );
}

sub _save_cache {
    my ($cache_data) = @_;
    return Cpanel::CachedDataStore::savedatastore( _cache_file(), { mode => 0600, data => $cache_data } );
}

sub update_cache {
    my ( $self, %args ) = @_;

    return 0 if !$args{'mirror'} || !$args{'url'};

    $self->{'cache'}->{ $args{'mirror'} }{ $args{'url'} } = { date_downloaded => time, signature_date => $args{'create_time'} };

    return _save_cache( $self->{'cache'} );
}

sub check_cache_for_rollback {
    my ( $self, %args ) = @_;

    my $cached_time = $self->{'cache'}->{ $args{'mirror'} }{ $args{'url'} }{'signature_date'};
    my $new_time    = $args{'create_time'};
    if ( defined $cached_time && $cached_time > $new_time ) {

        return 1;
    }
    else {
        return 0;
    }
}

sub cleanup_signature_cache {
    my ( $self, %args ) = @_;

    my $valid_time_window = exists $args{'valid_time_window'} ? $args{'valid_time_window'} : 7776000;
    my $current_time      = time;

    my $cache = $self->{'cache'};
    foreach my $mirror ( keys %{ $self->{'cache'} } ) {
        foreach my $file ( keys %{ $self->{'cache'}{$mirror} } ) {

            delete $cache->{$mirror}{$file} if $current_time - $self->{'cache'}{$mirror}{$file}{'date_downloaded'} >= $valid_time_window;

        }

        delete $cache->{$mirror} if !scalar keys %{ $cache->{$mirror} };
    }

    return _save_cache($cache);
}

1;

} # --- END Cpanel/Crypt/GPG/VendorKeys/TimestampCache.pm


{ # --- BEGIN Cpanel/Crypt/GPG/VendorKeys/Verify.pm
package Cpanel::Crypt::GPG::VendorKeys::Verify;



use strict;

# use Cpanel::Crypt::GPG::Import::Temp               ();
# use Cpanel::Crypt::GPG::VendorKeys                 ();
# use Cpanel::Crypt::GPG::VendorKeys::TimestampCache ();


sub new {
    my ( $class, %args ) = @_;

    if ( !$args{vendor} ) {
        return _result( undef, "Argument 'vendor' is required." );
    }

    if ( !( $args{category} || $args{categories} ) ) {
        return _result( undef, "Argument 'category' or 'categories' is required." );
    }

    if ( $args{category} && $args{categories} ) {
        return _result( undef, "Both argument 'category' and 'categories' can not be used simultaneously." );
    }

    my $argcat = $args{category} || $args{categories};
    my $keys   = Cpanel::Crypt::GPG::VendorKeys::get_keys( vendor => $args{vendor}, category => $argcat );

    if ( !keys %{$keys} ) {
        return _result( undef, "No keys found for vendor '" . $args{vendor} . "'" );
    }

    my ( $pgp, $msg ) = Cpanel::Crypt::GPG::Import::Temp->new();

    if ( !$pgp ) {
        return _result( undef, $msg );
    }

    for my $key_id ( keys %{$keys} ) {
        my ( $success, $msg ) = $pgp->add_pub_key( key => $keys->{$key_id} );

        if ( !$success ) {
            return _result( undef, "Failed to add key '$key_id' : " . $msg );
        }
    }

    my $obj = {
        vendor     => $args{vendor},
        categories => ( ref($argcat) eq 'ARRAY' ) ? $argcat : [$argcat],
        keys       => $keys,
        pgp        => $pgp,
    };

    bless $obj, $class;

    return _result( $obj, "Success" );
}


sub files {
    my ( $self, %args ) = @_;

    if ( !( $args{sig} || $args{sig_data} ) ) {
        return _result( undef, "Arguments 'sig' or 'sig_data' must be provided." );
    }


    if ( !( $args{files} || defined( $args{files_data} ) ) ) {
        return _result( undef, "Arguments 'files' or 'files_data' must be provided." );
    }

    my ( $s, $m ) = $self->{pgp}->verify(%args);

    if ( !$s ) {
        return _result( $s, $m );
    }

    ( $s, $m ) = _check_filename( $s, $m, \%args );

    if ( !$s ) {
        return _result( $s, $m );
    }

    ( $s, $m ) = _check_rollback( $s, $m, \%args );

    if ( !$s ) {
        return _result( $s, $m );
    }

    $m = "Successfully verified signature for " . $self->{vendor} . " (key types: " . join( ", ", @{ $self->{categories} } ) . ").";
    return _result( $s, $m );
}

sub _check_rollback {
    my ( $sig_data, $message, $args ) = @_;

    my $sig_cache = Cpanel::Crypt::GPG::VendorKeys::TimestampCache->new();

    my $rollback = $sig_cache->check_cache_for_rollback(
        mirror      => $args->{mirror},
        url         => $args->{url},
        create_time => $sig_data->{create_time},
    );

    if ($rollback) {
        return _result( undef, 'Signature rollback detected.' );
    }
    else {
        $sig_cache->update_cache( mirror => $args->{mirror}, url => $args->{url}, create_time => $sig_data->{create_time}, );
        return _result( $sig_data, $message );    # Everything ok, pass data through to next check.
    }
}

sub _check_filename {
    my ( $sig_data, $message, $args ) = @_;

    if ( defined( $sig_data->{'notations'} ) && defined( $sig_data->{'notations'}->{'filename@gpg.notations.cpanel.net'} ) ) {
        my $file_note = $sig_data->{'notations'}->{'filename@gpg.notations.cpanel.net'};

        my $url = $args->{url};
        $url =~ s/\.bz2$//;

        if ( $file_note eq $url ) {
            return _result( $sig_data, $message );    # Everything ok, pass data through to next check.
        }
        else {
            return _result( undef, 'Filename notation (' . $file_note . ') does not match URL (' . $url . ').' );
        }
    }
    else {
        return _result( undef, 'Signature does not contain a filename notation.' );
    }
}

sub _result {
    my ( $success, $message ) = @_;
    return wantarray ? ( $success, $message ) : $success;
}

1;

} # --- END Cpanel/Crypt/GPG/VendorKeys/Verify.pm


{ # --- BEGIN Cpanel/HttpRequest.pm
package Cpanel::HttpRequest;


use strict;
use warnings;

# use Cpanel::ArrayFunc::Shuffle        ();
# use Cpanel::Crypt::GPG::Settings      ();
# use Cpanel::FileUtils::Copy           ();
# use Cpanel::Hostname                  ();
# use Cpanel::Debug                     ();
# use Cpanel::Rand::Get                 ();
# use Cpanel::SocketIP                  ();
# use Cpanel::URL                       ();
# use Cpanel::UrlTools                  ();
# use Cpanel::Encoder::Tiny             ();
# use Cpanel::HTTP::Tiny::FastSSLVerify ();
use Socket                            ();

our $DEFAULT_TIMEOUT       = 260;
our $SIMULATE_FAILURE      = 0;
our $DEBUG                 = 0;
our $VERSION               = '3.0';
our $MAX_CONTENT_SIZE      = ( 1024 * 1024 * 1024 * 1024 );
our $HTTP_RETRY_COUNT      = 12;
our $SIGNATURE_RETRY_COUNT = 4;
our $MAX_RESOLVE_ATTEMPT   = 65;

my $buffer_size         = 131070;
my $has_cpanel_dnsRoots = 0;

sub new {
    my ( $obj, %OPTS ) = @_;

    my $self = bless {}, $obj;

    $self->{'connectedHostAddress'}   = '';                                                                #ip of connected host
    $self->{'connectedHostname'}      = '';                                                                #hostname of connected host
    $self->{'connectedHostFailCount'} = {};
    $self->{'connected'}              = 0;
    $self->{'http_retry_count'}       = $OPTS{'http_retry_count'} || $HTTP_RETRY_COUNT;
    $self->{'use_dns_cache'}          = exists $OPTS{'use_dns_cache'} ? int $OPTS{'use_dns_cache'} : 1;    #on by default
    $self->{'retry_dns'}              = exists $OPTS{'retry_dns'}     ? $OPTS{'retry_dns'}         : 1;
    $self->{'use_mirror_addr_list'}   = $OPTS{'use_mirror_addr_list'} || 0;
    $self->{'hideOutput'}             = $OPTS{'hideOutput'} && $OPTS{'hideOutput'} eq '1' ? 1 : 0;
    $self->{'htmlOutput'}             = $OPTS{'htmlOutput'} || 0;
    $self->{'dns_cache_ttl'}          = exists $OPTS{'dns_cache_ttl'} ? int $OPTS{'dns_cache_ttl'} : 7200;
    $self->{'mirror_search_attempts'} = {};
    $self->{'last_status'}            = undef;
    $self->{'die_on_404'}             = $OPTS{'die_on_404'}      || 0;
    $self->{'die_on_4xx_5xx'}         = $OPTS{'die_on_4xx_5xx'}  || 0;
    $self->{'die_on_error'}           = $OPTS{'die_on_error'}    || 0;
    $self->{'return_on_404'}          = $OPTS{'return_on_404'}   || 0;
    $self->{'return_on_error'}        = $OPTS{'return_on_error'} || 0;
    $self->{'protocol'}               = $OPTS{'protocol'}        || 0;
    $self->{'timeout'}                = $OPTS{'timeout'}         || $DEFAULT_TIMEOUT;
    $self->{'level'}                  = 0;
    $self->{'logger'}                 = $OPTS{'logger'};

    if ( !$self->{'logger'} ) {
        require Cpanel::Logger;
        $self->{'logger'} = Cpanel::Logger->new();
    }
    $self->{'announce_mirror'}       = $OPTS{'announce_mirror'};
    $self->{'signed'}                = $OPTS{'signed'};
    $self->{'vendor'}                = $OPTS{'vendor'}                || 'cpanel';
    $self->{'categories'}            = $OPTS{'categories'}            || Cpanel::Crypt::GPG::Settings::default_key_categories();
    $self->{'signature_validation'}  = $OPTS{'signature_validation'}  || Cpanel::Crypt::GPG::Settings::signature_validation_enabled();
    $self->{'signature_retry_count'} = $OPTS{'signature_retry_count'} || $SIGNATURE_RETRY_COUNT;

    $self->{'speed_test_enabled'} = exists $OPTS{'speed_test_enabled'} ? int( $OPTS{'speed_test_enabled'} ) : 1;
    $self->{'speed_test_file'}    = $OPTS{'speed_test_file'} || '/speedcheck';
    $self->{'sig_data'}           = undef;

    return $self;
}

sub _output {
    my ( $self, $str ) = @_;

    return if $self->{'hideOutput'};

    if ( $self->{'htmlOutput'} ) {
        $str = Cpanel::Encoder::Tiny::safe_html_encode_str($str);
        $str =~ s/\n/<br>/g;
    }

    return print $str;
}

sub request {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $self, %OPTS ) = @_;

    $OPTS{'uncompress'} = 1 if ( defined $OPTS{'uncompress_bzip2'} && length $OPTS{'uncompress_bzip2'} && $OPTS{'url'} =~ m{\.bz2$} );

    my $check_signature = defined $OPTS{'signed'} ? $OPTS{'signed'} : $self->{'signed'};
    my $uncompress      = ( defined $OPTS{'uncompress'} && length $OPTS{'uncompress'} && $OPTS{'uncompress'} && $OPTS{'url'} =~ m/\.(bz2|xz)$/ );


    if ( !$self->{'signature_validation'} ) {
        $check_signature = undef;
    }


    if ( Cpanel::Hostname::gethostname() =~ /^(autobuild|perlcc).*\.dev\.cpanel\.net$/ ) {
        $check_signature = undef;
    }


    if ( !$check_signature ) {
        return $self->_request_file(%OPTS);
    }

    my ( $gpg, $gpg_msg ) = $self->get_crypt_gpg_vendorkey_verify( vendor => $OPTS{'vendor'}, categories => $OPTS{'categories'} );

    if ( !$gpg ) {
        $self->_sigerror_die("Failed to create gpg object: $gpg_msg");
    }


    my $destfile = $OPTS{'destfile'};


    my $file_url = $OPTS{'url'};
    my $signature_url;

    if ( $OPTS{'signature_url'} ) {
        $signature_url = $OPTS{'signature_url'};
    }
    elsif ($destfile) {
        $signature_url = $file_url;

        $signature_url =~ s/\.bz2$//;    # xz files are not signed
        $signature_url = $signature_url . '.asc';
    }
    else {
        $signature_url = $file_url . '.asc';
    }

    my $signature_validation_failures = 0;
    my $signature_hostaddr;
    my $basefile_hostaddr;
    my $verification_data;
    my $verification_message;
    while ( $signature_validation_failures++ < $self->{'signature_retry_count'} ) {


        $OPTS{'url'} = $signature_url;
        delete $OPTS{'destfile'};
        my $signature_data = $self->_request_file(%OPTS);

        if ( !$signature_data ) {
            $self->_die( "Failed to download signature at URL 'http://" . $OPTS{'host'} . $signature_url . "'." );
        }
        $signature_hostaddr = $self->{'connectedHostAddress'};


        if ($destfile) {
            if ( !$uncompress && $destfile =~ /\.(bz2|xz)$/ ) {
                my $compressed_ext = $1;


                my $basename = $destfile;
                $basename =~ s/\.\Q$compressed_ext\E$//;

                my $tmp_file_a = $basename . '_' . Cpanel::Rand::Get::getranddata(8) . ".$compressed_ext";
                my $tmp_file_b = $basename . '_' . Cpanel::Rand::Get::getranddata(8) . ".$compressed_ext";

                $OPTS{'url'}      = $file_url;
                $OPTS{'destfile'} = $tmp_file_a;


                my $req = $self->_request_file(%OPTS);

                if ( !$req ) {
                    $self->_die( "Failed to download file at URL 'http://" . $OPTS{'host'} . $file_url . "'." );
                }
                $basefile_hostaddr = $self->{'connectedHostAddress'};


                my $copy = Cpanel::FileUtils::Copy::safecopy( $tmp_file_a, $tmp_file_b );

                if ( !$copy ) {
                    unlink $tmp_file_a;
                    $self->_die("Failed to make working copy of downloaded file.");
                }

                if ( $compressed_ext eq 'bz2' ) {
                    require Cpanel::Sync::Common;
                    Cpanel::Sync::Common::unbzip2($tmp_file_b);
                    $tmp_file_b =~ s/\.bz2$//;
                }
                elsif ( $compressed_ext eq 'xz' ) {
                    require Cpanel::SafeRun::Simple;
                    Cpanel::SafeRun::Simple::saferun( qw{ unxz -f }, $tmp_file_b )
                      and die "failed to extract '$tmp_file_b': $!";
                }

                ( $verification_data, $verification_message ) = $gpg->files(
                    files    => $tmp_file_b,
                    sig_data => $signature_data,
                    mirror   => $OPTS{'host'},
                    url      => $file_url
                );

                if ($verification_data) {
                    $self->{'logger'}->info($verification_message);
                    $self->{'sig_data'} = $verification_data;
                    unlink $destfile;
                    rename $tmp_file_a, $destfile;
                    unlink $tmp_file_b;
                    return wantarray ? ($req) : $req;
                }
                else {
                    unlink $tmp_file_a;
                    unlink $tmp_file_b;
                }
            }
            else {
                my $tmp_file = $destfile . '_' . Cpanel::Rand::Get::getranddata(8);

                $OPTS{'url'}      = $file_url;
                $OPTS{'destfile'} = $tmp_file;



                my $req = $self->_request_file(%OPTS);

                if ( !$req ) {
                    $self->_die( "Failed to download file at URL 'http://" . $OPTS{'host'} . $file_url . "'." );
                }
                $basefile_hostaddr = $self->{'connectedHostAddress'};

                ( $verification_data, $verification_message ) = $gpg->files(
                    files    => $tmp_file,
                    sig_data => $signature_data,
                    mirror   => $OPTS{'host'},
                    url      => $file_url
                );

                if ($verification_data) {
                    $self->{'logger'}->info($verification_message);
                    $self->{'sig_data'} = $verification_data;
                    unlink $destfile;
                    rename $tmp_file, $destfile;
                    return wantarray ? ($req) : $req;
                }
                else {
                    unlink $tmp_file;
                }
            }
        }
        else {


            $OPTS{'url'} = $file_url;


            my ( $file_data, $complete ) = $self->_request_file(%OPTS);

            if ( !$complete ) {
                $self->_die( "Failed to download URL 'http://" . $OPTS{'host'} . $file_url . "'." );
            }
            $basefile_hostaddr = $self->{'connectedHostAddress'};

            ( $verification_data, $verification_message ) = $gpg->files(
                files_data => $file_data,
                sig_data   => $signature_data,
                mirror     => $OPTS{'host'},
                url        => $file_url
            );

            if ($verification_data) {
                $self->{'logger'}->info($verification_message);
                $self->{'sig_data'} = $verification_data;
                return wantarray ? ( $file_data, $complete ) : $file_data;
            }
        }

        $self->_output("Signature verification failed using file from IP ${basefile_hostaddr} and signature from IP ${signature_hostaddr}");
        if ( $basefile_hostaddr eq $signature_hostaddr ) {
            $self->_skip_failed_mirror();
            $self->disconnect();
        }
        else {
            $self->_output("...retrying ${basefile_hostaddr}...");
        }
        $self->_output("\n");

    }

    $self->_sigerror_die( "Signature verification failed for URL 'http://" . $OPTS{'host'} . $file_url . "'. ${verification_message}" );

    return 1;
}

sub _fetcher {
    my ( $self, $timeout, %params ) = @_;
    my $fetcher = $self->{fetcher};
    return Cpanel::HTTP::Tiny::FastSSLVerify->new( timeout => $timeout, %params ) if !$fetcher || $fetcher->{timeout} != $timeout;
    return $fetcher;
}

sub _request_file {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $self, %OPTS ) = @_;

    my $host             = $OPTS{'host'};
    my $url              = $OPTS{'url'};
    my $destfile         = $OPTS{'destfile'}         || '';
    my $http_retry_count = $OPTS{'http_retry_count'} || $self->{'http_retry_count'};
    my $uncompress       = ( defined $OPTS{'uncompress'} && length $OPTS{'uncompress'} && $OPTS{'uncompress'} && $OPTS{'url'} =~ m/\.(bz2|xz)$/ );
    my $uncompress_ext   = $uncompress ? $1 : undef;

    my $compress_raw_bzip2_obj;
    my $compress_raw_lzma_obj;

    my $fetcher = $self->{fetcher} = $self->_fetcher( $self->{'timeout'} );

    if ($uncompress) {
        require Cpanel::Sync::Common;
        if ( !$Cpanel::Sync::Common::hasbzip2 && $uncompress_ext eq 'bz2' ) {
            $destfile .= '.bz2';
        }
    }
    my $complete = 0;
    my $page     = '';
    my $quiet    = $self->{'hideOutput'} || 0;
    $url =~ tr/\///s;    # squash duplicate "/"

    ( $host, $OPTS{'port'} ) = split /:/, $host, 2 if !defined $OPTS{'port'} && $host =~ tr/://;


    die '[ARGUMENT] a host must be specified at ' . (caller)[0] . ' line ' . (caller)[2] . "\n"
      if !$host;
    die '[ARGUMENT] a URL must be specified at ' . (caller)[0] . ' line ' . (caller)[2] . "\n"
      if !$url;

    print STDERR "[request] $host/$url\n" if $DEBUG;

    $url = "/$url" unless $url =~ m{^/};

    my $full_url = "http://$host" . ( $OPTS{'port'} ? ":$OPTS{'port'}" : "" ) . "$url";

    $self->_output( ( "\t" x $self->{'level'}++ ) . "Fetching $full_url (connected:" . $self->{'connected'} . ')....' );

    my $fh;
    my $addresses = $OPTS{'addresslist'};

    {
        my $httptrycount = 0;

      HTTP_TRY:
        while ( !$complete && $httptrycount < $http_retry_count ) {    # should be < then because we increment in the loop
            ++$httptrycount;
            if ($uncompress) {
                require Cpanel::Sync::Common;
                if ( $Cpanel::Sync::Common::hasbzip2 && $uncompress_ext eq 'bz2' ) {
                    ($compress_raw_bzip2_obj) = Compress::Raw::Bunzip2->new( $Cpanel::Sync::Common::BZIP2_OVERWRITE_OUTPUT, $Cpanel::Sync::Common::BZIP2_CONSUME_INPUT );
                }
                elsif ( $Cpanel::Sync::Common::haslzma && $uncompress_ext eq 'xz' ) {
                    ($compress_raw_lzma_obj) = Compress::Raw::Lzma::StreamDecoder->new();
                }
            }

            $self->_output("...(request attempt $httptrycount/$http_retry_count)...");

            my $method = $OPTS{'method'} || 'GET';
            my %reqargs;
            $reqargs{'headers'} = _convert_headers( $OPTS{'headers'} || {} );
            $reqargs{'content'} = $OPTS{'body'} if $OPTS{'body'};

            if ( length $destfile ) {
                my $callback;
                open( $fh, '>', $destfile ) or die "Can't open file: $!";
                if ($compress_raw_bzip2_obj) {
                    $callback = sub {
                        my $status = $compress_raw_bzip2_obj->bzinflate( $_[0], my $output );
                        if ( $status != $Cpanel::Sync::Common::BZ_OK && $status != $Cpanel::Sync::Common::BZ_STREAM_END || !defined($output) ) {
                            die "Decompressing chunked bzip2 data from $url to $destfile failed: $status";
                        }
                        print {$fh} $output;
                    };
                }
                elsif ($compress_raw_lzma_obj) {
                    $callback = sub {
                        my $status = $compress_raw_lzma_obj->code( $_[0], my $output );
                        if ( $status != $Cpanel::Sync::Common::LZMA_OK && $status != $Cpanel::Sync::Common::LZMA_STREAM_END || !defined($output) ) {
                            die "Decompressing chunked lzma data from $url to $destfile failed: $status";
                        }
                        print {$fh} $output;
                    };
                }
                else {
                    $callback = sub {
                        print {$fh} $_[0];
                    };
                }
                $reqargs{'data_callback'} = $callback;
            }
            else {
                $reqargs{'data_callback'} = sub {
                    $page .= $_[0];
                };
            }

            my $actual_url = $self->_initrequest(
                host         => $host,
                url          => $url,
                port         => $OPTS{'port'},
                headers      => $reqargs{'headers'},
                addresslist  => $OPTS{'addresslist'},
                attempt      => $httptrycount,
                max_attempts => $http_retry_count,
                destfile     => $destfile,
            ) or next HTTP_TRY;

            $reqargs{'peer'} = $self->{'connectedHostAddress'};

            $self->_output('...receiving...');
            my $response = eval { $fetcher->request( $method, $actual_url, \%reqargs ); };
            $response = { status => 599 } if $@;

            if ( $self->{die_on_4xx_5xx} && $response && $response->{status} =~ /^[45]/ ) {
                require Cpanel::Exception;
                die Cpanel::Exception::create(
                    'HTTP::Server',
                    [
                        method  => $method,
                        url     => $actual_url,
                        status  => $response->{status},
                        reason  => $response->{reason},
                        headers => $response->{headers},
                        content => $response->{content},
                    ]
                );
            }

            $complete = ( $response->{status} =~ /^2\d\d$/ ? 1 : 0 );
            my $status   = $self->{last_status} = $response->{status};
            my $httpline = "$status $response->{reason}";

            if ( $response->{status} == 599 ) {
                my $error = $response->{content};
                chomp $error;
                $self->_output("...$error...");
                $self->{'connected'} = 0;
                $self->_skip_failed_mirror();
                next HTTP_TRY;
            }

            if ( $status !~ /^2/ ) {
                $self->_output("Error $status while fetching URL $full_url\n");
                if ( length $destfile ) {
                    close($fh);
                    unlink $destfile;
                }
                $self->{'last_exception'} = "$status - $httpline - HTTP ERROR";
            }

            if ($complete) {
                $self->{'connectedHostFailCount'}{ $self->{'connectedHostAddress'} } = 0;
            }
            else {
                $self->disconnect();
                if ( ++$self->{'connectedHostFailCount'}{ $self->{'connectedHostAddress'} } < 3 ) {
                    $self->_output("...server closed connection (failcount=$self->{'connectedHostFailCount'}{$self->{'connectedHostAddress'}})...");
                    if ( $self->{'last_exception'} && $self->{'last_exception'} =~ m{HTTP ERROR} ) {

                        $self->_skip_failed_mirror();
                    }
                }
                else {
                    $self->_output("...failover...");
                    $self->_remove_failed_mirror();
                }

                if ( $self->{'last_status'} eq '404' && grep { $_->{'die_on_404'} } $self, \%OPTS ) {
                    local $@ = $self->{'last_exception'};
                    die;
                }
                elsif ( $self->{'last_status'} eq '404' && grep { $_->{'return_on_404'} } $self, \%OPTS ) {
                    $self->{'level'}--;
                    return wantarray ? ( '', 0 ) : 0;
                }
                elsif ( $self->{'last_status'} eq '404' && grep { $_->{'exitOn404'} } $self, \%OPTS ) {
                    $self->_output("...Distribution not required.\n");
                    exit;
                }
            }

        }
    }

    if ( !$complete && grep { $_->{'die_on_error'} } $self, \%OPTS ) {
        local $@ = $self->{'last_exception'};
        die;
    }

    $self->_output("...request success...") if $complete;
    $self->_output("...Done\n");

    if ( length $destfile ) {
        close($fh);
        if ( !$uncompress ) {
        }
        elsif ( !$Cpanel::Sync::Common::hasbzip2 && $uncompress_ext eq 'bz2' ) {
            Cpanel::Sync::Common::unbzip2($destfile);
        }
        elsif ( !$Cpanel::Sync::Common::haslzma && $uncompress_ext eq 'xz' ) {
            my $suffix = "__DEFLATE__$$";
            rename $destfile, "$destfile.$suffix.xz"
              or die "Failed to rename temporary file '$destfile' to '$destfile.$suffix.xz': $!";
            require Cpanel::SafeRun::Simple;
            Cpanel::SafeRun::Simple::saferun( 'unxz', '-f', "$destfile.$suffix.xz" )
              and die "Failed to decompress XZ data from '$destfile'";
            rename "$destfile.$suffix", $destfile
              or die "Failed to rename decompressed temporary file '$destfile.$suffix' to '$destfile': $!";
        }
    }

    if ( $complete == 0 ) {
        $self->disconnect();
        $self->{'fetcher'} = $fetcher = undef;
    }
    else {
        $self->{'connected'} = 1;
    }

    $self->{'level'}--;
    if ( length $destfile ) {
        return wantarray ? ($complete) : $complete;
    }
    return wantarray ? ( $page, $complete ) : $page;
}

sub disconnect {
    my ($self) = @_;
    $self->_socket_destroy();
    return $self->{'connected'} = 0;
}

sub make_http_query_string {
    my ($query) = @_;
    return $query unless ref $query;    # If query is a string, return it.

    require Cpanel::Encoder::URI;
    my ( $querystr, $delim, $enckey ) = ( '', '' );
    if ( ref $query eq 'ARRAY' ) {
        if ( @{$query} & 1 ) {
            Cpanel::Debug::log_invalid('Query key with no value.');
            return;
        }
        my $val;

        for ( my $i = 0; $i < $#{$query}; $i += 2 ) {
            ( $enckey, $val ) = ( Cpanel::Encoder::URI::uri_encode_str( $query->[$i] ), $query->[ $i + 1 ] );
            next unless $enckey;    #if we don't have a key, ignore it

            if ( ref $val eq 'ARRAY' ) {

                $querystr .= $delim . join( '&', map { "$enckey=" . ( Cpanel::Encoder::URI::uri_encode_str($_) // '' ) } @{$val} );
            }
            else {
                $querystr .= "$delim$enckey=" . ( Cpanel::Encoder::URI::uri_encode_str($val) // '' );
            }
            $delim ||= '&';
        }
    }
    elsif ( ref $query eq 'HASH' ) {
        foreach my $key ( sort keys %{$query} ) {
            $enckey = Cpanel::Encoder::URI::uri_encode_str($key);
            next unless $enckey;    #if we don't have a key, ignore it

            if ( ref $query->{$key} eq 'ARRAY' ) {

                $querystr .= $delim . join( '&', map { "$enckey=" . ( Cpanel::Encoder::URI::uri_encode_str($_) // '' ) } @{ $query->{$key} } );
            }
            else {
                $querystr .= "$delim$enckey=" . ( Cpanel::Encoder::URI::uri_encode_str( $query->{$key} ) // '' );
            }
            $delim ||= '&';
        }
    }
    else {
        Cpanel::Debug::log_invalid('Unrecognized type for query parameter.');
        return;
    }

    return $querystr;
}

sub http_post_req {
    my ( $self, $args_hr ) = @_;

    require Cpanel::Encoder::URI;
    my $query = $args_hr->{'query'};
    if ( ref $args_hr->{'query'} eq 'HASH' ) {
        $query = '';
        foreach my $key ( keys %{ $args_hr->{'query'} } ) {
            if ( ref $args_hr->{'query'}{$key} eq 'ARRAY' ) {
                for my $val ( @{ $args_hr->{'query'}{$key} } ) {
                    $query .=
                      $query
                      ? "&$key=" . Cpanel::Encoder::URI::uri_encode_str($val)
                      : "$key=" . Cpanel::Encoder::URI::uri_encode_str($val);
                }
            }
            else {
                $query .=
                  $query
                  ? "&$key=" . Cpanel::Encoder::URI::uri_encode_str( $args_hr->{'query'}{$key} )
                  : "$key=" . Cpanel::Encoder::URI::uri_encode_str( $args_hr->{'query'}{$key} );
            }
        }
    }

    my $postdata_len = length($query);

    my $proto = getprotobyname('tcp');
    return unless defined $proto;

    socket( my $socket_fh, &Socket::AF_INET, &Socket::SOCK_STREAM, $proto );
    return unless $socket_fh;

    my $iaddr = gethostbyname( $args_hr->{'host'} );
    my $port  = $self->_socket_default_port();
    return unless ( defined $iaddr && defined $port );

    my $sin = Socket::sockaddr_in( $port, $iaddr );
    return unless defined $sin;

    if ( connect( $socket_fh, $sin ) ) {

        send $socket_fh, "POST /$args_hr->{'uri'} HTTP/1.0\r\nContent-Length: $postdata_len\r\nHost: $args_hr->{'host'}\r\n\r\n$query", 0;

        if ( ref $args_hr->{'output_handler'} eq 'CODE' ) {
            my $in_header = 1;
            while (<$socket_fh>) {
                if ( /^\n$/ || /^\r\n$/ || /^$/ ) {
                    $in_header = 0;
                    next;
                }

                $args_hr->{'output_handler'}->( $_, $in_header );
            }
        }
    }

    close $socket_fh;
    return;
}

sub download {
    my ( $self, $url, $file, $is_signed ) = @_;

    unlink $file if defined $file;
    $is_signed = defined $is_signed ? $is_signed : $self->{'signed'};

    my $parsed_url = Cpanel::URL::parse($url);
    my $res        = $self->request(
        'host'     => $parsed_url->{'host'},
        'url'      => $parsed_url->{'uri'},
        'destfile' => $file,
        'protocol' => 0,
        'method'   => 'GET',
        'signed'   => $is_signed,
    );
    return $res;
}

sub http_request {
    my ( $self, $p_method, $p_host, $p_uri, %p_options ) = @_;


    die '[ARGUMENT] a host must be specified at ' . (caller)[0] . ' line ' . (caller)[2] . "\n"
      if !$p_host;
    die '[ARGUMENT] a URI must be specified at ' . (caller)[0] . ' line ' . (caller)[2] . "\n"
      if !$p_uri;

    my $method = $p_options{'method'} || $p_method;
    die '[ARGUMENT] a method must be specified at ' . (caller)[0] . ' line ' . (caller)[2] . "\n"
      if !$p_method;

    my $content_type = $p_options{'content_type'};

    unlink $p_options{'file'}
      if defined $p_options{'file'};

    my %OPTS = (
        'host'     => $p_host,
        'port'     => $p_options{'port'},
        'url'      => $p_uri,
        'protocol' => 0,
        'method'   => $method,
        'destfile' => $p_options{'file'}
    );

    if ( defined $p_options{'content'} ) {
        $OPTS{'body'} = $p_options{'content'};
        $content_type ||= 'text/plain';
    }

    my %headers;
    %headers = %{ $p_options{'headers'} }
      if ref $p_options{'headers'} eq ref {};
    $headers{'Content-Type'} = $content_type
      if $content_type;
    $OPTS{'headers'} = join( '', map { "$_: $headers{$_}\r\n" } keys %headers )
      if keys %headers;

    return $self->request(%OPTS);
}

sub httpreq {
    my ( $self, $host, $url, $file, %p_options ) = @_;
    return $self->http_request( 'GET', $host, $url, 'file' => $file, %p_options );
}

sub httpput {
    my ( $self, $host, $uri, $content, %p_options ) = @_;
    return $self->http_request( 'PUT', $host, $uri, 'content' => $content, %p_options );
}

sub httppost {
    my ( $self, $host, $url, $qparms, $file, %p_options ) = @_;
    my $content;
    $content = make_http_query_string($qparms)
      if defined $qparms;
    return $self->http_request( 'POST', $host, $url, 'content' => $content, 'content_type' => 'application/x-www-form-urlencoded', 'file' => $file, %p_options );
}

sub skiphost {
    my $self = shift;
    $self->disconnect();
    $self->_remove_failed_mirror();
    return;
}

sub _getAddressList {    ## no critic(Subroutines::ProhibitExcessComplexity)  -- Added with case SEC-398, out of scope for a TSR.
    my ( $self, $host, $port ) = @_;

    print STDERR "[_getAddressList][$host]\n" if $DEBUG;

    my $quiet                 = $self->{'hideOutput'} || 0;
    my $resolve_attempt_count = 1;

    my ( $cache_key, $homedir, @trueaddresses, $loaded_cache );

    if ( $self->{'use_dns_cache'} ) {
        $homedir   = ( getpwuid($>) )[7];
        $cache_key = $host;
        $cache_key =~ s/\///g;

        if ( !-e $homedir . '/.HttpRequest' ) {
            mkdir $homedir . '/.HttpRequest', 0700;
        }
        if ( -e $homedir . '/.HttpRequest/' . $cache_key && ( ( stat(_) )[9] + $self->{'dns_cache_ttl'} ) > time() ) {
            if ( open( my $address_cache_fh, '<', $homedir . '/.HttpRequest/' . $cache_key ) ) {
                local $/;
                @trueaddresses = split( /\n/, readline($address_cache_fh) );
                $loaded_cache  = 1;
                close($address_cache_fh);
                $self->_output("Using dns cache file $homedir/.HttpRequest/$cache_key...");
            }
            else {
                $self->_output("Loading dns cache file $homedir/.HttpRequest/$cache_key failed ($!)...");
            }
        }
    }

    while ( !@trueaddresses ) {
        $loaded_cache = 0;

        $self->_output("Resolving $host...(resolve attempt $resolve_attempt_count/${MAX_RESOLVE_ATTEMPT})...");
        @trueaddresses = Cpanel::SocketIP::_resolveIpAddress($host);
        last if (@trueaddresses);
        $self->_output("Resolving $host using backup method...");
        eval 'require Cpanel::DnsRoots; $has_cpanel_dnsRoots=1'                   if !$has_cpanel_dnsRoots;
        @trueaddresses = 'Cpanel::DnsRoots'->can('resolveIpAddressBAMP')->($host) if $has_cpanel_dnsRoots;
        last                                                                      if ( @trueaddresses || !$self->{'retry_dns'} || $resolve_attempt_count++ >= $MAX_RESOLVE_ATTEMPT );

        $self->_output("Waiting for dns resolution to become available....");
        sleep 1;
    }

    print STDERR "[finished address lookups]\n" if $DEBUG;

    if ($SIMULATE_FAILURE) {
        @trueaddresses = ( '1.1.1.1', '2.2.2.2' );
    }

    Cpanel::ArrayFunc::Shuffle::shuffle( \@trueaddresses );

    if ( !@trueaddresses ) {
        my $errormsg = "$host could not be resolved to an IP address. Please check your /etc/resolv.conf file.\n";
        Cpanel::Debug::log_warn($errormsg);
        if ( $self->{'die_on_error'} ) {
            die $errormsg;
        }
        return wantarray ? () : [];
    }
    elsif ( !$self->{'speed_test_enabled'} ) {
        @trueaddresses = ( $trueaddresses[0] );
    }
    elsif ( @trueaddresses > 1 ) {
        print STDERR "[has resolved, testing]\n" if $DEBUG;
        if ( !$loaded_cache ) {

            if ( $self->{'use_mirror_addr_list'} || $host eq 'httpupdate.cpanel.net' ) {
                $self->_output("\n");
                my $mirror_addr_list = $self->request( 'level' => 1, 'addresslist' => \@trueaddresses, 'host' => $host, 'url' => '/mirror_addr_list', 'protocol' => 1, 'http_retry_count' => 3 );
                my @mirror_addr_list_ADDR_LIST;
                if ($mirror_addr_list) {
                    foreach my $line ( split( /\n/, $mirror_addr_list ) ) {
                        chomp($line);
                        my ($ipaddr) = split( /=/, $line );
                        push @mirror_addr_list_ADDR_LIST, $ipaddr if ( $ipaddr =~ /^[\d\.\:]+$/ );
                    }
                }
                if (@mirror_addr_list_ADDR_LIST) {
                    $self->_output( "...found " . scalar @mirror_addr_list_ADDR_LIST . " host(s) from mirror_addr_list..." );
                    @trueaddresses = @mirror_addr_list_ADDR_LIST;
                }
            }
            if ( $self->{'use_dns_cache'} && @trueaddresses ) {
                if ( open( my $address_cache_fh, '>', $homedir . '/.HttpRequest/' . $cache_key ) ) {
                    print {$address_cache_fh} join( "\n", @trueaddresses );
                    close($address_cache_fh);
                }
            }
        }
        if ( ++$self->{'mirror_search_attempts'}{$host} == 4 ) {    # first time  = loaded from cache
            die "$host did not have any working mirrors.  Please check your internet connection or dns server.";
        }
        $self->_output( "...searching for mirrors (mirror search attempt " . $self->{'mirror_search_attempts'}{$host} . "/3)..." );


        require Cpanel::MirrorSearch;
        my @goodurls = Cpanel::MirrorSearch::findfastest(
            'days'  => ( 2.0 / 24 ),
            'key'   => $host,
            'count' => 10,
            'urls'  => [ Cpanel::UrlTools::buildurlfromuri( \@trueaddresses, $self->{'speed_test_file'} ) ],
            'quiet' => $self->{'htmlOutput'} ? 1 : $quiet,
            'port'  => $port || $self->_socket_default_port()
        );

        if ( @trueaddresses = Cpanel::UrlTools::extracthosts( \@goodurls ) ) {
            $self->_output("...mirror search success...");

            $self->{'mirror_search_attempts'}{$host} = 0;
        }
        else {
            $self->_output("...mirror search failed...");
        }

        if ( !@trueaddresses && $self->{'use_dns_cache'} ) {

            $self->_destroy_ip_cache($host);
        }

    }

    if ($SIMULATE_FAILURE) {
        return wantarray ? () : [];
    }

    return wantarray ? @trueaddresses : \@trueaddresses;
}

sub _remove_failed_mirror {
    my $self = shift;

    my $addr = $self->{'connectedHostAddress'};    #ip of connected host

    print STDERR "[_remove_failed_mirror] $addr\n" if $DEBUG;

    $self->_output("...removing $addr...");

    if ( $self->{'host'} ) {
        @{ $self->{'hostIps'}{ $self->{'host'} } } = grep( !m/^\Q$addr\E$/, @{ $self->{'hostIps'}{ $self->{'host'} } } );
    }
    require Cpanel::MirrorSearch;
    Cpanel::MirrorSearch::remove_mirror( 'key' => $self->{'connectedHostname'}, 'addr' => $addr );

    if ( !$self->{'host'} || !@{ $self->{'hostIps'}{ $self->{'host'} } } && $self->{'use_dns_cache'} ) {

        $self->_destroy_ip_cache();
    }

    return;
}

sub _skip_failed_mirror {
    my $self = shift;

    my $addr = $self->{'connectedHostAddress'};    #ip of connected host

    print STDERR "[_skip_failed_mirror] $addr\n" if $DEBUG;

    $self->_output("...skipping $addr...");

    @{ $self->{'hostIps'}{ $self->{'host'} } } = grep( !m/^\Q$addr\E$/, @{ $self->{'hostIps'}{ $self->{'host'} } } );

    push @{ $self->{'skipped_hostIps'}{ $self->{'host'} } }, $addr;    # if ! grep( !m/^\Q$addr\E$/, @{ $self->{'skipped_hostIps'}{ $self->{'host'} } } );;

    if ( !@{ $self->{'hostIps'}{ $self->{'host'} } } && @{ $self->{'skipped_hostIps'}{ $self->{'host'} } } ) {
        @{ $self->{'hostIps'}{ $self->{'host'} } } = @{ $self->{'skipped_hostIps'}{ $self->{'host'} } };
        $self->{'skipped_hostIps'}{ $self->{'host'} } = [];            # important to clear out this since we moved them to hostIps
    }
    return;
}

sub _destroy_ip_cache {
    my $self      = shift;
    my $cache_key = shift || $self->{'connectedHostname'};
    my $homedir   = ( getpwuid($>) )[7];
    $cache_key =~ s/\///g;
    unlink("$homedir/.HttpRequest/$cache_key");    # Kill the cache if we run out of working hosts so it will rebuild
    return;
}

sub _convert_headers {
    my ($headers) = @_;
    if ( !ref $headers ) {
        my @lines = split /\r\n/, $headers;
        $headers = {};
        foreach my $line (@lines) {
            last unless length $line;
            my ( $key, $value ) = split /:\s*/, $line, 2;
            next unless length $key;
            $headers->{$key} ||= [];
            push @{ $headers->{$key} }, $value;
        }
    }
    return $headers;
}

sub _socket_default_port {
    my $self = shift;
    return ( getservbyname( 'http', 'tcp' ) )[2];
}

sub _socket_destroy {
    my $self = shift;
    delete $self->{'fetcher'};
    return 1;
}

sub _initrequest {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    my ( $self, %OPTS ) = @_;
    $self->{'last_status'} = undef;

    print STDERR "\n\n\n\n[_initrequest]\n" if $DEBUG;

    my $host = $OPTS{'host'};
    $self->{'host'} = $host || die "Host is missing";

    $self->{'hostIps'}{$host}         ||= [];
    $self->{'skipped_hostIps'}{$host} ||= [];

    my $url           = $OPTS{'url'};
    my $http_protocol = $OPTS{'http_protocol'};
    my $destfile      = $OPTS{'destfile'};
    my $headers       = $OPTS{'headers'};
    my $port          = $OPTS{'port'};
    my $method        = $OPTS{'method'} || 'GET';

    $self->{'connected'} = 0 if ( $self->{'connectedHostname'} ne $host );

    my $has_an_addresslist = ( exists $OPTS{'addresslist'} && ref $OPTS{'addresslist'} ) ? 1 : 0;

    if ( ( $self->{'using_addresslist'}{$host} && !$has_an_addresslist ) || ( !$self->{'using_addresslist'}{$host} && $has_an_addresslist ) || $SIMULATE_FAILURE ) {
        delete $self->{'using_addresslist'}{$host};
        $self->{'hostIps'}{$host} = $self->{'skipped_hostIps'}{$host} = [];
        $self->{'connected'}      = 0;                                        # We must also disconnect because we may not be connected
    }

    if ($DEBUG) {
        print STDERR "[about to get ips has_an_addresslist=($has_an_addresslist)]\n";
        my $hostips_defined         = @{ $self->{'hostIps'}{$host} }         ? 1 : 0;
        my $skipped_hostips_defined = @{ $self->{'skipped_hostIps'}{$host} } ? 1 : 0;
        print "[HOSTIPS_DEFINED] $hostips_defined [SKIPPEDHOSTIPS_DEFINED] $skipped_hostips_defined\n";
    }

    if ( !@{ $self->{'hostIps'}{$host} } && !@{ $self->{'skipped_hostIps'}{$host} } ) {
        print STDERR "[...doing address lookup block...]\n" if $DEBUG;
        if ( @{ $self->{'hostIps'}{$host} } = $has_an_addresslist ? @{ $OPTS{'addresslist'} } : $self->_getAddressList( $host, $port ) ) {
            if ($has_an_addresslist) { $self->{'using_addresslist'}{$host} = 1; }
            if ($DEBUG) {
                my $hostips_defined = @{ $self->{'hostIps'}{$host} } ? 1 : 0;
                print STDERR "[....addresslist load or getAddressList ok...] ($hostips_defined)\n";
            }

        }
        else {
            print STDERR "[...failed to resolve $host...]\n" if $DEBUG;

            return;
        }

    }

    print STDERR "[init_req finished populating hostIps]\n" if $DEBUG;

    my $port_suffix = $OPTS{'port'} ? ":$OPTS{'port'}" : "";

    $url =~ s/\s/\%20/g;
    $url ||= '/';

    $headers->{Accept} ||= "text/html, text/plain, audio/mod, image/*, application/msword, application/pdf, application/postscript, text/sgml, */*;q=0.01";

    foreach my $addr ( @{ $self->{'hostIps'}{$host} } ) {
        $self->{'connectedHostAddress'} = $addr;    #must be set before we actually connect() in setupsocket
        $self->{'connectedHostname'}    = $host;
        $self->{'connectedHostFailCount'}{$addr} ||= 0;
        $self->{'connected'} = 1;
        my $local_logger = $self->{'logger'};

        if ( $self->{'announce_mirror'} && ( !defined $self->{'_previous_mirror_used'} || $self->{'_previous_mirror_used'} ne $addr ) ) {
            $self->{'_previous_mirror_used'} = $addr;
            $local_logger->info("Using mirror '${addr}' for host '${host}'.");
        }
        last;
    }
    $self->_output( '@' . $self->{'connectedHostAddress'} . '...' );

    return "http://$host$port_suffix$url";
}

sub _die {
    my ( $self, $msg ) = @_;

    if ( $self->{'logger'}->can('die') ) {
        return $self->{'logger'}->die($msg);
    }
    else {
        die "$msg\n";
    }
}

sub _sigerror_die {
    my ( $self, $msg ) = @_;

    return $self->_die( $msg . ' Please see https://go.cpanel.net/sigerrors for further information about this error.' );
}

sub get_crypt_gpg_vendorkey_verify {
    my ( $self, %opts ) = @_;

    my ( $gpg_vendor, $gpg_category ) = @opts{qw(vendor categories)};
    $gpg_vendor   ||= $self->{'vendor'};
    $gpg_category ||= $self->{'categories'};
    my $key = join( '__', $gpg_vendor, ref $gpg_category ? @$gpg_category : $gpg_category );

    return $self->{'_gpg_verify'}{$key} if $self->{'_gpg_verify'}{$key};

    require Cpanel::Crypt::GPG::VendorKeys::Verify;

    my ( $gpg, $gpg_msg ) = Cpanel::Crypt::GPG::VendorKeys::Verify->new(
        vendor     => $gpg_vendor,
        categories => $gpg_category,
    );

    return ( $gpg, $gpg_msg ) if !$gpg;

    $self->{'_gpg_verify'}{$key} = $gpg;
    return ( $gpg, $gpg_msg );
}

1;

} # --- END Cpanel/HttpRequest.pm


{ # --- BEGIN Cpanel/Services/Running.pm
package Cpanel::Services::Running;


use strict;
use warnings;

# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::SafeRun::Object              ();
# use Cpanel::Autodie                      ();


sub is_online {
    my ($service) = @_;

    Cpanel::Validate::FilesystemNodeName::validate_or_die($service);

    my $restartsrv_binary = "/usr/local/cpanel/scripts/restartsrv_$service";

    if ( !Cpanel::Autodie::exists($restartsrv_binary) ) {
        require Cpanel::Exception;
        die Cpanel::Exception::create( 'Services::Unknown', [ service => $service ] );
    }

    my $run = Cpanel::SafeRun::Object->new(
        'program' => $restartsrv_binary,
        'args'    => ['--check'],
    );

    if ( $run->CHILD_ERROR() && $run->error_code ) {
        return 0;
    }

    return 1;
}

1;

} # --- END Cpanel/Services/Running.pm


{ # --- BEGIN Cpanel/Chdir.pm
package Cpanel::Chdir;



use strict;
use warnings;

use Cwd ();

# use Cpanel::Exception ();
# use Cpanel::Finally   ();

sub new {
    my ( $class, $dir, %options ) = @_;


    if ( !defined $dir ) {
        die Cpanel::Exception::create( 'IO::ChdirError', [ error => "Target directory was not defined.", path => $dir ] );
    }

    my $new_dir = Cwd::abs_path($dir) || die Cpanel::Exception::create( 'IO::ChdirError', [ error => "Failed to find absolute path.",              path => $dir ] );
    my $old_dir = Cwd::getcwd()       || die Cpanel::Exception::create( 'IO::ChdirError', [ error => "Current directory could not be determined.", path => $dir ] );

    my $self = {
        _old_dir => $old_dir,
        _new_dir => $new_dir,
    };
    bless $self, $class;

    _checked_chdir($new_dir);

    $self->{'_finally'} = Cpanel::Finally->new(
        sub {
            my $cur_dir = Cwd::getcwd();

            if ( defined $cur_dir && $cur_dir ne $new_dir ) {
                die "I want to chdir() back to “$old_dir”. I expected the current directory to be “$new_dir”, but it’s actually “$cur_dir”.";
            }

            _checked_chdir( $old_dir, $options{'quiet'} );
        }
    );

    return $self;
}

sub _checked_chdir {
    my ( $to_dir, $quiet ) = @_;

    local ( $!, $^E );
    my $success = chdir($to_dir);
    return if $quiet || $success;
    die Cpanel::Exception::create( 'IO::ChdirError', [ error => $!, path => $to_dir ] );
}

1;

} # --- END Cpanel/Chdir.pm


{ # --- BEGIN Cpanel/SafeRun/Full.pm
package Cpanel::SafeRun::Full;



use strict;

# use Cpanel::Chdir           ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::Env             ();
# use Cpanel::PwCache         ();


sub _get_default_output_hash {
    my %output = ( 'status' => 0, 'message' => '', 'stdout' => '', 'stderr' => '', );
    return wantarray ? %output : \%output;
}

sub _prepare_env {
    my ( $parent_env, $env_hr ) = @_;
    return if ref $parent_env ne 'HASH';

    my %keepers = ( 'HOME', undef, 'USER', undef, 'TMP', undef, 'TEMP', undef );

    if ( ref $env_hr ne 'HASH' || !$env_hr->{'keep'} || ref $env_hr->{'keep'} ne 'ARRAY' ) {
        $env_hr->{'keep'} = [];
    }

    foreach my $extra_keep ( @{ $env_hr->{'keep'} } ) {

        if ( !exists $keepers{$extra_keep} && exists $parent_env->{$extra_keep} ) {
            $ENV{$extra_keep} = $parent_env->{$extra_keep};
        }
    }

    push @{ $env_hr->{'keep'} }, keys %keepers;

    Cpanel::Env::clean_env( %{$env_hr} );
}

sub run {
    my %OPTS   = @_;
    my $output = _get_default_output_hash();

    if ($Cpanel::AccessIds::ReducedPrivileges::PRIVS_REDUCED) {    # PPI NO PARSE --  can't be reduced if the module isn't loaded
        die __PACKAGE__ . " cannot be used with ReducedPrivileges. Use Cpanel::SafeRun::Object instead";
    }

    my ( $user, $homedir ) = ( Cpanel::PwCache::getpwuid_noshadow($>) )[ 0, 7 ];
    if ( !$homedir ) {
        $output->{'message'} = 'Invalid user';
        return $output;
    }
    my %parent_env = %ENV;
    local %ENV;
    $ENV{'HOME'} = $homedir;
    $ENV{'USER'} = $user;
    $ENV{'TMP'}  = $ENV{'TEMP'} = $homedir . '/tmp';
    _prepare_env( \%parent_env, $OPTS{'cleanenv'} );

    my $chdir;
    if ( $OPTS{'chdir'} ) {
        $chdir = Cpanel::Chdir->new( $OPTS{'chdir'} );
    }

    if ( $OPTS{'program'} ) {
        if ( !-e $OPTS{'program'} ) {
            $output->{'message'} = qq<program "$OPTS{'program'}" does not exist>;
            return $output;
        }
        if ( !-x $OPTS{'program'} ) {
            $output->{'message'} = qq<program "$OPTS{'program'}" is not executable>;
            return $output;
        }
    }
    else {
        $output->{'message'} = 'program not specified';
        return $output;
    }

    if ( $OPTS{'args'} ) {
        if ( ref $OPTS{'args'} ne 'ARRAY' ) {
            $output->{'message'} = 'program arguments invalid';
            return $output;
        }
    }
    else {
        $OPTS{'args'} = [];
    }

    my $run;
    {
        local $SIG{'PIPE'} = 'IGNORE' if length $OPTS{'stdin'};
        $run = Cpanel::SafeRun::Object->new(
            'program'  => $OPTS{'program'},
            'args'     => $OPTS{'args'},
            'keep_env' => 1,                  # handled above
            ( length $OPTS{'stdin'} ? ( 'stdin'        => $OPTS{'stdin'} )   : () ),
            ( $OPTS{'timeout'}      ? ( 'timeout'      => $OPTS{'timeout'} ) : () ),
            ( $OPTS{'timeout'}      ? ( 'read_timeout' => $OPTS{'timeout'} ) : () ),
        );
    }

    $? = $run->CHILD_ERROR();    ## no critic qw(Variables::RequireLocalizedPunctuationVars)
    _augment_with_process_status($output);
    $output->{'timeout'} = $run->timed_out();
    $output->{'stderr'}  = $run->stderr();
    $output->{'stdout'}  = $run->stdout();
    $output->{'status'}  = 1;
    $output->{'message'} = 'Executed ' . $OPTS{'program'} . ' ' . join( ' ', @{ $OPTS{'args'} } );
    return $output;
}

sub _augment_with_process_status {
    my ($output) = @_;

    @{$output}{ 'exit_value', 'did_dump_core', 'died_from_signal' } = (
        $? >> 8,
        $? & 0x80,
        $? & 0x7f,
    );

    return $output;
}

1;

} # --- END Cpanel/SafeRun/Full.pm


{ # --- BEGIN Cpanel/Hooks.pm
package Cpanel::Hooks;


use strict;
use warnings;

# use Cpanel::Debug      ();
# use Cpanel::LoadModule ();

our $HOOKS_DB_DIR = '/var/cpanel/hooks';

my $debughooks;
my $MIN_SIZE_FOR_YAML_TO_HAVE_DATA = 6;

our %loaded;


sub is_name_invalid {
    return $_[0] =~ tr{a-zA-Z0-9:_}{}c;
}



sub load_hooks_for {
    my ( $category, $event, $options_hr ) = @_;
    $options_hr = {} if ( !$options_hr || ref $options_hr ne 'HASH' );

    $debughooks = Cpanel::Debug::debug_hooks_value() if !defined($debughooks);

    return [] if ( !$category || !$event || grep { is_name_invalid($_) } ( $category, $event ) );

    if ( ref $loaded{$category} eq 'HASH' && ref $loaded{$category}->{$event} eq 'ARRAY' && scalar @{ $loaded{$category}->{$event} } ) {
        if ( $options_hr->{'filter_id'} ) {
            $options_hr->{'filter_id'} = [ $options_hr->{'filter_id'} ] if ref $options_hr->{'filter_id'} ne 'ARRAY';
            return [
                grep {
                    my $id = '';
                    $id = $_->{'id'} if ( ref $_ eq 'HASH' && $_->{'id'} );
                    grep { defined $_ && "$id" eq "$_" } @{ $options_hr->{'filter_id'} };
                } @{ $loaded{$category}->{$event} }
            ];
        }
        return [ @{ $loaded{$category}->{$event} } ];
    }

    my $hook_file = "$HOOKS_DB_DIR/data/$category/$event.yaml";

    return [] if ( -l $hook_file || !-f _ || ( -s _ || 0 ) < $MIN_SIZE_FOR_YAML_TO_HAVE_DATA );

    require Cpanel::CachedDataStore;
    local $@;
    my $hook_ar = eval { Cpanel::CachedDataStore::loaddatastore($hook_file) };
    Cpanel::Debug::log_warn($@) if $@;
    return []                   if !$hook_ar;

    $loaded{$category} ||= {};
    $loaded{$category}->{$event} = $hook_ar->{'data'};

    if ( $options_hr->{'filter_id'} ) {
        $options_hr->{'filter_id'} = [ $options_hr->{'filter_id'} ] if ref $options_hr->{'filter_id'} ne 'ARRAY';
        return [
            grep {
                my $id = '';
                $id = $_->{'id'} if ( ref $_ eq 'HASH' && $_->{'id'} );
                grep { defined $_ && "$id" eq "$_" } @{ $options_hr->{'filter_id'} };
            } @{ $hook_ar->{'data'} }
        ];
    }
    return [ @{ $hook_ar->{'data'} } ];
}


sub hooks_exist_for_category {
    my ($category) = @_;
    return   if ( !$category || is_name_invalid($category) );
    return 1 if exists( $loaded{$category} );
    my $dir2search = "$HOOKS_DB_DIR/data/$category";

    return scalar(
        scandir(
            'dir'    => $dir2search,
            'first'  => 1,
            'wanted' => sub {
                my ($entry) = @_;

                return if ( substr( $entry, -5 ) ne '.yaml' );
                return if ( ( -s "$dir2search/$entry" || 0 ) < $MIN_SIZE_FOR_YAML_TO_HAVE_DATA );
                return 1;
            }
        )
    );
}

sub scandir {
    my %opts = @_;
    return () if !$opts{'dir'}      || !-d $opts{'dir'};
    opendir( my $dh, $opts{'dir'} ) || return ();

    my @found;
    foreach my $entry ( readdir($dh) ) {

        next if index( $entry, '.' ) == 0;

        if ( $opts{'wanted'}->($entry) ) {
            push @found, $entry;
            return @found if $opts{'first'};
        }
    }
    return @found;
}


sub hook {
    my ( $context, $data ) = @_;
    $data ||= [];

    $data = _filter_data($data);

    my @ran_hooks;
    my @msgs;

    my @hooks2run = _get_hooks_list($context);

    return ( 1, [] ) if !@hooks2run;

    if ( ref $data eq "HASH" ) {
        delete @{$data}{ grep { tr/\r\n\0// } keys %$data };
    }

    foreach my $hook (@hooks2run) {
        next if $hook->{'stage'} ne $context->{'stage'};
        if ( defined $hook->{'disabled'} && $hook->{'disabled'} ) {
            _debug( 'Hook found, but is disabled', undef, $hook, $context ) if $debughooks == 3;
            next;
        }

        my $check_result = 1;
        my $msg;
        my $exec_result = 1;
        eval {
            if ( exists $hook->{'check'} ) {
                ( $check_result, $msg ) = _exec_hook( 'check', $hook, $context, $data );
                next if !$check_result;
            }
            ( $exec_result, $msg ) = _exec_hook( 'main', $hook, $context, $data );
            push @msgs,      $msg  if defined $msg;
            push @ran_hooks, $hook if $exec_result;
        };
        if ( my $err = $@ ) {
            require Cpanel::Exception;
            push @msgs, Cpanel::Exception::get_string($err);
            if ( $err =~ /BAILOUT/ ) {
                Cpanel::Debug::log_warn("An exception was thrown in the hook “$hook->{'hook'}” for “$context->{'category'}::$context->{'event'}”: $msgs[-1]");
                if ( $hook->{'blocking'} || $context->{'blocking'} ) {
                    _exec_rollback( $hook, $context, $data, \@ran_hooks );
                    return 0, \@msgs;
                }
                next;
            }
        }
        if ( ( $hook->{'blocking'} || $context->{'blocking'} ) && !$exec_result ) {
            _exec_rollback( $hook, $context, $data, \@ran_hooks );
            return 0, \@msgs;
        }
    }
    return 1, \@msgs;
}

sub _exec_rollback {
    my ( $hooks, $context, $data, $ran_hooks ) = @_;
    foreach my $hook ( @{$ran_hooks} ) {
        next if !exists $hook->{'rollback'};
        my ($result) = _exec_hook( 'rollback', $hook, $context, $data );
        Cpanel::Debug::log_info( 'rollback hook ' . $hooks->{'rollback'} . ' for ' . $hook->{'hook'} . ' in context ' . $context->{'category'} . '::' . $context->{'event'} . ' returned a non-true status (this may indicate failure)' ) if !$result;
    }
    return 1;
}

sub _get_hooks_list {
    my ($context) = @_;
    return () if ref $context ne 'HASH';

    my ( $category, $event ) = @{$context}{qw( category  event )};
    return () unless $event && $category;

    my $contextual_hook_list;
    {

        local $@;
        $contextual_hook_list = eval { load_hooks_for( $category, $event ) };
    }
    if ( ref $contextual_hook_list eq 'ARRAY' ) {
        if ( $debughooks == 3 ) {
            my $hook_list_contains_context_stage = 0;
            foreach my $hook (@$contextual_hook_list) {
                $hook_list_contains_context_stage++ if $hook->{'stage'} eq $context->{'stage'};
            }
            _debug( "No hooks found for '$context->{'stage'}' stage of context", undef, undef, $context ) if $hook_list_contains_context_stage < 1;
        }
        return @$contextual_hook_list;
    }

    elsif ($contextual_hook_list) {
        Cpanel::Debug::log_warn("Malformed hook list $category:$event - must be an array");
    }

    _debug( 'No hooks found for traversed context', undef, undef, $context ) if $debughooks == 3;
    return ();
}

sub _filter_data {
    my ($data) = @_;

    if ( ref $data eq 'CODE' ) {
        return '<coderef>';
    }
    elsif ( ref $data eq 'ARRAY' ) {
        my @copy = map { _filter_data($_) } @$data;
        return \@copy;
    }
    elsif ( ref $data eq 'HASH' ) {
        my %copy = map { $_ => _filter_data( $data->{$_} ) } keys %$data;
        return \%copy;
    }

    return $data;
}

sub _exec_hook {
    my ( $point, $hook, $context, $data ) = @_;
    my $result = 1;
    my $msg    = undef;
    $context->{'point'} = $point;
    if ( $hook->{'exectype'} eq 'script' ) {
        _debug( 'Beginning execution of script hook.', $point, $hook, $context, $data ) if $debughooks;
        ( $result, $msg ) = _exec_script( $point, $hook, $context, $data );
        _debug( 'Finished execution of script hook.', $point, $hook, $context, $data, $result ) if $debughooks;
    }
    elsif ( $hook->{'exectype'} eq 'module' ) {
        _debug( 'Beginning execution of module hook.', $point, $hook, $context, $data ) if $debughooks;
        ( $result, $msg ) = _exec_module( $point, $hook, $context, $data );
        _debug( 'Finished execution of module hook.', $point, $hook, $context, $data, $result ) if $debughooks;
    }
    else {
        Cpanel::Debug::log_warn( 'invalid hook type called for ' . $context->{'category'} . "::" . $context->{'event'} );
    }
    return $result, $msg;
}

sub _debug {    ## no critic qw(Subroutines::ProhibitManyArgs)
    my ( $msg, $point, $hook, $context, $data, $result ) = @_;
    $hook    ||= '';
    $context ||= {};
    $data    ||= [];
    $result //= 0;
    return if !$debughooks;
    Cpanel::Debug::log_info('---debug_hooks---');
    Cpanel::Debug::log_info( '            msg: ' . $msg );
    Cpanel::Debug::log_info( '        context: ' . $context->{'category'} . '::' . $context->{'event'} );
    Cpanel::Debug::log_info( '          stage: ' . $context->{'stage'} );
    Cpanel::Debug::log_info( '         result: ' . $result ) if defined $result;
    Cpanel::Debug::log_info( '          point: ' . $point )  if defined $point;

    if ( defined $hook && ref $hook eq 'HASH' ) {
        Cpanel::Debug::log_info( '             id: ' . $hook->{'id'} )            if exists $hook->{'id'};
        Cpanel::Debug::log_info( '           hook: ' . $hook->{'hook'} )          if exists $hook->{'hook'};
        Cpanel::Debug::log_info( '  escalateprivs: ' . $hook->{'escalateprivs'} ) if exists $hook->{'escalateprivs'};
        Cpanel::Debug::log_info( '         weight: ' . $hook->{'weight'} )        if exists $hook->{'weight'};
        Cpanel::Debug::log_info( '       rollback: ' . $hook->{'rollback'} )      if exists $hook->{'rollback'};
        Cpanel::Debug::log_info( '          check: ' . $hook->{'check'} )         if exists $hook->{'check'};
    }
    if ( $debughooks > 1 && defined $data ) {
        require Cpanel::JSON;
        Cpanel::Debug::log_info( '           data: ' . Cpanel::JSON::Dump($data) );
    }
    return;
}


sub set_debug {
    return ( $debughooks = $_[0] );
}

sub _exec_script {    ## no critic qw(ProhibitExcessComplexity) # Would rather not introduce more bugs via refactor
    my ( $point, $hook, $context, $data ) = @_;
    my ( $script, @script_args );

    my $hook_name = $point eq 'main' ? 'hook' : $point;
    if ( $point eq 'main' || $point eq 'check' || $point eq 'rollback' ) {
        ( $script, @script_args ) = split( /\s/, $hook->{$hook_name} );
    }
    else {
        Cpanel::Debug::log_warn( 'exec_script was called with an invalid execution point of ' . $point );
        return 0;
    }

    my $input = {
        'hook'    => $hook,
        'context' => $context,
        'data'    => $data,
    };

    my ( $output, $msg );

    if ( $script eq '/usr/local/cpanel/scripts/run_if_exists' && !-e $script_args[0] ) {

        return 1;
    }

    if ( $hook->{'escalateprivs'} && $< != 0 ) {
        if ( $context->{'escalateprivs'} ) {

            Cpanel::LoadModule::load_perl_module('Cpanel::AdminBin');
            require Cpanel::JSON;
            $output = Cpanel::AdminBin::adminstor( 'hooks2', $context->{'category'} . "::" . $context->{'event'}, $input );

            local $@;
            my $decoded = eval { Cpanel::JSON::Load($output) };
            die( $output || $@ ) if $@;
            $output = $decoded;
        }
        else {
            $msg = 'A script hook attempted to escalate privileges when escalation was not permitted in ' . $context->{'category'} . '::' . $context->{'event'} . ' with the script ' . $script;
            Cpanel::Debug::log_info($msg);
            return 0, $msg;
        }
    }
    else {
        require Cpanel::JSON;
        require Cpanel::SafeRun::Full;
        $output = Cpanel::SafeRun::Full::run(
            'program' => $script,
            'stdin'   => Cpanel::JSON::Dump($input),
            'args'    => \@script_args,
        );
    }
    if ( exists $output->{'message'} && $output->{'message'} !~ /Executed / ) {
        Cpanel::Debug::log_warn( $output->{'message'} );
    }
    if ($debughooks) {
        if ( $output->{'stdout'} ne '' ) {
            Cpanel::Debug::log_info( 'STDOUT output from hook: ' . $hook->{'hook'} );
            Cpanel::Debug::log_info( $output->{'stdout'} );
            Cpanel::Debug::log_info('End STDOUT from hook');
        }
        else {
            Cpanel::Debug::log_info( 'HOOK INFO: hook ' . $hook->{'hook'} . ' did not output any data' );
        }
    }

    if ( exists $output->{'stderr'} && $output->{'stderr'} ne '' ) {
        Cpanel::Debug::log_info( 'STDERR output from hook: ' . $hook->{'hook'} );
        Cpanel::Debug::log_info( $output->{'stderr'} );
        Cpanel::Debug::log_info('End STDERR from hook');
    }
    return 1                   if !exists $output->{'stdout'} || $output->{'stdout'} eq '';
    return $output->{'stdout'} if $output->{'stdout'} eq '0'  || $output->{'stdout'} eq '1';
    my $result;
    ( $result, $msg ) = split( ' ', $output->{'stdout'}, 2 );
    if ( $result eq 'BAILOUT' && $point ne 'rollback' ) {
        die "BAILOUT The hook has thrown an exception indicating that it should be halted. " . $msg;
    }
    if ( $result ne 'BAILOUT' && $result ne '0' && $result ne '1' ) {
        Cpanel::Debug::log_info('Script hook returned an invalid response: ');
        Cpanel::Debug::log_info( '   script: ' . $hook->{'hook'} );
        Cpanel::Debug::log_info( ' response: ' . $output->{'stdout'} );
        Cpanel::Debug::log_info(' -- End Garbage output -- ');
    }
    return $result, $msg;
}

sub _exec_module {
    my ( $point, $hook, $context, $data ) = @_;
    my ( $module, $subroutine );

    my $hook_name = $point eq 'main' ? 'hook' : $point;
    if ( $point eq 'main' || $point eq 'check' || $point eq 'rollback' ) {
        ( $module, $subroutine ) = $hook->{$hook_name} =~ /(^[a-zA-Z0-9\:_]+)\:\:([a-zA-Z0-9_]+)$/;
    }
    else {
        Cpanel::Debug::log_warn( 'exec_module was called with an invalid execution point of ' . $point );
        return 0;
    }

    local @INC = ( @INC, '/var/cpanel/perl5/lib' );
    return 1 if !defined $module || !defined $subroutine;
    eval "require $module;";    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)

    if ($@) {
        Cpanel::Debug::log_warn($@);
        return 1;
    }
    my $return = 1;
    my $msg    = undef;
    eval {
        if ( my $cr = $module->can($subroutine) ) {
            ( $return, $msg ) = $cr->( $context, $data );
        }
        else {
            Cpanel::Debug::log_warn("Could not find $subroutine in module $module");
        }
    };
    if ( $@ =~ /BAILOUT/ && $point ne 'rollback' ) {
        die $@;
    }
    Cpanel::Debug::log_warn($@) if $@;
    return $return, $msg;
}


sub hook_halted_msg {
    my ( $hook_info, $hook_msgs ) = @_;


    my $the_hook_abides  = 0;
    my $hook_error_descr = "A hook has halted this operation.\n";
    if ( ref($hook_info) eq 'HASH' ) {
        if ( $hook_info->{'category'} ) {
            $hook_error_descr .= "Category : $hook_info->{'category'}\n";
            $the_hook_abides = 1;
        }
        if ( $hook_info->{'event'} ) {
            $hook_error_descr .= "Event : $hook_info->{'event'}\n";
            $the_hook_abides = 1;
        }
        if ( $hook_info->{'stage'} ) {
            $hook_error_descr .= "Stage : $hook_info->{'stage'}\n";
            $the_hook_abides = 1;
        }
    }

    if ( $the_hook_abides != 1 ) {
        $hook_msgs = $hook_info;
    }

    if ($hook_msgs) {
        if ( ref($hook_msgs) eq 'ARRAY' && @{$hook_msgs} ) {
            return $hook_error_descr . join( "\n", @{$hook_msgs} );
        }
        elsif ( !ref($hook_msgs) && $hook_msgs ) {
            return $hook_error_descr . $hook_msgs;
        }
    }

    return $hook_error_descr;
}

1;

} # --- END Cpanel/Hooks.pm


{ # --- BEGIN Cpanel/RPM/Versions/File.pm
package Cpanel::RPM::Versions::File;


use cPstrict;

use Try::Tiny;

# use Cpanel::Parallelizer              ();
# use Cpanel::Binaries                  ();
# use Cpanel::Config::Sources           ();
# use Cpanel::Crypt::GPG::Settings      ();
# use Cpanel::Exception                 ();
# use Cpanel::FileUtils::Link           ();
# use Cpanel::FileUtils::TouchFile      ();
# use Cpanel::OS                        ();
# use Cpanel::RPM::Versions::Directory  ();
# use Cpanel::RPM::Versions::File::YAML ();
# use Cpanel::RPM::Versions::Pkgr       ();
# use Cpanel::SafeDir::MK               ();
# use Cpanel::SafeRun::Errors           ();
# use Cpanel::Sync::Digest              ();
# use Cpanel::URL                       ();
# use Cpanel::Update::Logger            ();
# use Cpanel::Version                   ();
# use Cpanel::LoadFile                  ();

# use Cpanel::Update::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Update::Base); }

our $install_rpms_in_progress_file = '/var/cpanel/install_rpms_in_progress';

# use Cpanel::ConfigFiles::RpmVersions ();

my $PERL_MAJOR = Cpanel::Binaries::PERL_MAJOR();
my $PHP_MAJOR  = Cpanel::Binaries::PHP_MAJOR();

my %components_to_defer_on_firstinstall = (
    "perl${PERL_MAJOR}-mojolicious"      => 1,
    "perl${PERL_MAJOR}-graph"            => 1,
    "perl${PERL_MAJOR}-git"              => 1,
    "perl${PERL_MAJOR}-cpanel-dev"       => 1,
    "perl${PERL_MAJOR}-export"           => 1,
    "perl${PERL_MAJOR}-tooling"          => 1,
    "perl${PERL_MAJOR}-dav"              => 1,
    "perl${PERL_MAJOR}-oidc"             => 1,
    "perl${PERL_MAJOR}-spamassassin"     => 1,
    "perl${PERL_MAJOR}-backups"          => 1,
    "perl${PERL_MAJOR}-wordpress-plugin" => 1,
    "perl${PERL_MAJOR}-idn"              => 1,
    'cpanel-rrdtool'                     => 1,
);

my %targets_to_defer_on_firstinstall = (
    'horde'                  => 1,
    'p0f'                    => 1,
    'phpmy'                  => 1,
    'git'                    => 1,
    'userinterface'          => 1,
    'userinterface-debug'    => 1,
    'sitepublisher'          => 1,
    'pure-ftpd'              => 1,
    'exim'                   => 1,
    'spamassassin'           => 1,
    'roundcube'              => 1,
    'composer'               => 1,
    'cpanel-deferrable'      => 1,
    'webalizer'              => 1,
    'analog'                 => 1,
    'awstats'                => 1,
    '3rdparty'               => 1,
    "cpanel-php${PHP_MAJOR}" => 1,
);

our $_tailwatchd_was_running_when_rpm_transaction_began;


sub new ( $class, $args = undef ) {

    my $self = $class->init($args);
    bless $self, $class;

    return $self;
}

sub _need_object ($self) {
    $self->isa(__PACKAGE__) or do {
        my @caller = caller(1);
        die("You must call $caller[3] as a method at $caller[1] line $caller[2].\n");
    };
    return;
}

sub obsolete          ( $self, $key = undef ) { return $self->generic_get_method( 'obsolete',          $key ) }
sub unsupported_rpms  ( $self, $key = undef ) { return $self->generic_get_method( 'unsupported_rpms',  $key ) }
sub url_templates     ( $self, $key = undef ) { return $self->generic_get_method( 'url_templates',     $key ) }
sub rpm_groups        ( $self, $key = undef ) { return $self->generic_get_method( 'rpm_groups',        $key ) }
sub srpm_sub_packages ( $self, $key = undef ) { return $self->generic_get_method( 'srpm_sub_packages', $key ) }
sub target_settings   ( $self, $key = undef ) { return $self->generic_get_method( 'target_settings',   $key ) }
sub file_format       ( $self, $key = undef ) { return $self->generic_get_method( 'file_format',       $key ) }
sub location_keys     ( $self, $key = undef ) { return $self->generic_get_method( 'location_keys',     $key ) }

sub rpm_locations ( $self, $key = undef ) {
    my $rpm_locations = $self->generic_get_method( 'rpm_locations', $key ) // {};

    if ( my $srpm_sub_packages = $self->srpm_sub_packages ) {

        foreach my $main_pkg ( sort keys $srpm_sub_packages->%* ) {
            my $location = $rpm_locations->{$main_pkg};
            next unless defined $location;

            foreach my $subpkg ( $srpm_sub_packages->{$main_pkg}->@* ) {
                next if $subpkg eq $main_pkg;
                $rpm_locations->{$subpkg} = $location;
            }
        }
    }

    return $rpm_locations;
}

sub srpm_versions ( $self, $key = undef ) {

    my $srpms_v = $self->generic_get_method( 'srpm_versions', $key );

    return $srpms_v unless ref $srpms_v eq 'HASH';

    foreach my $srpm ( keys $srpms_v->%* ) {
        my $v = $srpms_v->{$srpm};
        next unless $v =~ qr{\.cp\d{3}$}a;    # >= cp108
        $srpms_v->{$srpm} .= Cpanel::OS::package_release_distro_tag();
    }

    if ( my $srpm_sub_packages = $self->srpm_sub_packages ) {

        foreach my $main_pkg ( sort keys $srpm_sub_packages->%* ) {
            my $v = $srpms_v->{$main_pkg};

            if ( !defined $v ) {
                $self->logger->warning("Cannot find version for srpm_sub_packages '$main_pkg'");
                next;
            }

            foreach my $subpkg ( $srpm_sub_packages->{$main_pkg}->@* ) {
                next if $subpkg eq $main_pkg;
                $srpms_v->{$subpkg} = $v;
            }
        }
    }

    return $srpms_v;
}

sub generic_get_method ( $self, $method, $key = undef ) {
    _need_object($self);

    if ($key) {    # Supply from one of the files in rpm.versions.d
        my $value = $self->dir_files()->fetch( { 'section' => $method, 'key' => $key } );

        if ($value) {
            return $value;
        }
        else {     # supply from etc/rpm.versions
            return $self->config_file()->fetch( { 'section' => $method, 'key' => $key } );
        }
    }
    else {

        my $dir_section = $self->dir_files()->fetch( { 'section' => $method } );

        my $config_section = $self->config_file()->fetch( { 'section' => $method } );

        @{$config_section}{ keys %{$dir_section} } = values %{$dir_section};

        return $config_section;
    }
}

sub set_target_settings ( $self, $args ) {

    _need_object($self);

    my $key = $args->{'key'} or return 'No target name passed to set target_settings';
    ref $key eq 'ARRAY'      or return 'No target name array passed to set target_settings';
    scalar @$key == 1        or return 'Unexpected target_settings name (' . join( '.', @$key ) . ') passed to set target_settings';
    my $target = $key->[0]   or return "A target must be passed in order to set target_settings";

    if ( !$self->target_settings->{$target} ) {
        return "Attempted to set unknown target '$target'";
    }

    my $value = $args->{'value'} or return "No value passed to set target_settings.$target";

    unless ( $value =~ m/^((un)?installed|unmanaged)$/ ) {
        return "Unrecoginzed value '$value' set for target '$target'. Supported values are: installed, uninstalled, unmanaged.";
    }

    return $self->generic_set_method( 'target_settings', $args );
}

sub set_srpm_versions ( $self, $args ) {

    _need_object($self);

    my $key = $args->{'key'} or return 'No srpm name passed to set srpm_versions';
    ref $key eq 'ARRAY'      or return 'No srpm name array passed to set srpm_versions';

    scalar @$key == 1 or return 'Unexpected srpm name (' . join( '.', @$key ) . ') passed to set srpm_versions';

    my $srpm = $key->[0] or return "A valid srpm name must be passed in order to set the value of any srpm";

    if ( !$self->srpm_versions->{$srpm} ) {
        return "Attempted to set the version of an unknown srpm '$srpm'";
    }

    return $self->generic_set_method( 'srpm_versions', $args );
}

sub set_obsolete          ( $self, $args ) { return $self->generic_set_method( 'obsolete',          $args ) }
sub set_unsupported_rpms  ( $self, $args ) { return $self->generic_set_method( 'unsupported_rpms',  $args ) }
sub set_url_templates     ( $self, $args ) { return $self->generic_set_method( 'url_templates',     $args ) }
sub set_rpm_groups        ( $self, $args ) { return $self->generic_set_method( 'rpm_groups',        $args ) }
sub set_srpm_sub_packages ( $self, $args ) { return $self->generic_set_method( 'srpm_sub_packages', $args ) }
sub set_rpm_locations     ( $self, $args ) { return $self->generic_set_method( 'rpm_locations',     $args ) }
sub set_location_keys     ( $self, $args ) { return $self->generic_set_method( 'location_keys',     $args ) }
sub set_install_targets   ( $self, $args ) { return $self->generic_set_method( 'install_targets',   $args ) }

sub generic_set_method ( $self, $method, $args ) {
    my $key   = $args->{'key'};
    my $value = $args->{'value'};

    _need_object($self);

    $self->dir_files()->set( { 'section' => $method, 'key' => $key, 'value' => $value } );

    return;
}

sub delete_obsolete          ( $self, $args ) { return $self->generic_delete_method( 'obsolete',          $args ) }
sub delete_unsupported_rpms  ( $self, $args ) { return $self->generic_delete_method( 'unsupported_rpms',  $args ) }
sub delete_url_templates     ( $self, $args ) { return $self->generic_delete_method( 'url_templates',     $args ) }
sub delete_rpm_groups        ( $self, $args ) { return $self->generic_delete_method( 'rpm_groups',        $args ) }
sub delete_srpm_sub_packages ( $self, $args ) { return $self->generic_delete_method( 'srpm_sub_packages', $args ) }
sub delete_srpm_versions     ( $self, $args ) { return $self->generic_delete_method( 'srpm_versions',     $args ) }
sub delete_rpm_locations     ( $self, $args ) { return $self->generic_delete_method( 'rpm_locations',     $args ) }
sub delete_target_settings   ( $self, $args ) { return $self->generic_delete_method( 'target_settings',   $args ) }
sub delete_location_keys     ( $self, $args ) { return $self->generic_delete_method( 'location_keys',     $args ) }
sub delete_install_targets   ( $self, $args ) { return $self->generic_delete_method( 'install_targets',   $args ) }

sub generic_delete_method ( $self, $method, $args ) {
    my $key   = $args->{'key'};
    my $value = $args->{'value'};

    _need_object($self);

    return $self->dir_files()->delete( { 'section' => $method, 'key' => $key, 'value' => $value } );
}

sub init ( $class, $args = undef ) {
    $args ||= {};    # New can be empty.
    die 'New takes a hash reference only.' if ( ref $args ne 'HASH' );

    foreach my $arg ( keys %$args ) {
        die("Unknown parameter: '$arg'") unless ( grep { $_ eq $arg } qw/firstinstall mysql_targets only_targets temp_dir file directory logger rpm_install http_client dir_object pkgr/ );
    }

    if ( $args->{'http_client'} ) {
        $args->{'http_client'}->isa('Cpanel::HttpRequest') or die "http_client must be a Cpanel::HttpRequest";

    }

    die 'The value of only_targets must be an array_ref.' if ( exists $args->{'only_targets'} && ref $args->{'only_targets'} ne 'ARRAY' );

    die 'The value of rpm_install must be an array_ref.' if ( exists $args->{'rpm_install'} && ref $args->{'rpm_install'} ne 'ARRAY' );

    die 'only_targets and rpm_install are mutually exclusive.' if ( exists $args->{'rpm_install'} && exists $args->{'only_targets'} );

    my $file = $args->{'file'}      || $Cpanel::ConfigFiles::RpmVersions::RPM_VERSIONS_FILE;
    my $dir  = $args->{'directory'} || '/var/cpanel/rpm.versions.d';

    $args->{'logger'} ||= Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );

    if ( !-e $file ) {
        die "$file does not exist.\n";
    }

    my @digest_algorithms = Cpanel::Crypt::GPG::Settings::allowed_digest_algorithms();

    my $pkgr = $args->{'pkgr'} || Cpanel::RPM::Versions::Pkgr->new( 'logger' => $args->{'logger'} );
    return {
        'config_file'           => Cpanel::RPM::Versions::File::YAML->new( { file => $file } ),
        'dir_files'             => $args->{'dir_object'} || Cpanel::RPM::Versions::Directory->new( { directory => $dir, 'logger' => $args->{'logger'}, mysql_targets => $args->{'mysql_targets'} } ),
        'only_targets'          => $args->{'only_targets'},
        'rpm_install'           => $args->{'rpm_install'},
        'logger'                => $args->{'logger'},
        'firstinstall'          => $args->{'firstinstall'},
        'temp_dir'              => $args->{'temp_dir'} || '/usr/local/cpanel/tmp/rpm_downloads',
        'digest_algorithms'     => \@digest_algorithms,
        'max_download_attempts' => 5,
        'request'               => $args->{'http_client'},
        'pkgr'                  => $pkgr,
        'packaging'             => $pkgr->{'packaging'},
    };
}

sub pkgr      ($self) { return $self->{'pkgr'} }
sub packaging ($self) { return $self->{'packaging'} }

sub is_rpm ($self) { return $self->{'packaging'} eq 'rpm' ? 1 : 0 }
sub is_deb ($self) { return $self->{'packaging'} eq 'deb' ? 1 : 0 }

sub logger ($self) {
    _need_object($self);

    $self->{logger} //= Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );

    return $self->{logger};
}


sub http_request ($self) {
    _need_object($self);

    return $self->{'request'} if $self->{'request'};

    require Cpanel::HttpRequest;
    $self->{'request'} = Cpanel::HttpRequest->new(
        'retry_dns'  => 0,
        'hideOutput' => 1,
        'logger'     => $self->logger,
    );

    die "Failed to instantiate Cpanel::HttpRequest object." if !$self->{'request'};
    return $self->{'request'};
}

sub cpsources ($self) {
    _need_object($self);

    $self->{'cpsources'} ||= Cpanel::Config::Sources::loadcpsources();
    return $self->{'cpsources'};
}

sub config_file ($self) {
    _need_object($self);

    return $self->{'config_file'};
}

sub dir_files ($self) {
    _need_object($self);

    return $self->{'dir_files'};
}

sub install_targets ( $self, $key, $filter ) {
    _need_object($self);

    die unless $key;

    my $method = 'install_targets';

    if ($key) {
        my $value = $self->dir_files()->fetch( { 'section' => $method, 'key' => $key } );
        if ( !$value ) {
            $value = $self->config_file()->fetch( { 'section' => $method, 'key' => $key } );
        }

        if ( ref $value eq 'HASH' ) {
            my @flat_list;

            my @dependencies;
            if ( ref $value->{'dependencies'} eq 'ARRAY' ) {
                push @dependencies, @{ $value->{'dependencies'} || [] } unless $filter eq 'uninstalled';
            }
            else {
                push @dependencies, $value->{'dependencies'} unless $filter eq 'uninstalled';
            }

            if ( $self->{firstinstall} && @dependencies ) {
                @dependencies = grep { length && !$components_to_defer_on_firstinstall{$_} } @dependencies;
            }

            push @flat_list, @dependencies;

            my @components;
            if ( ref $value->{'components'} eq 'ARRAY' ) {
                push @components, @{ $value->{'components'} || [] };
            }
            else {
                push @components, $value->{'components'};
            }

            if ( $self->{firstinstall} && @components ) {
                @components = grep { length && !$components_to_defer_on_firstinstall{$_} } @components;
            }

            push @flat_list, @components;

            return \@flat_list;
        }
        elsif ( ref $value eq 'ARRAY' ) {
            return $value;
        }
        else {
            return;
        }
    }
    else {
        my $dir_section    = $self->dir_files()->fetch( { 'section' => $method } );
        my $config_section = $self->config_file()->fetch( { 'section' => $method } );

        foreach my $current_key ( keys %{$dir_section} ) {
            $config_section->{$current_key} = $dir_section->{$current_key};
        }

        return $config_section;
    }
}


sub unsupported_rpms_for_this_distro ($self) {
    _need_object($self);

    my $stash  = $self->global_template_stash;
    my $distro = $stash->{'dist'} eq 'ubuntu' ? 'ubuntu' : 'redhat';

    return $self->unsupported_rpms->{ sprintf( "%s%s", $distro, $stash->{'dist_ver'} // '' ) } // [];
}


sub expand_to_srpm_versions_from_target ( $self, $target ) {
    _need_object($self);

    die unless $target;

    my $package_groups      = $self->rpm_groups_cached();
    my $package_group       = $package_groups->{$target} || [$target];
    my $srpm_versions       = $self->srpm_versions_cached();
    my $packages_to_exclude = $self->unsupported_rpms_for_this_distro;

    my $packages_to_return = { map { $srpm_versions->{$_} ? ( $_ => $srpm_versions->{$_} ) : () } @{$package_group} };
    delete $packages_to_return->{$_} foreach @$packages_to_exclude;

    return $packages_to_return;
}


sub expand_target_to_rpms ( $self, $target = undef ) {

    _need_object($self);

    return if !$target;

    my $package_map = $self->expand_to_srpm_versions_from_target($target);

    if ( my $temp_map = $self->find_from_srpm_sub_packages($target) ) {
        @{$package_map}{ keys %$temp_map } = values %$temp_map;
    }

    return $package_map;
}


sub install_hash ( $self, $installed_rpms = undef, $upgraded_rpms = undef ) {

    my $ihash      = $installed_rpms || $self->list_rpms_in_state('installed');
    my $to_install = {};
    foreach my $package ( keys %{$ihash} ) {
        if ( !$self->_is_installed_in_os( $package, $ihash->{$package} ) ) {    # If the Package is already installed in the OS there is no need to reinstall.
            $to_install->{$package} = $ihash->{$package};
        }
    }

    my $uhash = $upgraded_rpms || $self->list_rpms_in_state('upgraded');
    foreach my $package ( keys %{$uhash} ) {
        if ( $self->_is_installed_in_os($package) && !$self->_is_installed_in_os( $package, $uhash->{$package} ) ) {    # Only if the Package is already installed but not up to date.
            $to_install->{$package} = $uhash->{$package};
        }
    }

    $self->{'install_hash'} = $to_install;
    return $to_install;
}


sub uninstall_hash ( $self, $installed_rpms = undef, $uninstalled_rpms = undef ) {
    _need_object($self);

    my $ulist = $uninstalled_rpms || $self->list_rpms_in_state('uninstalled');

    my $ilist = $installed_rpms || $self->list_rpms_in_state("installed");

    my $to_uninstall = {};

    foreach my $package ( keys %{$ulist} ) {
        if ( !exists $ilist->{$package} && $self->_is_installed_in_os($package) ) {    # Don't uninstall if the Package is found in
            $to_uninstall->{$package} = $ulist->{$package};                            # the list of things to be installed
        }
    }

    my $obsolete_rpms = $self->obsolete;
    foreach my $package ( keys %{$obsolete_rpms} ) {
        if ( !exists $ilist->{$package} && $self->_is_installed_in_os($package) ) {    # Don't uninstall if the Package is found in
            $to_uninstall->{$package} = q[obsolete];                                   # the list of things to be installed
        }
    }

    return $to_uninstall;
}

sub list_rpms_in_state ( $self, $filter = 'installed' ) {

    _need_object($self);

    my @targets = $self->get_all_targets_in_state($filter) or return {};

    if ( $self->{firstinstall} && @targets ) {
        @targets = grep { length && !$targets_to_defer_on_firstinstall{$_} } @targets;
    }

    if ( $self->{'only_targets'} ) {

        my @only_targets_in_state;
        foreach my $target ( @{ $self->{'only_targets'} } ) {
            push @only_targets_in_state, $target if ( grep { $_ eq $target } @targets );
        }
        @targets = @only_targets_in_state;
    }

    my %packages;
    if ( $self->{'rpm_install'} ) {
        my $srpm_versions = $self->srpm_versions_cached();    # already expanded
        foreach my $target ( @{ $self->{'rpm_install'} } ) {
            if ( defined $srpm_versions->{$target} ) {
                $packages{$target} = $srpm_versions->{$target};
            }
        }

        return \%packages;
    }

    foreach my $target (@targets) {

        my $modules = $self->install_targets( $target, $filter ) // [];
        push @$modules, $target unless scalar @$modules;

        foreach my $module ( @{$modules} ) {
            foreach my $sub_target ( $self->expand_target_to_rpms($module) ) {
                @packages{ keys %{$sub_target} } = values %{$sub_target};
            }
        }
    }

    return \%packages;
}


sub get_template_name ( $self, $package ) {
    die unless $package;

    my $location = $self->rpm_locations_cached()->{$package};
    $location //= 'default';

    my $packaging_system = $self->packaging;

    $location = "${packaging_system}_${location}" if $packaging_system ne 'rpm';

    return $location;
}


sub global_template_stash ($self) {

    return { $self->{'template_stash'}->%* } if ref $self->{'template_stash'};

    $self->{'template_stash'} = {
        'httpupdate' => $self->cpsources->{'HTTPUPDATE'},
        'lts'        => Cpanel::Version::get_lts(),
        'dist'       => Cpanel::OS::rpm_versions_system(),
        'dist_ver'   => Cpanel::OS::major(),                 ## no critic(Cpanel::CpanelOS) rpm.versions template
        'arch'       => Cpanel::OS::packages_arch(),
    };

    if ( $self->is_rpm ) {
        $self->{'template_stash'}->{'rpm_dist'}     = $self->{'template_stash'}->{'dist'};
        $self->{'template_stash'}->{'rpm_dist_ver'} = $self->{'template_stash'}->{'dist_ver'};
        $self->{'template_stash'}->{'rpm_arch'}     = $self->{'template_stash'}->{'arch'};
    }

    return { $self->{'template_stash'}->%* };
}

sub package_to_source ( $self, $package ) {
    return $self->{'pkg_to_source_map'}->{$package} || $package if $self->{'pkg_to_source_map'};

    my $subs = $self->srpm_sub_packages;
    foreach my $source_package ( keys %$subs ) {
        foreach my $sub_package ( $subs->{$source_package}->@* ) {
            $self->{'pkg_to_source_map'}->{$sub_package} = $source_package;
        }
    }

    return $self->{'pkg_to_source_map'}->{$package} || $package;
}


sub url ( $self, $package, $version ) {
    _need_object($self);

    $package or die;
    $version or die("No version provided for $package");

    my $template_name = $self->get_template_name($package);

    my $url_template = $self->url_templates_cached($template_name) or die("The Package '$package-$version' does not have a valid URL template '$template_name'");    ###doc###

    my ( $package_version, $package_revision ) = split /-/, $version, 2;


    my $lowest_cpanel_version_supported = 'unknown';
    if ( defined $package_revision ) {
        if ( $package_revision =~ m/cp(\d{3})(?:~.+)?$/a ) {    # we drop the 11 in cp11 starting with cp108
            $lowest_cpanel_version_supported = "11.$1";
        }
        elsif ( $package_revision =~ m/cp11(\d+)$/a ) {
            $lowest_cpanel_version_supported = "11.$1";
        }
    }
    my $source_package = $self->package_to_source($package);

    my $vars = {
        $self->global_template_stash->%*,
        'source_package'                  => $source_package,
        'package'                         => $package,
        'package_version'                 => $package_version,
        'package_revision'                => $package_revision,
        'lowest_cpanel_version_supported' => $lowest_cpanel_version_supported,
    };

    my $output = process_template( $url_template, $vars );

    return $output;
}

sub process_template ( $template = undef, $vars = undef ) {
    return $template if !$template;
    return $template unless $vars && ref $vars eq 'HASH';
    return $template =~ s{\[\%\s+(\S+)\s+\%\]}{length $vars->{$1} ? $vars->{$1} : ''}msger;
}

sub download ( $self, $url, $dest_file, $opts = do { {} } ) {

    return { 'status' => 0, 'file' => $dest_file } unless ( $url && $dest_file );

    my $res;
    $self->logger->info("Downloading $url") unless $self->{'did_preinstall'};    # Don't say this if we already did a first download pass.

    my $parsed_url = Cpanel::URL::parse($url);

    my %request_opts = (
        'host'       => $parsed_url->{'host'},
        'url'        => $parsed_url->{'uri'},
        'destfile'   => $dest_file,
        'protocol'   => 0,
        'method'     => 'GET',
        'signed'     => $opts->{'signed'},
        'vendor'     => $opts->{'vendor'},
        'categories' => $opts->{'categories'},
    );

    local $@;
    eval {
        $res = $self->http_request()->request(%request_opts);
        -e $dest_file or die("Could not download '$url' to '$dest_file'");
        -z _ and die("Tried to download '$url' to '$dest_file' but the file is zero bytes");
    };

    if ($@) {
        my $err = $@;

        if ( $opts->{'no_die_on_error'} ) {
            $self->logger->warning($err);
        }
        else {
            $self->logger->fatal($err);
            die $err;
        }
    }

    $self->{'files_downloaded'} ||= [];
    push @{ $self->{'files_downloaded'} }, $dest_file;

    return { 'status' => $res, 'file' => $dest_file };
}

sub stage_digests ( $self, $download_hash, $algorithm, $opts_ref = do { {} } ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    die unless $download_hash;
    die unless $algorithm;

    my $temp_dir = $self->{'temp_dir'};
    unlink( glob( $temp_dir . '/*.' . $algorithm ) );

    my @downloads;

    my %digests;
    my %download_queued;
    for my $package ( sort keys %{$download_hash} ) {
        my $url      = $download_hash->{$package}->{url};
        my $location = $download_hash->{$package}->{location};

        my $dest_file = $url;
        $dest_file =~ s{^[^\/]+:\/\/}{};    # Strip https?://

        if ( $self->is_deb ) {
            $dest_file =~ s{(/pool/).+}{/pool};
            $url       =~ s{(/pool/).+}{/pool};
        }

        $dest_file =~ s{/}{_}g;             # Replace / with _
        $dest_file = $temp_dir . '/' . $dest_file . '.' . $algorithm;
        next if $download_queued{$dest_file};

        my $download_url = $url . '/' . $algorithm;
        my $location_key = $self->location_keys()->{$location};

        my $vendor     = $location_key->{vendor};
        my $categories = $location_key->{categories};
        my $signed     = $location_key->{disable_signatures} ? 0 : 1;

        if ($signed) {

            $self->http_request()->get_crypt_gpg_vendorkey_verify( vendor => $vendor, categories => $categories );
        }

        $download_queued{$dest_file} = 1;
        push @downloads,
          {
            'dest_file'    => $dest_file,
            'download_url' => $download_url,
            'url'          => $url,
            'opts'         => { signed => $signed, vendor => $vendor, categories => $categories, no_die_on_error => 1 }
          };
    }

    if (@downloads) {
        my $process_limit = $opts_ref->{'max_sync_children'} ||= $self->calculate_max_sync_children();
        my $parallelizer  = Cpanel::Parallelizer->new( 'process_limit' => $process_limit, 'keep_stdout_open' => 1 );

        my $files_to_download_per_process = $parallelizer->get_operations_per_process( scalar @downloads );


        my $on_return = sub ($rets) {
            foreach my $download (@$rets) {
                my ( $dest_file, $url, $res ) = @{$download}{qw(dest_file url res)};
                if ( $res->{'status'} ) {
                    $digests{$url} = $res->{'file'};
                }
            }
            return;
        };

        while ( my @download_chunk = splice( @downloads, 0, $files_to_download_per_process ) ) {
            my $urls = join( ',', map { $_->{'download_url'} } @download_chunk );
            $parallelizer->queue(
                sub ( $self, @downloads ) {
                    my @ret;
                    foreach my $download_ref (@downloads) {
                        my $res = $self->download( $download_ref->{'download_url'}, $download_ref->{'dest_file'}, $download_ref->{'opts'} );
                        push @ret, { 'dest_file' => $download_ref->{'dest_file'}, 'url' => $download_ref->{'url'}, 'res' => $res };
                    }
                    return \@ret;
                },
                [ $self, @download_chunk ],
                $on_return,
                sub { warn "Parallelizer error ($urls): @_" },
            );
        }

        $parallelizer->run();
    }

    return \%digests;
}

sub init_digests ( $self, $digest_urls ) {

    die unless $digest_urls;
    my %digests;

    for my $url ( keys %{$digest_urls} ) {
        my $digest_file = $digest_urls->{$url};

        if ( !-e $digest_file ) {

            next;
        }

        $digests{$url} = { ( map { ( split( /\s+/, $_, 2 ) )[ 1, 0 ] } split( m{\n}, Cpanel::LoadFile::load($digest_file) ) ) };
    }

    return \%digests;
}

sub download_hash ($self) {
    my %download_hash;
    foreach my $package_hash ( $self->install_hash() ) {
        foreach my $package ( keys %{$package_hash} ) {
            my $url          = $self->url( $package, $package_hash->{$package} );
            my $package_file = $self->_get_rpm_name($url);
            my $location     = $self->get_template_name($package);
            $url =~ s/\/$//;
            $url =~ s/\/[^\/]+$//;
            $download_hash{$package_file} = { url => $url, location => $location };
        }
    }

    return \%download_hash;
}

sub download_all ( $self, %opts ) {
    my $temp_dir = $self->{'temp_dir'} or die q[No temp_dir set for download_all];
    -d '/usr/local/cpanel/tmp'         or Cpanel::SafeDir::MK::safemkdir( '/usr/local/cpanel/tmp', '0700', 2 );
    -d $temp_dir                       or Cpanel::SafeDir::MK::safemkdir( $temp_dir,               '0700', 2 );

    my $download_hash = $self->download_hash();

    return [] if !scalar keys %$download_hash;

    my %digest_files;
    my %package_digests;

    for my $alg ( @{ $self->{'digest_algorithms'} } ) {
        $digest_files{$alg}    = $self->stage_digests( $download_hash, $alg, \%opts );
        $package_digests{$alg} = $self->init_digests( $digest_files{$alg} );
    }

    my @packages;

    my @downloads;
    my $process_limit = $opts{'max_sync_children'} ||= $self->calculate_max_sync_children();
    my $parallelizer  = Cpanel::Parallelizer->new( 'process_limit' => $process_limit, 'keep_stdout_open' => 1 );
    my $on_return     = sub (@processed) {
        push @packages, @processed;
        return;
    };

  RPM:
    for my $package_file ( keys %$download_hash ) {

        my $download_to = $temp_dir . '/' . $package_file;
        my %expected_digests;

        my $digest_package_file;
        for my $alg ( @{ $self->{'digest_algorithms'} } ) {

            my $digest_url = $download_hash->{$package_file}->{url};
            $digest_package_file = $package_file;
            if ( $self->is_deb ) {
                $digest_url =~ s{(/pool/)(.+)}{/pool};    # Debian digests are all in one file.
                $digest_package_file = "$2/$digest_package_file";
            }

            my $digest = $package_digests{$alg}->{$digest_url}->{$digest_package_file};

            if ($digest) {
                $expected_digests{$alg} = $digest;
            }
        }

        unless ( keys %expected_digests ) {
            my $err = "No digest data for $digest_package_file";
            $self->logger->fatal($err);
            die $err;
        }

        if ( -e $download_to ) {
            for my $alg ( @{ $self->{'digest_algorithms'} } ) {
                my $digest = Cpanel::Sync::Digest::digest( $download_to, { algo => $alg } );

                if ( defined($digest) && ( $digest eq $expected_digests{$alg} ) ) {
                    $self->logger->info("$package_file already downloaded") unless $self->{'did_preinstall'};    # Don't say this if we already did a first download pass.
                    push @packages, $package_file;
                    next RPM;
                }
            }
        }

        my $url = $download_hash->{$package_file}->{url} . '/' . $package_file;

        push @downloads, { 'rpm_file' => $package_file, 'url' => $url, 'download_to' => $download_to, 'expected_digests_hr' => \%expected_digests };
    }

    if (@downloads) {
        my $files_to_download_per_process = $parallelizer->get_operations_per_process( scalar @downloads );

        while ( my @download_chunk = splice( @downloads, 0, $files_to_download_per_process ) ) {
            my $urls = join( ',', map { $_->{'url'} } @download_chunk );
            $parallelizer->queue(
                \&_download_pkgs,
                [ $self, \@download_chunk ],
                $on_return,
                sub { warn "Parallelizer error ($urls): @_" },
            );
        }

        $parallelizer->run();
    }

    return \@packages;
}

sub _download_pkgs ( $self, $packages_ar ) {
    _need_object($self);

    my @complete;
    my $logger = $self->logger();
    foreach my $package (@$packages_ar) {
        my ( $package_file, $url, $download_to, $expected_digests_hr ) = @{$package}{qw(rpm_file url download_to expected_digests_hr)};
        my $err;
      ATTEMPT:
        for my $attempt ( 1 .. $self->{'max_download_attempts'} ) {
            $err = '';
            try {
                my $res = $self->download( $url, $download_to );
                if ( !$res->{'status'} ) {
                    die "Failed to download: $package_file";
                }

                my $success = 0;
                my $digest;
              DIGEST:
                for my $alg ( @{ $self->{'digest_algorithms'} } ) {
                    $digest = Cpanel::Sync::Digest::digest( $download_to, { algo => $alg } );

                    if ( defined($digest) ) {
                        if ( $digest eq $expected_digests_hr->{$alg} ) {
                            $success = 1;
                            last DIGEST;
                        }
                    }
                    else {
                        $logger->warning("Failed to generate local digest for file: $package_file");
                    }
                }
                if ( !$success ) {

                    unlink $download_to;

                    my $ip = $self->http_request->{'connectedHostAddress'} || '(unknown)';
                    die "Digest for $url is different from expected (got hash $digest; expected hash $expected_digests_hr->{$self->{'digest_algorithms'}[0]}; mirror IP $ip)";
                }
            }
            catch {
                $err = $_;
            };

            last ATTEMPT if !$err;
            if ( $attempt == $self->{'max_download_attempts'} ) {
                $logger->fatal($err);
                die $err;
            }

            $logger->error( "Retrying download of $package_file (attempt " . ( $attempt + 1 ) . "/$self->{'max_download_attempts'}): $err" );
        }
        push @complete, $package_file;
    }

    $logger->{'brief'} = 1;

    return @complete;
}

sub _get_rpm_name ( $self, $url ) {
    _need_object($self);

    my @url_parts = split /\//, $url;
    my $file      = $url_parts[-1];
    return $file;
}

sub stage ( $self, %opts ) {

    my $packages = $self->download_all(%opts);

    if ( !@$packages ) {
        $self->logger->info("No new Packages needed for install");
    }

    push @{ $self->{'to_install'} }, @{$packages};

    return scalar @{ $self->{'to_install'} } || '0E0';
}

sub test_rpm_install ( $self, @pkg_files ) {
    _need_object($self);

    $self->{'to_install'} ||= [];

    if ( ( !@pkg_files ) ) {
        @pkg_files = @{ $self->{'to_install'} };
    }

    return 0 unless @pkg_files;

    $self->pkgr->test_install( $self->{'temp_dir'}, \@pkg_files, $self->uninstall_hash );

    return 1;
}

sub install_rpms ( $self, %options ) {
    _need_object($self);

    my @packages = @{ $self->{'to_install'} || [] };
    return unless @packages;

    my $download_dir = $self->{'temp_dir'};
    -d $download_dir or die("$download_dir unexpectedly missing!");

    my $preinstall = $options{'preinstall'} ? 1 : 0;

    my $errors = $self->pkgr->install( $download_dir, $preinstall, \@packages );

    return if $preinstall;

    $self->_cleanup_tmp_packages if !$errors;

    return scalar @packages;
}

sub _cleanup_tmp_packages ($self) {
    _need_object($self);

    my $pkg_ext = $self->pkgr->package_extension;
    unlink( glob( $self->{'temp_dir'} . '/*' . $pkg_ext ) );
    unlink( glob( $self->{'temp_dir'} . '/sha512' ) );

    return;
}

sub uninstall_rpms ( $self, @pkgs ) {
    _need_object($self);

    if ( !@pkgs ) {
        my $pkgs_hash = $self->uninstall_hash() // {};
        @pkgs = keys $pkgs_hash->%*;
    }

    if ( !@pkgs ) {
        $self->logger->info('No packages need to be uninstalled');
        return;
    }
    elsif ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        $self->logger->info('Packages cannot be uninstalled during the base cPanel installation.');
        return;
    }

    return $self->pkgr->uninstall( \@pkgs );    # number of uninstalled packages
}

sub _disable_monitoring_file() {
    return q{/var/run/chkservd.suspend};
}

sub _tailwatchd_was_running_when_rpm_transaction_began() {
    return $_tailwatchd_was_running_when_rpm_transaction_began if defined $_tailwatchd_was_running_when_rpm_transaction_began;
    require Cpanel::Services::Running;
    local $@;

    eval { $_tailwatchd_was_running_when_rpm_transaction_began = Cpanel::Services::Running::is_online('tailwatchd'); };
    warn if $@;
    return $_tailwatchd_was_running_when_rpm_transaction_began;
}

sub _restart_monitoring_service_if_running() {
    return if !_tailwatchd_was_running_when_rpm_transaction_began();

    return Cpanel::SafeRun::Errors::saferunnoerror( '/usr/local/cpanel/scripts/restartsrv_tailwatchd', '--no-verbose' );
}

my $monitoring_disabled_from;

sub disable_monitoring ( $self = undef ) {
    my $disable_file = _disable_monitoring_file();

    return if -e $disable_file;

    $monitoring_disabled_from = $$;

    if ( ref $self eq __PACKAGE__ ) {
        $self->logger->info("Disabling service monitoring.");
    }

    Cpanel::FileUtils::TouchFile::touchfile($disable_file);
    _restart_monitoring_service_if_running();

    return 1;
}

sub restore_monitoring ( $self = undef ) {

    local $?;

    return unless $monitoring_disabled_from && $monitoring_disabled_from == $$;

    my $disable_file = _disable_monitoring_file();
    if ( ref $self eq __PACKAGE__ ) {
        $self->logger->info("Restoring service monitoring.");
    }
    Cpanel::FileUtils::Link::safeunlink($disable_file);
    _restart_monitoring_service_if_running();

    undef $monitoring_disabled_from;

    return;
}

sub perl_rpm_name {
    return 'cpanel-perl-' . Cpanel::Binaries::PERL_MAJOR();
}


sub preinstall_list ($self) {
    _need_object($self);

    my $perl_rpm_base = perl_rpm_name();

    my $install_hash = $self->install_hash;

    my @list = (
        "$perl_rpm_base-mail-spamassassin",    # Has a big post script that runs perl stuff.
    );

    my $version_sep = Cpanel::OS::is_rpm_based() ? '-' : '_';
    my @pre_install;
    foreach my $package ( keys %$install_hash ) {
        next unless substr( $package, 0, length($perl_rpm_base) ) eq $perl_rpm_base;    # Skip non-perl rpms.
        next if grep { substr( $package, 0, length($_) ) eq $_ } @list;                 # Skip blacklist items.
        next if $package eq $perl_rpm_base;                                             # Skip the main perl rpm (cpanel-perl-536)

        push @pre_install, $package . $version_sep . $install_hash->{$package};
    }

    @pre_install = sort @pre_install;
    return @pre_install;
}

sub perl_package_file_name ( $self, $install_list, $major ) {
    _need_object($self);

    foreach my $pkg (@$install_list) {
        next unless $pkg =~ m/^cpanel-perl-$major[-_]5./;
        return $pkg;
    }
    return;    # couldn't find it.
}

sub clear_installed_packages_cache ($self) {
    $self->pkgr->clear_installed_packages_cache;
    return;
}

sub reset_install_data ($self) {
    _need_object($self);

    $self->{'to_install'} = [];
    $self->clear_installed_packages_cache;

    $self->stage();

    return;
}

sub die_if_perl_symlink_is_rpm_owned ($self) {
    _need_object($self);

    my $perl_symlink = $self->{'perl_symlink'} //= '/usr/local/cpanel/3rdparty/bin/perl';

    return 1 unless ( -l $perl_symlink || -e _ );

    if ( -d _ ) {
        die "Stopping upgrade attempt due to $perl_symlink being a directory. cPanel cannot function when this is the case.\n";
    }

    if ( my $owner = $self->pkgr->what_owns($perl_symlink) ) {

        die "Stopping upgrade attempt due to failure to correct the rpm owning $perl_symlink. The following Package may have a problem: $owner";
    }

    return 2;
}


sub preinstall_perlmajor_upgrade ($self) {
    _need_object($self);

    my @original_to_install = @{ $self->{'to_install'} // [] };
    return unless scalar @original_to_install;    # nothing to do

    $self->{'did_preinstall'} = 1;

    my $legacy_major = Cpanel::Binaries::PERL_LEGACY_MAJOR();
    my $new_major    = Cpanel::Binaries::PERL_MAJOR();
    $self->logger->info("Updating cpanel-perl-$legacy_major and installing cpanel-perl-$new_major packages prior to switching major versions of perl.");
    $self->{'to_install'} = [];
    foreach my $major ( $legacy_major, $new_major ) {
        my $package = $self->perl_package_file_name( \@original_to_install, $major ) or next;
        push @{ $self->{'to_install'} }, $package;
    }
    eval {
        $self->install_rpms( preinstall => 1 );
        symlink( "/usr/local/cpanel/3rdparty/perl/$legacy_major/bin/perl", "/usr/local/cpanel/3rdparty/bin/perl" );
        $self->logger->info("cpanel-perl-$legacy_major and cpanel-perl-$new_major are now installed.");
    };

    $self->die_if_perl_symlink_is_rpm_owned;

    my @preinstall_list = $self->preinstall_list();
    return unless @preinstall_list;

    my @preinstall_files;
    foreach my $package_name (@preinstall_list) {
        my ($package_file) = grep { substr( $_, 0, length($package_name) ) eq $package_name } @original_to_install;
        next unless $package_file;
        push @preinstall_files, $package_file;
    }
    $self->{'to_install'} = \@preinstall_files;


    my $packages_installed = eval { $self->install_rpms( preinstall => 1 ) };

    $self->uninstall_rpms();

    $self->reset_install_data;

    return !!$packages_installed;
}

sub commit_changes ($self) {
    _need_object($self);
    my @packages = keys $self->install_hash()->%*;

    my $disable = $self->disable_monitoring();
    if ($disable) {    # only when we disabled it
        eval q{ END{ restore_monitoring() } };    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
    }

    run_hooks( $self->logger(), \@packages, 'pre' );

    my $changes = 0;
    $changes += $self->uninstall_rpms() // 0;
    $changes += $self->install_rpms()   // 0;

    run_hooks( $self->logger(), \@packages, 'post' );

    if ( $self->dir_files()->config_changed() ) {
        $self->dir_files()->save();
    }

    $self->restore_monitoring() if $disable;

    return $changes;
}

sub run_hooks ( $logger, $packages, $stage ) {

    $packages //= [];

    return 0 unless scalar $packages;
    return 0 if $ENV{CPANEL_BASE_INSTALL};

    if ( $INC{'YAML/Syck.pm'} ) {
        $logger->info("Hooks system enabled.");
    }
    else {
        $logger->warn("Hooks system unavailable.");
        return 0;
    }

    my $err;
    try {
        require Cpanel::Hooks;

        $logger->info("Checking for and running RPM::Versions '$stage' hooks for any Packages about to be installed");

        foreach my $package ( @{$packages} ) {
            Cpanel::Hooks::hook(
                {
                    'category' => 'RPM::Versions',
                    'event'    => $package,
                    'stage'    => $stage,
                    'blocking' => 1,
                },
            );
        }

        $logger->info("All required '$stage' hooks have been run");
    }
    catch {
        $err = $_;
    };

    if ($err) {
        $logger->warning( "Hooks system failure with Packages ( " . join( ', ', sort @{$packages} ) . " ) " . Cpanel::Exception::get_string($err) );
        return 0;
    }
    return 1;
}

sub get_all_targets_in_state ( $self, $filter ) {
    _need_object($self);

    die unless $filter;

    my $target_settings = $self->target_settings();

    return grep { $target_settings->{$_} eq $filter } keys %{$target_settings};
}

sub save ($self) {
    _need_object($self);

    $self->_clear_cache();
    return $self->dir_files()->save();
}

sub _is_installed_in_os ( $self, $pkg, $version = undef ) {

    my $installed_in_os = $self->pkgr->installed_packages();

    if ( defined $version ) {
        return exists $installed_in_os->{$pkg} && $installed_in_os->{$pkg} eq $version ? 1 : 0;
    }

    return exists $installed_in_os->{$pkg} ? 1 : 0;
}


sub get_dirty_rpms ( $self, $skip_digest_check = 0 ) {
    _need_object($self);

    my @cpanel_rpm_list = sort keys %{ $self->list_rpms_in_state('installed') };
    return {} if ( !@cpanel_rpm_list );    # When called with targets, this may be empty;

    return $self->pkgr->get_dirty_packages( \@cpanel_rpm_list, $skip_digest_check );
}


sub reinstall_rpms ( $self, @reinstall ) {
    _need_object($self);

    foreach my $package (@reinstall) {
        ($package) = split( ',', $package, 2 );
    }

    $self->pkgr->uninstall_leave_files(@reinstall) if @reinstall;

    $self->stage();
    return $self->commit_changes();
}


sub find_from_srpm_sub_packages ( $self, $name ) {
    _need_object($self);

    my $srpm_sub_package_to_package_map = $self->srpm_sub_package_to_package_map_cached();

    if ( my $key = $srpm_sub_package_to_package_map->{$name} ) {
        my $srpm_versions = $self->srpm_versions_cached();
        my $version_info  = $srpm_versions->{$key};
        if ($version_info) {
            return { $name => $version_info };
        }
    }
    return {};
}

sub url_templates_cached ( $self, $url ) {
    return $self->{'_url_templates'}{$url} ||= $self->url_templates($url);
}

sub srpm_versions_cached ($self) {
    return $self->{'_srpm_versions'} ||= $self->srpm_versions();
}

sub rpm_groups_cached ($self) {
    return $self->{'_rpm_groups'} ||= $self->rpm_groups();
}

sub srpm_sub_packages_cached ($self) {
    return $self->{'_srpm_sub_packages'} ||= $self->srpm_sub_packages();
}

sub rpm_locations_cached ($self) {
    return $self->{'_package_locations'} ||= $self->rpm_locations();
}

sub srpm_sub_package_to_package_map_cached ($self) {
    _need_object($self);
    return $self->{'_srpm_sub_package_to_package_map'} if $self->{'_srpm_sub_package_to_package_map'};
    my $srpm_sub_packages = $self->srpm_sub_packages_cached();
    my %srpm_sub_package_to_package_map;
    foreach my $key ( keys %{$srpm_sub_packages} ) {
        foreach my $srpm_name ( @{ $srpm_sub_packages->{$key} } ) {
            $srpm_sub_package_to_package_map{$srpm_name} = $key;
        }
    }
    return ( $self->{'_srpm_sub_package_to_package_map'} = \%srpm_sub_package_to_package_map );
}

sub _clear_cache ($self) {
    _need_object($self);
    delete @{$self}{qw(_srpm_versions _rpm_groups _srpm_sub_packages _rpm_locations _srpm_sub_package_to_package_map _url_templates)};
    return;
}

1;

} # --- END Cpanel/RPM/Versions/File.pm


{ # --- BEGIN Cpanel/Sys/Chattr.pm
package Cpanel::Sys::Chattr;


use strict;



my %NAME_TO_NUMBER = qw(
  FS_IOC_GETFLAGS    2148034049
  FS_IOC_SETFLAGS    1074292226
  FS_SECRM_FL                 1
  FS_UNRM_FL                  2
  FS_COMPR_FL                 4
  FS_SYNC_FL                  8
  FS_IMMUTABLE_FL            16
  FS_APPEND_FL               32
  FS_NODUMP_FL               64
  FS_NOATIME_FL             128
);


sub set_attribute {
    my ( $fh, $attribute ) = @_;

    my $attribute_number   = name_to_number("FS_${attribute}_FL");
    my $current_attributes = _get_attributes($fh);
    return unless defined $current_attributes;
    return 1 if ( $current_attributes & $attribute_number );
    return _set_attributes( $fh, $current_attributes | $attribute_number );
}


sub remove_attribute {
    my ( $fh, $attribute ) = @_;

    my $attribute_number   = name_to_number("FS_${attribute}_FL");
    my $current_attributes = _get_attributes($fh);
    return 1 unless ( $current_attributes & $attribute_number );
    return _set_attributes( $fh, $current_attributes & ~$attribute_number );
}


sub get_attribute {
    return _get_attributes( $_[0] ) & name_to_number("FS_$_[1]_FL");
}

sub _get_attributes {
    my $res = pack 'L', 0;
    return unless defined ioctl( $_[0], name_to_number('FS_IOC_GETFLAGS'), $res );
    return scalar unpack 'L', $res;
}

sub _set_attributes {
    my ( $fh, $flags ) = @_;
    my $flag = pack 'L', $flags;
    return ioctl( $fh, name_to_number('FS_IOC_SETFLAGS'), $flag );
}

sub name_to_number {
    return $NAME_TO_NUMBER{ $_[0] } || _die_unknown_constant( $_[0] );
}

sub _die_unknown_constant {
    my $name = shift;
    die "Unknown ioctl constant: $name";
}


1;

} # --- END Cpanel/Sys/Chattr.pm


{ # --- BEGIN Cpanel/Fcntl/Types.pm
package Cpanel::Fcntl::Types;


use strict;
use warnings;


# use Cpanel::Fcntl::Constants ();

our %FILE_TYPES = (
    $Cpanel::Fcntl::Constants::S_IFREG  => 'file',
    $Cpanel::Fcntl::Constants::S_IFDIR  => 'dir',
    $Cpanel::Fcntl::Constants::S_IFCHR  => 'char',
    $Cpanel::Fcntl::Constants::S_IFBLK  => 'block',
    $Cpanel::Fcntl::Constants::S_IFIFO  => 'fifo',
    $Cpanel::Fcntl::Constants::S_IFLNK  => 'link',
    $Cpanel::Fcntl::Constants::S_IFSOCK => 'socket',
);
1;

} # --- END Cpanel/Fcntl/Types.pm


{ # --- BEGIN Cpanel/Sync/v2.pm
package Cpanel::Sync::v2;


use cPstrict;

use Carp                        ();
# use Cpanel::Config::CpConfGuard ();
# use Cpanel::LoadFile            ();
# use Cpanel::Exception           ();
# use Cpanel::FileUtils::Write    ();
# use Cpanel::HttpRequest         ();
# use Cpanel::LoadModule          ();
# use Cpanel::SafeDir::MK         ();
# use Cpanel::SafeDir::RM         ();
# use Cpanel::Sys::Chattr         ();
# use Cpanel::TempFile            ();
# use Cpanel::JSON                ();
# use Cpanel::Fcntl::Types        ();
# use Cpanel::Fcntl::Constants    ();
use File::Basename              ();
use File::Copy                  ();
use File::Spec                  ();
use IO::Handle                  ();
eval {
    local $SIG{'__DIE__'};
    local $SIG{'__WARN__'};
    require Cpanel::YAML;          # PPI NO PARSE - We need updatenow.static to build this in
    require Cpanel::YAML::Syck;    # PPI NO PARSE - We need updatenow.static to build this in
};

use Try::Tiny;
# use Cpanel::Update::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Update::Base); }

use constant S_IFMT => $Cpanel::Fcntl::Constants::S_IFMT;


our $VERSION = '4.03';

my $STATE_FAILED = 0;
my $STATE_OK     = 1;

our $STATE_KEY_POSITION      = 0;
our $STAGED_DIR_KEY_POSITION = 1;

our $USE_HASH_CACHE    = 0;
our $IGNORE_HASH_CACHE = 1;

my $STREAM_MEMORY_LIMIT = 1024**2 * 4;    # 4MiB

sub cpanelsync_excludes_file      { return '/etc/cpanelsync.exclude' }
sub cpanelsync_chmod_exclude_file { return '/etc/cpanelsync.no_chmod' }


sub new ( $class, $args ) {

    ref($args) eq 'HASH' or die("Hash ref not passed into Cpanel::Sync::v2->new");

    foreach my $param (qw( syncto url source logger)) {
        $args->{$param} or die( "Cannot create " . __PACKAGE__ . " without $param parameter" );
    }
    ref( $args->{'source'} ) eq 'ARRAY' or die("Required array ref not passed to new as 'source'");
    @{ $args->{'source'} }              or die("Required array ref passed to new as 'source' is empty");

    $args->{'stage_suffix'} ||= '-cpanelsync';

    $args->{'url'} =~ m{https?://([^/]+)(.*)} or die("Cannot parse url: $args->{'url'}");
    $args->{'host'} = $1;
    $args->{'url'}  = $2;
    $args->{'options'} ||= {};

    eval { require Digest::SHA;            $args->{'hassha'}  = 1 };
    eval { require Cpanel::IO::Mmap::Read; $args->{'hasmmap'} = 1; };

    if ( $args->{'http_client'} ) {
        $args->{'http_client'}->isa('Cpanel::HttpRequest') or die "http_client must be a Cpanel::HttpRequest";
    }

    my @required_binaries = qw/bzip2 sha512sum gzip/;
    push @required_binaries, 'xz' unless $args->{'options'}{'ignore_xz'};
    foreach (@required_binaries) {
        -x "/usr/bin/$_" or die("This program cannot function without an executable /usr/bin/$_");
    }

    my $conf = Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 )->config_copy;

    $args->{'sync_basename'} = '.cpanelsync';

    unlink "$args->{'syncto'}/$args->{'sync_basename'}.new";
    if ( -e "$args->{'syncto'}/.cpanelsync.new" ) {
        $args->{'logger'}->warning("Could not remove previous temp cpanelsync file '$args->{'syncto'}/$args->{'sync_basename'}.new': $!");
        $args->{'logger'}->set_need_notify();
    }

    my $self = bless $args, $class;

    chop $self->{'staging_dir'} while substr( $self->{'staging_dir'}, -1 ) eq '/';
    $self->{'staging_dir_length'}  = length $self->{'staging_dir'};
    $self->{'stage_suffix_length'} = length $self->{'stage_suffix'};
    $self->{'staging_dir_is_ulc'}  = $self->{'staging_dir'} eq $self->{'ulc'} ? 1 : 0;

    $self->{'source_data'}->{'excludes'}       = $self->_get_excludes( cpanelsync_excludes_file() );
    $self->{'source_data'}->{'chmod_excludes'} = $self->_get_excludes( cpanelsync_chmod_exclude_file() );

    $self->{'master_pid'} = $$;

    $self->{'staged_directories'} = {};

    $self->{'staged_files'} = {};

    return $self;
}

sub _create_http_client ($self) {
    return $self->{'http_client'} ||= Cpanel::HttpRequest->new(
        'die_on_404'      => 1,
        'retry_dns'       => 0,
        'hideOutput'      => $self->{'http_verbose'} ? 0 : 1,
        'logger'          => $self->{'logger'},
        'announce_mirror' => 1,
    );
}


sub _get_excludes ( $self, $file ) {
    $file or die;

    return undef if ( !-e $file || -z _ || -d _ );
    my %excludes;

    open( my $fh, '<', $file ) or return {};
    while ( my $line = <$fh> ) {
        next if $line =~ m/^\s*$/;
        chomp $line;
        $line =~ s/\s+$//;    #remove whitespace
        $line =~ s/^\s+//;
        $excludes{ $self->_normalize_syncfile_path($line) } = 1;
    }
    close($fh);

    return undef if !( scalar keys %excludes );

    return \%excludes;
}

sub get_source_list ($self) { return $self->{'source'}->@* }

sub get_hash ( $self, $file, $relative_path, $use_cache = $USE_HASH_CACHE, $file_info = undef ) {    ## no critic qw(Subroutines::ProhibitManyArgs)
    $file_info //= $self->get_target_info($file);

    return '' if !$file_info->{'exists'} || !$file_info->{'isnormfile'};

    substr( $relative_path, -24, 24, '' ) if substr( $relative_path, -24 ) eq '.cpanelsync.nodecompress';
    $self->{'digest_lookup'}->{$relative_path} ||= {};
    my $digest_cache = $self->{'digest_lookup'}->{$relative_path};

    if (
           $use_cache == $USE_HASH_CACHE
        && $digest_cache->{'sha'}                               # Skip cache if no hash value in cache
        && defined $digest_cache->{'mtime'}
        && $file_info->{'mtime'} == $digest_cache->{'mtime'}    # Skip cache if mtime of file is not the same as what cache has.
        && defined $digest_cache->{'size'}
        && $file_info->{'size'} == $digest_cache->{'size'}
      ) {                                                       # Skip cache if size in cache is not the same as the current file size
        $digest_cache->{'used'} = 1;
        return $digest_cache->{'sha'};
    }

    my $hash = $self->{'hassha'} ? $self->_get_checksum_lib( $file, $file_info->{'size'} ) : $self->_get_checksum_binary($file);
    @{$digest_cache}{ 'size', 'mtime', 'sha', 'used' } = ( $file_info->{'size'}, $file_info->{'mtime'}, $hash, 1 );

    return $hash;
}

sub _get_checksum_binary ( $self, $file ) {

    my $bin = '/usr/bin/sha512sum';
    open( my $bin_fh, '-|' ) || exec $bin, $file;

    my $line = <$bin_fh>;
    my ($hash) = split( /\s+/, $line );

    close($bin_fh);
    return $hash;

}

sub _get_checksum_lib ( $self, $file, $size ) {

    my $ctx = Digest::SHA->new(512);
    my ( $hash, $has_bytes_read );

    if ( open( my $fh, '<', $file ) ) {
        if ( $self->{'hasmmap'} && $size > 16384 ) {
            my ( $bytes_read, $buffer );
            my $obj = Cpanel::IO::Mmap::Read->new($fh);
            while ( $bytes_read = $obj->read( $buffer, $STREAM_MEMORY_LIMIT ) ) {
                $has_bytes_read = $bytes_read;
                $ctx->add($buffer);
            }
        }
        elsif ( $ctx->addfile($fh) ) {
            $has_bytes_read = 1;
        }

        if ($has_bytes_read) {
            $hash = $ctx->hexdigest();
        }
        else {
            $hash = '';
            $self->{'logger'}->error("Unable to read file ($file) to validate it's signature!");
            $self->{'logger'}->set_need_notify();
        }
    }
    else {
        $hash = '';
        $self->{'logger'}->error("Unable to open $file to get it's checksum: $!");
        $self->{'logger'}->error( "Stat: " . `stat '$file'` );    ## no critic qw(ProhibitQxAndBackticks) give more debug info

        $self->{'logger'}->set_need_notify();
        return '';
    }

    return $hash;
}

sub parse_new_cpanelsync_files ($self) {

    return $self if $self->{'already_ran_parse_new_cpanelsync_files'};

    for my $source ( $self->get_source_list() ) {
        my $sync_file      = $self->get_local_cpanelsync_file_name($source);
        my $temp_sync_file = $sync_file . $self->{'stage_suffix'};

        my %sync;
        foreach my $line ( split( m{\n}, Cpanel::LoadFile::load($temp_sync_file) ) ) {
            my ( $rtype, $rfile, $rperm, $rextra, $sha ) = split( /===/, $line, 5 );
            next if !$rtype || ( index( $rtype, '.' ) > -1 && $rtype =~ m/^\s*\.\s*$/ );

            $sync{ $self->_normalize_syncfile_path($rfile) } = {
                'file' => $rfile,
                'type' => $rtype,
                'perm'  => sprintf( '%04d', $rperm ),
                'extra' => $rextra,
                'sha'   => $sha,
            };
        }

        if ( !%sync ) {
            $self->{'logger'}->fatal("$sync_file unexpectedly had no data.");
            die("Cannot continue without valid data from $sync_file");
        }
        $self->{'source_data'}->{'sync_file_data'}->{$source} = \%sync;
    }

    $self->{'already_ran_parse_new_cpanelsync_files'} = 1;

    return $self;
}

sub already_done ($self) {

    return 0 if !-d $self->{'syncto'};

    $self->stage_cpanelsync_files();
    $self->parse_new_cpanelsync_files();

    foreach my $source ( keys %{ $self->{'source_data'}->{'sync_file_data'} } ) {
        foreach my $file ( keys %{ $self->{'source_data'}->{'sync_file_data'}->{$source} } ) {

            next if -l $file;

            return 0 if !-e $file;
        }
    }

    return 1;
}

sub is_excluded ( $self, $path ) {
    $path or die;
    return if !$self->{'source_data'}->{'excludes'};
    return $self->syncfile_path_is_excluded( $path, $self->{'source_data'}->{'excludes'} );
}

sub is_excluded_chmod ( $self, $path ) {
    $path or die;

    return if !$self->{'source_data'}->{'chmod_excludes'};
    return $self->syncfile_path_is_excluded( $path, $self->{'source_data'}->{'chmod_excludes'} );
}

sub commit_directories ($self) {

    my $logger = $self->{'logger'};

    foreach my $staged_dir ( keys %{ $self->{'staged_directories'} } ) {
        my $commit_to   = $self->{'staged_directories'}->{$staged_dir};
        my $target_info = $self->get_target_info($commit_to);
        if ( $target_info->{'islnk'} || $target_info->{'isnormfile'} ) {
            unlink $target_info->{'path'};
            $target_info->{'exists'} = 0;
        }

        if ( -d $commit_to ) {
            $logger->error("$commit_to was unexpectedly put in place while staging files for update");
            $logger->set_need_notify();
        }

        if ( File::Copy::move( $staged_dir, $commit_to ) ) {
            delete $self->{'staged_directories'}{$staged_dir};    # remove it once it has been commited
        }
        else {
            $logger->error("Could not rename $staged_dir -> $commit_to: $!");
            $logger->set_need_notify();
        }
    }

    for my $source ( $self->get_source_list() ) {
        my $cpanelsync_data = $self->{'source_data'}->{'sync_file_data'}->{$source};
        foreach my $full_path ( keys %$cpanelsync_data ) {
            my $cpanelsync_file = $cpanelsync_data->{$full_path};
            next if ( !$cpanelsync_file->{'type'} || $cpanelsync_file->{'type'} ne 'd' );

            my $target_info = $self->get_target_info( $self->_convert_path_to_ulc($full_path) );

            unlink( $target_info->{'path'} ) if ( !$target_info->{'isdir'} && $target_info->{'exists'} );

            if ( !$target_info->{'isdir'} ) {

                Cpanel::SafeDir::MK::safemkdir( $target_info->{'path'}, $cpanelsync_file->{'perm'}, 2 );
                $self->{'logger'}->info("Created directory $target_info->{'path'} successfully");
            }    # TODO: This logic was REALLY backwards? Validate.
            else {
                $self->chmod( $cpanelsync_file->{'perm'}, $target_info );
            }
        }
    }

    $self->{'logger'}->info("All directories created and updated");
    return 1;
}

sub commit_files ($self) {

    my @files_to_commit = keys %{ $self->{'staged_files'} };

    $self->{'logger'}->info( "Commiting all downloaded files for " . join( ", ", $self->get_source_list() ) );

    @files_to_commit = sort { return 1 if ( $a =~ m{/version$} ); return -1 if ( $b =~ m{/version$} ); $a cmp $b } @files_to_commit;

    foreach my $commit_to (@files_to_commit) {
        my $cpanelsync_status = $self->{'staged_files'}->{$commit_to};
        my ( $stage_path, $temp_file ) = $self->_calculate_stage_path_and_temp_file_from_stage_file($commit_to);
        my $target_info = $self->get_target_info( $self->_convert_path_to_ulc($commit_to) );
        my $commit_path = $target_info->{'path'};


        if ( $target_info->{'isdir'} ) {
            Cpanel::SafeDir::RM::safermdir($commit_path);    # TODO: error check
            $target_info = $self->get_target_info( $self->_convert_path_to_ulc($commit_path) );
        }

        if ( $target_info->{'exists'} ) {
            unlink $commit_path;
            $target_info = $self->get_target_info( $self->_convert_path_to_ulc($commit_path) );

            if ( $target_info->{'exists'} ) {
                $self->{'logger'}->error("Failed to remove $commit_path to install the new version of this file. Trying to move it out of the way...");
                $self->{'logger'}->debug(`lsattr '$commit_path'`) if -x '/usr/bin/lsattr';    ## no critic qw(ProhibitQxAndBackticks) - just debug.
                $self->{'logger'}->debug(`ls -ld '$commit_path'`);                            ## no critic qw(ProhibitQxAndBackticks) - just debug.
                $self->{'logger'}->set_need_notify();

                if ( rename( $commit_path, $commit_path . '.unlink' ) ) {
                    $self->{'logger'}->error("$commit_path has been renamed to $commit_path.unlink. You should try to remove it.");
                    unlink $commit_path . '.unlink';
                }
                else {
                    $self->{'logger'}->error("Could not rename $commit_path out of the way. Please resolve and re-run /usr/local/cpanel/scripts/upcp --force.");
                    unlink $commit_path;
                }
            }
        }

        my $message = '';

        if ( !File::Copy::move( $temp_file, $commit_path ) ) {
            $message = $!;
            unlink $temp_file;

            if ( $self->is_file_immutable($commit_path) ) {
                $self->{'logger'}->error("$commit_path could not be overwritten by staged $temp_file");
                $self->{'logger'}->set_need_notify();
            }
            else {
                $self->{'logger'}->error("Could not put new '$commit_path' into place from $temp_file: $message");
                $self->{'logger'}->set_need_notify();
            }
        }
        else {

            push @{ $self->{'new_files'} }, $commit_path;
        }

        delete $self->{'staged_files'}{$commit_to};    # remove it once it has been commited
    }
    return;
}

sub handle_symlinks ($self) {

    for my $source ( $self->get_source_list() ) {
        my $cpanelsync_data = $self->{'source_data'}->{'sync_file_data'}->{$source};
        foreach my $path ( keys %$cpanelsync_data ) {
            my $cpanelsync_file = $cpanelsync_data->{$path};
            next if ( !$cpanelsync_file->{'type'} || $cpanelsync_file->{'type'} ne 'l' );

            my $link_to     = $cpanelsync_file->{'extra'};
            my $target_info = $self->get_target_info( $self->_convert_path_to_ulc($path) );

            if ( $target_info->{'islnk'} ) {

                next if ( readlink $target_info->{'path'} eq $link_to );

                unlink $target_info->{'path'};
            }
            elsif ( $target_info->{'isnormfile'} ) {
                unlink $target_info->{'path'};
            }
            elsif ( $target_info->{'isdir'} ) {
                Cpanel::SafeDir::RM::safermdir( $target_info->{'path'} );
            }

            if ( symlink( $cpanelsync_file->{'extra'}, $target_info->{'path'} ) ) {
                $self->{'logger'}->info("Created symlink $target_info->{'path'} -> $link_to successfully");
            }
            else {
                $self->{'logger'}->error("Failed to create symlink $target_info->{'path'} -> $link_to: $!");
                $self->{'logger'}->set_need_notify();
            }
        }
    }
    return;
}

sub validate_file_permissions ($self) {

    $self->{'logger'}->info("Checking permissions of all files we manage");
    for my $source ( $self->get_source_list() ) {
        my $cpanelsync_data = $self->{'source_data'}->{'sync_file_data'}->{$source};
        for my $full_path ( grep { $cpanelsync_data->{$_}{'type'} eq 'f' } keys %$cpanelsync_data ) {
            my $ulc_path    = $self->_convert_path_to_ulc($full_path);
            my $target_info = $self->{'get_target_info_cache_hash_checked'}{$ulc_path} || $self->get_target_info($ulc_path);
            next if !$target_info->{'exists'};
            $self->chmod( $cpanelsync_data->{$full_path}->{'perm'}, $target_info );
        }
    }

    delete $self->{'get_target_info_cache_hash_checked'};

    return;
}

sub is_file_immutable ( $self, $file ) {
    $file or die;

    open( my $fh, '<', $file ) or do {
        warn "open(< $file): $!" if !$!{'ENOENT'};
        return;
    };
    my $attr = grep { Cpanel::Sys::Chattr::get_attribute( $fh, $_ ) } qw( IMMUTABLE APPEND );
    close $fh;

    return 1 if $attr;
    return;
}


my %_filetype_keymap = ( 'dir' => 'isdir', 'file' => 'isnormfile', 'link' => 'islnk' );

sub get_target_info ( $self, $normalized_path ) {
    $normalized_path or die;

    my %target = ( 'path' => $normalized_path, 'isdir' => 0, 'isnormfile' => 0, 'islnk' => 0, 'exists' => 0 );
    @target{ 'perm', 'uid', 'gid', 'size', 'mtime' } = ( lstat( $target{'path'} ) )[ 2, 4, 5, 7, 9 ];

    if ( $target{'perm'} ) {
        $target{'exists'} = 1;
        $target{ $_filetype_keymap{ $Cpanel::Fcntl::Types::FILE_TYPES{ S_IFMT & $target{'perm'} } } || 'isunknown' } = 1;
    }

    $target{uid} //= -1;
    $target{gid} //= -1;

    return \%target;

}

sub _convert_path_to_ulc ( $self, $path ) {
    return undef if !defined $path;

    my $staging_dir_with_trailing_slash = $self->{'staging_dir'} . '/';

    if ( !$self->{'staging_dir_is_ulc'} && rindex( $path, $staging_dir_with_trailing_slash, 0 ) == 0 ) {
        substr( $path, 0, $self->{'staging_dir_length'}, $self->{'ulc'} );
    }
    return substr( $path, -$self->{'stage_suffix_length'} ) eq $self->{'stage_suffix'} ? substr( $path, 0, -$self->{'stage_suffix_length'} ) : $path;
}

sub _convert_path_to_staging ( $self, $path ) {
    $path =~ s/^$self->{'ulc'}/$self->{'staging_dir'}/;
    return $path;
}

sub create_dot_new_file ($self) {

    my $new_file = "$self->{'syncto'}/.cpanelsync.new";
    unless ( exists $self->{'new_files'} && ref( $self->{'new_files'} ) eq 'ARRAY' ) {
        $self->{'logger'}->debug("No new files to manifest");
        return 1;
    }

    my $new_fh;
    unless ( open( $new_fh, '>', $new_file ) ) {
        $self->{'logger'}->fatal("Could not open '$new_file' for writing: $!");
        die("Cannot continue without $new_file");
    }

    for ( sort @{ $self->{'new_files'} } ) {
        print {$new_fh} "$_\n";
    }
    return close($new_fh);
}

sub init_current_digest_cache ($self) {

    my $digest_lookup = $self->{'digest_lookup'} = {};

    return if ( $self->{'force'} );

    my $digest_file = "$self->{'syncto'}/.cpanelsync.digest";

    return if ( !-e $digest_file );    # No MD5 is fine.

    $self->{'logger'}->info("Loading digest cache from $self->{'syncto'}/.cpanelsync.digest");
    foreach ( split( m{\n}, Cpanel::LoadFile::load($digest_file) ) ) {
        my ( $filename, $size, $mtime, undef, $sha ) = split( /:::/, $_, 5 );
        $digest_lookup->{$filename} = {
            'size'  => $size,
            'mtime' => $mtime,
            'sha'   => $sha,
        };
    }
    return;
}

sub save_updated_digest_data ($self) {

    my $digest_file   = "$self->{'syncto'}/.cpanelsync.digest";
    my $digest_lookup = $self->{'digest_lookup'};
    my $contents      = '';
    foreach my $relative_path ( sort keys %{$digest_lookup} ) {
        next
          if (
            !$digest_lookup->{$relative_path}{'used'}         ||    # Don't save the cache of a file we didn't use this time around
            !defined $digest_lookup->{$relative_path}{'size'} ||    # Don't save if size is undefined
            !$digest_lookup->{$relative_path}{'mtime'}        ||    # Don't save if mtime is false
            !$digest_lookup->{$relative_path}{'sha'}
          );                                                        # Don't' save if no hash
        my $cache_str = join(
            ':::',
            $relative_path,
            $digest_lookup->{$relative_path}{'size'},
            $digest_lookup->{$relative_path}{'mtime'}
        );

        $cache_str .= '::::::';

        if ( $digest_lookup->{$relative_path}{'sha'} ) {
            $cache_str .= $digest_lookup->{$relative_path}{'sha'};
        }

        $cache_str .= "\n";
        $contents  .= $cache_str;
    }

    try {
        Cpanel::FileUtils::Write::overwrite( $digest_file, $contents, 0644 );
    }
    catch {
        local $@ = $_;
        my $err = Cpanel::Exception::get_string($_);
        $self->{'logger'}->fatal("Could not open '$digest_file' for writing: $err.");
        die;
    };
    return;
}

sub _normalize_syncfile_path ( $self, $path_from_syncfile ) {
    length $path_from_syncfile or Carp::croak('[ARGUMENT] path_from_syncfile must be specified');

    chop $path_from_syncfile while substr( $path_from_syncfile, -1 ) eq '/';    # Strip off the trailing slash from the path_from_syncfile.
    substr( $path_from_syncfile, -24, 24, '' ) if substr( $path_from_syncfile, -24 ) eq '.cpanelsync.nodecompress';
    return rindex( $path_from_syncfile, '.', 0 ) == 0 ? $self->{'syncto'} . substr( $path_from_syncfile, 1 ) : $path_from_syncfile;
}

sub syncfile_path_is_excluded ( $self, $path, $normalized_exclude_lookup_hr ) {    ## no critic qw(Subroutines::ProhibitManyArgs)
    $path                         or die;
    $normalized_exclude_lookup_hr or die;

    my $full_path = $self->_normalize_syncfile_path($path);
    return 1 if $normalized_exclude_lookup_hr->{$full_path};

    while (1) {
        my $copy = $full_path;
        $full_path =~ s{/[^/]+$}{};
        last if !$full_path || $full_path eq '/' || $copy eq $full_path;

        return 1 if ( $normalized_exclude_lookup_hr->{$full_path} );
    }

    return;
}

sub chmod ( $self, $plaintext_octal_perms, $file_info, $check_exclusions = undef ) {    ## no critic qw(Subroutines::ProhibitManyArgs)
    $plaintext_octal_perms ||= 0;
    $file_info or die;
    $check_exclusions = !$check_exclusions;

    my $full_path = $file_info->{'path'};
    return 0 unless ( $file_info->{'exists'} );
    return 0 if ( $file_info->{'islnk'} );

    my $decimal_perms_needed = oct($plaintext_octal_perms);
    return 0 if ( $decimal_perms_needed == ( $file_info->{'perm'} & 07777 ) );

    if ( $check_exclusions && $self->{'source_data'}->{'chmod_excludes'} && $self->syncfile_path_is_excluded( $full_path, $self->{'source_data'}->{'chmod_excludes'} ) ) {
        $self->{'logger'}->warning("$full_path is prevented from chmod");
        return 0;
    }

    unless ( CORE::chmod( $decimal_perms_needed, $full_path ) ) {
        $self->{'logger'}->error("Failed to update permissions for $full_path to $plaintext_octal_perms: $!");
        $self->{'logger'}->set_need_notify();
        return 0;
    }

    if ( $self->{'verbose'} && $self->{'verbose'} >= 2 ) {
        $self->{'logger'}->info("Set permissions on $full_path to $plaintext_octal_perms");
    }

    return 1;
}

sub chown ( $self, $uid, $gid, $full_path ) {

    return 1 if $uid == -1 && $gid == -1;

    unless ( CORE::chown( $uid, $gid, $full_path ) ) {
        $self->{'logger'}->error("Failed to update ownership for $full_path to $uid:$gid: $!");
        $self->{'logger'}->set_need_notify();
        return 0;
    }
    $self->{'logger'}->info("Set ownership on $full_path to $uid:$gid") if $uid || $gid;
    return 1;
}

sub _symlink_in_path_during_handle_removed_files ( $self, $original_path ) {
    $original_path or die;

    my @parts = split( m{/+}, $original_path );
    my $path;
    my $ulc_path_syncto = $self->_convert_path_to_ulc( $self->{'syncto'} );
    while ( pop(@parts) ) {
        $path = join( '/', @parts );

        return if $path eq $ulc_path_syncto;

        return 2 if length($path) < length($ulc_path_syncto);

        return 1 if ( $self->{'symlink_cache'}{$path} //= ( -l $path ? 1 : 0 ) );    # Something along the path to this file is a symlink.
    }

    return 2;
}

sub handle_removed_files ($self) {

    my @files_to_remove;
    my @directories_to_remove;
    my @source_list = $self->get_source_list();
    my $syncdata    = $self->{'source_data'}->{'sync_file_data'};

    delete $self->{'symlink_cache'};
    for my $source (@source_list) {
        my $sync_file = $self->_convert_path_to_ulc( $self->get_local_cpanelsync_file_name($source) );

        next if ( !-e $sync_file || -z _ );

      handle_removed_files_next_syncfile:
        foreach my $line ( split( m{\n}, Cpanel::LoadFile::load($sync_file) ) ) {
            my ( $type, $path, $perm, $extra, $sha ) = split( /===/, $line, 5 );
            next unless ( $type && $path );    # Skip lines which aren't populated.

            $path = $self->_normalize_syncfile_path($path);

            foreach (@source_list) {

                next handle_removed_files_next_syncfile if $syncdata->{$_}->{$path} || ( $syncdata->{$_}->{"$path.cpanelsync.nodecompress"} && $path =~ m/\.(?:bz2|t?gz|xz)$/i );
            }

            my $ulc_path = $self->_convert_path_to_ulc($path);

            next if $self->is_excluded($ulc_path);

            next if $self->_symlink_in_path_during_handle_removed_files($ulc_path);

            if ( !-l $ulc_path && -d _ ) {
                push @directories_to_remove, $ulc_path;
            }
            else {
                push @files_to_remove, $ulc_path;
            }
        }
    }
    delete $self->{'symlink_cache'};

    foreach my $path (@files_to_remove) {
        $self->{'logger'}->info("Removing file/link $path");
        unlink $path;
        if ( -f $path || -l $path ) {
            $self->{'logger'}->warning("Could not unlink '$path': $!");
            $self->{'logger'}->set_need_notify();
        }
    }

    @directories_to_remove = sort { length($b) <=> length($a) } @directories_to_remove;

    foreach my $path (@directories_to_remove) {
        $self->{'logger'}->info("Removing dir $path");
        Cpanel::SafeDir::RM::safermdir($path) || $self->{'logger'}->warning("Could not remove directory '$path': $!");
    }
    return;
}


sub fetch_file ( $self, $download_to, $source_path, $file_info ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    my $file_path_in_ulc = $self->_convert_path_to_ulc($download_to);
    if ( $self->_file_is_already_downloaded_and_matches_digest( $file_path_in_ulc, $file_info ) ) {
        return -1;
    }

    my $cached_hash = $file_info->{'sha'};

    if ( !$file_info->{'nochecksum'} && !$file_info->{'sha'} ) {
        $self->{'logger'}->error("No sha512 digest found!");
        die("No sha512 digest found!");
    }

    my $uncompress       = ( $source_path !~ m/\.(?:bz2|gz|xz|cpanelsync\.nodecompress)$/ );
    my $real_source_path = $source_path;

    if ($uncompress) {
        if ( $source_path =~ m/\.(cpanelsync|static)$/ ) {
            $real_source_path .= '.bz2';
        }
        else {
            $real_source_path .= ".xz";
        }
    }

    $self->{'logger'}->info("Retrieving and staging $real_source_path");

    my $is_disk_full;

    my $total_attempts = 10;

    $self->_create_http_client();
    my $error;

    foreach my $attempt ( 1 .. $total_attempts ) {
        $error = '';
        try {
            local $| = 1;

            my @return = $self->{'http_client'}->request(
                'host'       => $self->{'host'},
                'url'        => $real_source_path,
                'protocol'   => 1,
                'destfile'   => $download_to,
                'signed'     => $file_info->{signed},
                'uncompress' => $uncompress,
            );
            my $ip               = $self->{'http_client'}{'connectedHostAddress'};
            my $last_http_status = $self->{'http_client'}{'last_status'} || 'unknown';

            if ( !$return[-1] ) {
                my $message = "HTTP download returned an error while downloading “$source_path” to “$download_to” (IP: $ip) (HTTP Status:$last_http_status): " . $return[0];
                if ( $attempt % 2 == 0 ) {
                    $message .= "...skipping this mirror.";
                    $self->{'http_client'}->skiphost();
                }
                $self->{'logger'}->error($message);
                die $message;
            }
            elsif ( !-e $download_to ) {
                my $message = "File was unexpectedly missing while downloading “$source_path” to “$download_to” (IP: $ip) (HTTP Status:$last_http_status).";
                if ( $attempt % 2 == 0 ) {
                    $message .= "...skipping this mirror.";
                    $self->{'http_client'}->skiphost();
                }

                $self->{'logger'}->error($message);
                die $message;
            }

            if ( $file_info->{'sha'} ) {
                my $check_hash = $self->get_hash( $download_to, $file_info->{'file'}, $IGNORE_HASH_CACHE );
                if ( $check_hash eq $file_info->{'sha'} ) {
                    $self->{'logger'}->debug("Got file $download_to ok (sha512 matches)");
                }
                else {
                    my $target_info = $self->get_target_info($download_to);

                    unlink $download_to unless $ENV{'UPDATENOW_PRESERVE_FAILED_FILES'};

                    $is_disk_full = $self->is_disk_full() and Carp::confess("The disk is full");

                    my $size = $target_info->{'size'};

                    my $message = "http://$self->{'host'}$real_source_path -> $download_to: Checksum mismatch (actual: $check_hash) (expected: $cached_hash) (size: $size) (IP: $ip) (HTTP Status:$last_http_status) (uncompress_[xz|bz2]: $uncompress)";
                    $self->{'logger'}->error($message);

                    if ( $attempt % 2 == 0 ) {
                        $message .= "...skipping this mirror.";
                        $self->{'http_client'}->skiphost();
                    }
                    die $message;
                }
            }
        }
        catch {
            $error = $_;
        };

        last if !$error || $is_disk_full || $ENV{'UPDATENOW_PRESERVE_FAILED_FILES'} || $ENV{'UPDATENOW_NO_RETRY'} || $attempt == $total_attempts;

        my $error_as_string = Cpanel::Exception::get_string($error);
        $self->{'logger'}->info("Retrying download of $real_source_path (attempt @{[$attempt+1]}/$total_attempts): $error_as_string");
    }

    if ($error) {
        $self->{'logger'}->set_need_notify();
        die $error;
    }

    return 1;
}

sub _file_is_already_downloaded_and_matches_digest ( $self, $download_to, $file_info ) {

    return 0 if $self->_has_symlinked_parents($download_to);

    if ( $file_info->{'sha'} && $self->get_hash( $download_to, $file_info->{'file'}, $USE_HASH_CACHE ) eq $file_info->{'sha'} ) {
        $self->{'logger'}->debug("$download_to already downloaded");
        return 1;
    }

    return 0;
}

sub _df ($path) {

    $path ||= '';
    my @output = `/bin/df -PB1 $path 2>&1`;    ## no critic qw(ProhibitQxAndBackticks)

    return @output;
}


sub is_disk_full ($self) {

    my @disk_space = _df( $self->{'syncto'} );

    return 0 if ( $? || scalar @disk_space != 2 );

    return 0 if ( !length $disk_space[1] || $disk_space[1] !~ m/^\s*\S+\s+\S+\s+\S+\s+([0-9]+)\s/ );

    my $space = $1;

    if ( $space < 104857600 ) {    # About 100MB;
        $self->{'logger'}->error( sprintf( "Can not complete downloads. Only %1.02fMB is available on $self->{'syncto'}", $space / 1024 / 1024 ) );
        return 1;
    }

    return 0;
}


sub stage_directory ( $self, $download_into ) {
    $download_into or Carp::confess('no download provided to stage');

    if ( substr( $download_into, 0, length $self->{'syncto'} ) ne $self->{'syncto'} ) {
        Carp::confess("Cannot stage “$download_into” outside of the syncto path: “$self->{'syncto'}”.");
    }

    my $download_dir = File::Basename::dirname($download_into);
    my $staged_dir   = $download_dir;
    my $last_dir     = '';

    my ( $symlink_found, @rest_of_path ) = $self->_check_for_symlinked_parents($staged_dir);
    if ($symlink_found) {
        $self->{'staged_directories'}->{ $symlink_found . $self->{'stage_suffix'} } = $symlink_found;
        $staged_dir = File::Spec->catdir( $symlink_found . $self->{'stage_suffix'}, @rest_of_path );
    }
    else {
        return $staged_dir if ( $self->_memorized_stage_dir_exists($staged_dir) );
        my $syncto_length = length( $self->{'syncto'} );

        while ( !$self->_memorized_stage_dir_exists($staged_dir) ) {
            $last_dir   = File::Basename::basename($staged_dir);
            $staged_dir = File::Basename::dirname($staged_dir);

            length($staged_dir) >= $syncto_length or die( "Unable to calculate stage to directory for $download_into ($syncto_length) (" . length($staged_dir) . ')' );
        }

        $staged_dir .= '/' . $last_dir;

        $self->{'staged_directories'}->{ $staged_dir . $self->{'stage_suffix'} } = $staged_dir;

        $staged_dir .= $self->{'stage_suffix'} . substr( $download_dir, length($staged_dir) );
    }

    if ( !$self->_memorized_stage_dir_exists($staged_dir) ) {
        $self->{'logger'}->info("Creating directory $staged_dir");


        Cpanel::SafeDir::MK::safemkdir( $staged_dir, '0700', 2 );
        $self->_rebuild_memorized_stage_dir_exists_cache_and_parents($staged_dir);
    }

    return $staged_dir;
}

sub _memorized_stage_dir_exists ( $self, $path ) {

    return $self->{'memorized_staged_dirs'}{$path} if exists $self->{'memorized_staged_dirs'}{$path};

    return ( $self->{'memorized_staged_dirs'}{$path} = -d $path ? 1 : 0 );
}

sub _memorized_is_symlink ( $self, $path ) {

    return $self->{'memorized_is_symlinks'}{$path} if exists $self->{'memorized_is_symlinks'}{$path};

    return ( $self->{'memorized_is_symlinks'}{$path} = -l $path ? 1 : 0 );
}

sub _rebuild_memorized_stage_dir_exists_cache_and_parents ( $self, $staged_dir ) {
    my $syncto_length = length( $self->{'syncto'} );

    while ( length($staged_dir) >= $syncto_length ) {
        $self->{'memorized_staged_dirs'}{$staged_dir} = -d $staged_dir ? 1 : 0;
        $staged_dir = File::Basename::dirname($staged_dir);
    }
    return;
}

sub _has_symlinked_parents ( $self, $path ) {
    my ($base_path) = $self->_check_for_symlinked_parents($path);
    return defined $base_path ? 1 : 0;

}

sub _check_for_symlinked_parents ( $self, $path_to_check ) {

    my @parts_to_check = File::Spec->splitdir( substr( $path_to_check, length $self->{'syncto'} ) );
    return unless @parts_to_check;

    for ( my $i = 0; $i <= $#parts_to_check; $i++ ) {
        my $_path = File::Spec->catdir( $self->{'syncto'}, @parts_to_check[ 0 .. $i ] );

        next if $_path eq $self->{'syncto'};

        if ( $self->_memorized_is_symlink($_path) ) {
            return ( $_path, @parts_to_check[ $i + 1 .. $#parts_to_check ] );
        }
    }

    return;
}


sub stage_file ( $self, $source_path, $download_into, $file_info, $staged_dir ) {    ## no critic qw(Subroutines::ProhibitManyArgs)
    $source_path             or die;                                                     # The URL after hostname for what we want to download (might be minus the .bz2)
    $download_into           or Carp::confess("stage_file requires a download_into");    # The full path to where this file needs to be put ultimatley (not where this sub WILL put it)
    $file_info               or die;                                                     # The cpanelsync hash data.
    length $staged_dir       or die;
    ref $file_info eq 'HASH' or die("file_info not passed as a hash");

    if ( substr( $download_into, 0, length $self->{'syncto'} ) ne $self->{'syncto'} ) {
        Carp::confess("Cannot stage “$download_into” outside of the syncto path: “$self->{'syncto'}”.");
    }

    $source_path =~ s{^([^/])}{/$1};                                                     # Assure the passed source_path leads with a slash
    $source_path = $self->{'url'} . $source_path;

    $self->{'staged_files'}->{$download_into}->[$STATE_KEY_POSITION]      = $STATE_FAILED;
    $self->{'staged_files'}->{$download_into}->[$STAGED_DIR_KEY_POSITION] = $staged_dir;

    my ( $stage_path, $temp_file ) = $self->_calculate_stage_path_and_temp_file_from_stage_file($download_into);

    my $fetched = $self->fetch_file( $stage_path, $source_path, $file_info );

    if ( defined $fetched && $fetched == -1 ) {

        delete $self->{'staged_files'}->{$download_into};
        return;
    }

    $self->{'staged_files'}->{$download_into}->[$STATE_KEY_POSITION] = $STATE_OK;

    my $dest_file_info = $self->get_target_info($download_into);
    if ( !$dest_file_info->{'exists'} ) {
        $dest_file_info = { 'uid' => -1, 'gid' => -1 };
    }

    if ( $self->is_excluded_chmod($download_into) && $dest_file_info->{'exists'} ) {
        my $original_mode = sprintf( '%04o', ( $dest_file_info->{'perm'} & 07777 ) );
        $self->{'logger'}->warning("$download_into is excluded from chmod so the local mode $original_mode will be preserved.");
        $self->chown( $dest_file_info->{'uid'}, $dest_file_info->{'gid'}, $stage_path );
        $self->chmod( $original_mode, $self->get_target_info($stage_path), 1 );
        $file_info->{'perm'} = $original_mode;    # Protect from validate_file_permissions (which should be honoring excludes anyways but still...)
    }
    else {
        $self->{'logger'}->debug("$stage_path set from cpanelsync mode $file_info->{'perm'}");
        $self->chown( $dest_file_info->{'uid'}, $dest_file_info->{'gid'}, $stage_path );
        $self->chmod( $file_info->{'perm'}, $self->get_target_info($stage_path) );
    }
    return $stage_path;
}

sub get_staged_file ( $self, $file ) {
    $file or die;

    if ( !$self->{'staged_files'}->{$file} ) {
        $file = $self->_convert_path_to_staging($file);
    }

    return if ( !$self->{'staged_files'}->{$file} || !$self->{'staged_files'}->{$file}->[$STATE_KEY_POSITION] );

    my ( $stage_path, $temp_file ) = $self->_calculate_stage_path_and_temp_file_from_stage_file($file);

    return $stage_path;
}

sub get_local_cpanelsync_file_name ( $self, $source ) {
    $source or die("no source provided");

    my $local_cpanelsync_file = $source;
    $local_cpanelsync_file =~ s{/+}{__forward_slash__}g;
    return "$self->{'syncto'}/$self->{'sync_basename'}_$local_cpanelsync_file";
}

sub stage_cpanelsync_files ($self) {

    return $self if $self->{'already_ran_stage_cpanelsync_files'};

    for my $source ( $self->get_source_list() ) {
        my $dest_file   = $self->get_local_cpanelsync_file_name($source);
        my $staging_dir = $self->stage_directory($dest_file);
        $self->stage_file( "/$source/$self->{'sync_basename'}", $dest_file, { 'perm' => '0644', 'signed' => 1, 'nochecksum' => 1 }, $staging_dir );
    }

    $self->{'already_ran_stage_cpanelsync_files'} = 1;
    return $self;
}


sub stage ( $self, %opts ) {

    $self->{'logger'}->debug( 'Starting at ' . time() );

    if ( !-d $self->{'syncto'} ) {
        Cpanel::SafeDir::MK::safemkdir( $self->{'syncto'}, 0755 );
        $self->{'logger'}->info("Created base directory: $self->{'syncto'}");
    }

    $self->{'logger'}->debug('Initializing hash cache');
    $self->init_current_digest_cache();

    $self->{'logger'}->debug('Downloading and reading cpanelsync files.');
    $self->stage_cpanelsync_files();
    $self->parse_new_cpanelsync_files();

    return 1 if $opts{'no_download'};

    my %files_to_stage_by_child = ();
    my $child_num               = 1;

    my $max_num_of_sync_children_this_system_can_handle = $self->calculate_max_sync_children();

    for my $source ( $self->get_source_list() ) {
        $self->{'logger'}->info("Staging files for $source");
        my $cpanelsync_data = $self->{'source_data'}->{'sync_file_data'}->{$source};

        for my $path ( grep { $cpanelsync_data->{$_}{'type'} eq 'f' } keys %$cpanelsync_data ) {

            my $path_modified = $path;
            substr( $path_modified, -24, 24, '' ) if substr( $path_modified, -24 ) eq '.cpanelsync.nodecompress';

            my $file_info_in_ulc = $self->get_target_info( $self->_convert_path_to_ulc($path_modified) );

            if ( $self->is_excluded( $file_info_in_ulc->{'path'} ) ) {
                $self->{'logger'}->warning("Excluding from sync: '$file_info_in_ulc->{'path'}'");
                next;
            }

            if (   $cpanelsync_data->{$path}->{'sha'}
                && $self->get_hash( $file_info_in_ulc->{'path'}, $cpanelsync_data->{$path}->{'file'}, $USE_HASH_CACHE, $file_info_in_ulc ) eq $cpanelsync_data->{$path}->{'sha'}
                && !$self->_has_symlinked_parents($path_modified) ) {
                $self->{'get_target_info_cache_hash_checked'}{ $file_info_in_ulc->{'path'} } = $file_info_in_ulc;
                next;
            }

            my $download_from = $cpanelsync_data->{$path}->{'file'};
            $download_from =~ s{^\./}{};    # Strip ./ from the front of file paths.
            $download_from = "/$source/$download_from";

            if ( $child_num > $max_num_of_sync_children_this_system_can_handle ) { $child_num = 1; }

            my $staged_dir = $self->stage_directory($path_modified);

            push @{ $files_to_stage_by_child{ $child_num++ } }, [ $download_from, $path_modified, $cpanelsync_data->{$path}, $staged_dir ];
        }
    }

    return $self->download_files( \%files_to_stage_by_child );
}

sub download_files ( $self, $files_to_stage_by_child_ref ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    $self->_load_best_available_serializer();

    $self->_create_sync_children($files_to_stage_by_child_ref);

    $self->_wait_load_results_from_sync_children();

    return 1;
}

sub _wait_load_results_from_sync_children ($self) {

    while ( scalar keys %{ $self->{'sync_children'} } ) {
        my $child_pid;
        my @pids = keys %{ $self->{'sync_children'} };
        foreach my $pid (@pids) {
            $child_pid = waitpid( $pid, 1 );
            if ( $child_pid == -1 ) {
                delete $self->{'sync_children'}{$pid};
                next;
            }
            elsif ( $child_pid == 0 ) {
                next;
            }
            else {
                last;
            }
        }

        if ( $child_pid && $self->{'sync_children'}{$child_pid} ) {

            if ( $? != 0 ) {
                $self->{'logger'}->error( "Sync child $child_pid exited with signal: " . ( $? & 127 ) . " and code: " . ( $? >> 8 ) );
                $self->{'logger'}->set_need_notify();
            }
            else {
                $self->{'logger'}->info("Sync child $child_pid exited cleanly.");
            }

            my $temp_file = delete $self->{'sync_children'}{$child_pid};
            if ( open( my $fh, '<', $temp_file ) ) {
                my ( $child_data, $error );

                try {
                    local $/;
                    $child_data = ( Cpanel::JSON::Load( readline($fh) ) )[0];
                }
                catch {
                    $error = $_;
                };
                if ($error) {
                    my $error_as_string = Cpanel::Exception::get_string($error);
                    my $error_message   = "Failed to deserialize staged_files and digest_lookup from: $temp_file because of an error: $error_as_string";
                    $self->{'logger'}->error($error_message);
                    $self->{'logger'}->set_need_notify();
                    die $error_message;
                }

                $self->{'staged_files'} = {
                    %{ $self->{'staged_files'} },
                    %{ $child_data->{'staged_files'} }
                };
                $self->{'digest_lookup'} = {
                    %{ $self->{'digest_lookup'} },
                    %{ $child_data->{'digest_lookup'} }
                };

                close($fh);
            }
            else {
                die "Failed to read back staged_files and digest_lookup from: $temp_file: $!";
            }
        }
        else {
            select( undef, undef, undef, 0.025 );
        }
    }

    delete $self->{'sync_children_temp_obj'};
    delete $self->{'sync_children'};
    return 1;
}

sub _create_sync_children ( $self, $files_to_stage_by_child_ref ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    $self->{'sync_children_temp_obj'} = Cpanel::TempFile->new();
    $self->{'sync_children'}          = {};
    $self->{'http_client'}            = undef;

    my $NUM_SYNC_CHILDREN = scalar keys %{$files_to_stage_by_child_ref};
    $self->_create_http_client() if $NUM_SYNC_CHILDREN;
    for my $child_num ( 1 .. $NUM_SYNC_CHILDREN ) {
        my $temp_file = $self->{'sync_children_temp_obj'}->file();
        $self->{'logger'}->info("Child: $child_num: Stage File: $temp_file");

        if ( my $child_pid = fork() ) {
            $self->{'sync_children'}{$child_pid} = $temp_file;
            $self->{'logger'}->info("Child $child_pid created to stage files.");
        }
        elsif ( defined $child_pid ) {

            my $files_ref = delete $files_to_stage_by_child_ref->{$child_num};
            undef $files_to_stage_by_child_ref;

            my %files_to_stage_this_child = map { $_->[2]->{'file'} => 1 } @{$files_ref};
            delete @{ $self->{'digest_lookup'} }{ grep { !$files_to_stage_this_child{$_} } keys %{ $self->{'digest_lookup'} } };
            %files_to_stage_this_child = ();

            foreach my $file_ref ( @{$files_ref} ) {
                my $error;
                try {
                    $self->stage_file( @{$file_ref} );
                }
                catch {    # Its possible to get EIO when calculating the MD5 of the file
                    $error = $_;
                };
                if ($error) {
                    my $error_as_string = Cpanel::Exception::get_string($error);
                    $self->{'logger'}->error("Unable to stage file from $file_ref->[0] => $file_ref->[1]: $error_as_string");
                    $self->{'logger'}->set_need_notify();
                    exit(1);
                }
            }

            my $error;
            try {
                Cpanel::FileUtils::Write::overwrite( $temp_file, Cpanel::JSON::Dump( { 'staged_files' => $self->{'staged_files'}, 'digest_lookup' => $self->{'digest_lookup'} } ), 0600 );    #
            }
            catch {
                $error = $_;
            };
            if ($error) {
                my $error_as_string = Cpanel::Exception::get_string($error);
                $self->{'logger'}->error("Unable write stage file data to: $temp_file: $error_as_string");
                $self->{'logger'}->set_need_notify();
                exit(1);
            }

            exit(1) if $self->{'logger'}->get_need_notify();
            exit(0);
        }
        else {
            die "Failed to fork(): $!";
        }
    }
    return 1;

}

sub _load_best_available_serializer ($self) {

    foreach my $modules ( [ 'JSON::XS', 'Cpanel::JSON' ], [ 'YAML::Syck', 'Cpanel::YAML' ] ) {
        my $error;

        try {
            Cpanel::LoadModule::load_perl_module($_) for @$modules;
        }
        catch {
            $error = $_;
        };
        last if !$error;
    }

    return 1;
}

sub commit ($self) {

    delete $self->{'memorized_staged_dirs'};
    delete $self->{'memorized_is_symlinks'};

    Cpanel::SafeDir::MK::safemkdir( $self->{'syncto'} ) if ( !-d $self->{'syncto'} );

    $self->{'logger'}->debug('  Remove pre-existing files that are not found in any data source');
    $self->handle_removed_files();

    $self->{'logger'}->debug('  Move staged directories into place.');
    $self->commit_directories();

    $self->{'logger'}->debug('  Move staged files into place.');
    $self->commit_files();

    $self->{'logger'}->debug('  Put Symlinks in place.');
    $self->handle_symlinks();

    $self->{'logger'}->debug('  Validate all permissions');
    $self->validate_file_permissions();

    $self->{'logger'}->debug('  Saving updated digest cache');
    $self->save_updated_digest_data();

    $self->{'logger'}->debug('  Making .cpanelsync.new file list');
    $self->create_dot_new_file();

    $self->{'logger'}->debug( "  Ending at " . time() );
    return 1;
}

sub sync_updatenow_static ( $self, $skip_signature_check = 0 ) {

    my $dir = $self->{'syncto'} . '/scripts';

    if ( !-d $self->{'syncto'} ) {
        Cpanel::SafeDir::MK::safemkdir( $self->{'syncto'}, 0711 );
        Cpanel::SafeDir::MK::safemkdir( $dir,              0755 );
    }

    my $target = $self->{'syncto'} . '/scripts/updatenow.static';
    $self->stage_file( "/cpanel/scripts/updatenow.static", $target, { 'file' => './scripts/updatenow.static', 'perm' => '0700', 'signed' => int( !$skip_signature_check ), 'nochecksum' => 1 }, $dir );

    return $self->get_staged_file($target);
}

sub _calculate_stage_path_and_temp_file_from_stage_file ( $self, $stage_file ) {

    Carp::confess("$stage_file is not staged") if ref $self->{'staged_files'}->{$stage_file} ne 'ARRAY';

    my $staged_dir = $self->{'staged_files'}->{$stage_file}->[$STAGED_DIR_KEY_POSITION] or Carp::confess("$stage_file does not have a staged_dir value.");

    return ( $staged_dir . '/' . File::Basename::basename($stage_file) . $self->{'stage_suffix'}, $stage_file . $self->{'stage_suffix'} );
}

sub DESTROY ($self) {

    return if $self->{'master_pid'} && $self->{'master_pid'} != $$;

    return unless ( ( $self->{'staged_files'} && %{ $self->{'staged_files'} } ) or ( $self->{'staged_directories'} && %{ $self->{'staged_directories'} } ) );

    $self->{'logger'}->info( "Removing staged files and directories for " . join( ', ', @{ $self->{'source'} || () } ) );
    my %dirs_to_keep;
    foreach my $stage_file ( keys %{ $self->{'staged_files'} } ) {
        my ( $stage_path, $temp_file ) = $self->_calculate_stage_path_and_temp_file_from_stage_file($stage_file);

        if ( $self->{'staged_files'}{$stage_file}->[$STATE_KEY_POSITION] == $STATE_FAILED && $ENV{'UPDATENOW_PRESERVE_FAILED_FILES'} ) {
            $self->{'logger'}->info("Skipping removal of file $stage_file as requested");
            foreach my $file ( $temp_file, $stage_path ) {
                $file =~ m{^(.*)/[^/]+$};
                $dirs_to_keep{$1} = 1;
            }
            next;
        }

        if ( -e $temp_file ) {
            unlink $temp_file;
        }

        if ( $temp_file ne $stage_path && -e $stage_path ) {
            unlink $stage_path;
        }
    }

    foreach my $stage_dir ( keys %{ $self->{'staged_directories'} } ) {
        if ( $dirs_to_keep{$stage_dir} ) {
            $self->{'logger'}->info("Skipping removal of directory $stage_dir as requested");
            next;
        }

        if ( -e $stage_dir ) {
            system( '/bin/rm', '-rf', '--', $stage_dir );
        }
    }

    return;
}


1;

} # --- END Cpanel/Sync/v2.pm


{ # --- BEGIN Cpanel/Mkdir.pm
package Cpanel::Mkdir;


use strict;
use warnings;

# use Cpanel::Umask ();

# use Cpanel::Autodie   ();
# use Cpanel::Exception ();


sub ensure_directory_existence_and_mode {
    my ( $path, $mode ) = @_;

    if ( Cpanel::Autodie::exists($path) && -d _ ) {
        return _chmod_or_die( $path, $mode );    # The caller MUST always stat $path before calling _chmod_or_die
    }

    my @path_split = split m</>, $path;

    my $parent_count = ( $#path_split - 1 );
    my $parent_path  = join( '/', @path_split[ 0 .. $parent_count ] );
    my $umask;
    if ( defined $mode ) {
        $umask ||= Cpanel::Umask->new(0000);
    }

    if ( Cpanel::Autodie::exists($parent_path) && -d _ ) {
        return _mkdir_or_chmod_if_exists_or_die( $path, $mode );
    }

    my $count = 0;
    for my $i ( 1 .. $#path_split ) {
        my $interim_path = join( '/', @path_split[ 0 .. $i ] );

        next if -d $interim_path;
        $count += _mkdir_or_chmod_if_exists_or_die( $interim_path, $mode );
    }

    return $count;
}

sub _mkdir_or_chmod_if_exists_or_die {
    my ( $path, $mode ) = @_;

    return 1 if _mkdir( $path, $mode );

    if ( $! == _EEXIST() && -d $path ) {

        _chmod_or_die( $path, $mode );    # The caller MUST always stat $path before calling _chmod_or_die
        return 0;
    }

    die Cpanel::Exception::create( 'IO::DirectoryCreateError', [ path => $path, mask => $mode, error => $! ] );
}

sub _mkdir {
    return ( defined $_[1] ? mkdir( $_[0], $_[1] ) : mkdir( $_[0] ) );
}

sub _chmod_or_die {
    my ( $path, $mode ) = @_;
    if ( defined($mode) && ( ( stat(_) )[2] & 07777 ) != ( $mode & 07777 ) ) {
        Cpanel::Autodie::chmod( $mode, $path );
        return -1;
    }
    return 0;
}

sub _EEXIST { return 17; }

1;

} # --- END Cpanel/Mkdir.pm


{ # --- BEGIN Cpanel/Binaries/Debian/Apt.pm


package Cpanel::Binaries::Debian::Apt;


use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path ($self) {
    return '/usr/bin/apt';
}


sub needs_lock ( $self, $action, @args ) {
    return 0 if grep { $action eq $_ } qw/list search show satisfy/;
    return 1;
}

1;

} # --- END Cpanel/Binaries/Debian/Apt.pm


{ # --- BEGIN Cpanel/Binaries/Debian/AptCache.pm
package Cpanel::Binaries::Debian::AptCache;



use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path ($self) {
    return '/usr/bin/apt-cache';
}


sub needs_lock ( $self, $action, @args ) {
    return 1 if grep { $action eq $_ } qw/ gencaches /;
    return 0;
}


sub show ( $self, $package ) {
    my $results = $self->_show( 1, $package );
    return if ref($results) ne 'ARRAY' || scalar(@$results) == 0;
    return $results->[0];
}


sub show_all_versions ( $self, @packages ) {
    return $self->_show( 0, @packages );
}

sub _show ( $self, $no_all_versions, @packages ) {
    my @cmd = ('show');
    push @cmd, '--no-all-versions' if $no_all_versions;
    push @cmd, @packages;
    my $run = $self->cmd(@cmd);
    return if $run->{'status'};

    my @rv;
    my @records = split( "\n\n", $run->{'output'} );

    pop @records if index( $records[-1], 'additional record' ) != -1;

    foreach my $output (@records) {
        my $cur_key;
        my %hr;
        my @lines = split( "\n", $output );
        foreach my $line (@lines) {
            my $cur_val;

            if ( $cur_key && index( $line, " " ) == 0 ) {
                $hr{ lc($cur_key) } .= $line;
                next;
            }

            my @exploded = split( ": ", $line, 2 );
            if ( scalar(@exploded) == 2 ) {
                ( $cur_key, $cur_val ) = @exploded;
                $hr{ lc($cur_key) } = $cur_val;
            }
        }

        push @rv, \%hr;
    }

    return \@rv;
}

1;

} # --- END Cpanel/Binaries/Debian/AptCache.pm


{ # --- BEGIN Cpanel/Binaries/Debian/AptGet.pm


package Cpanel::Binaries::Debian::AptGet;


use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path ($self) {
    return '/usr/bin/apt-get';
}


sub needs_lock ( $self, $action, @args ) {
    return 0 if grep { $action eq $_ } qw/ show check download changelog/;
    return 1;
}

1;

} # --- END Cpanel/Binaries/Debian/AptGet.pm


{ # --- BEGIN Cpanel/Binaries/Debian/AptKey.pm
package Cpanel::Binaries::Debian::AptKey;



use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path { return q[/usr/bin/apt-key] }

1;

} # --- END Cpanel/Binaries/Debian/AptKey.pm


{ # --- BEGIN Cpanel/Binaries/Debian/AptMark.pm
package Cpanel::Binaries::Debian::AptMark;



use cPstrict;

# use Cpanel::Binaries::Debian();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Debian); }


sub bin_path { return q[/usr/bin/apt-mark] }


sub showhold ($self) {
    my $run = $self->cmd('showhold');
    return [] if $run->{'status'};

    my @results = split( "\n", $run->{'output'} );
    return \@results;
}


sub hold ( $self, $pkg ) {
    my $run = $self->cmd( 'hold', $pkg );
    return 0 if $run->{'status'};

    return 1;
}


sub unhold ( $self, $pkg ) {
    my $run = $self->cmd( 'unhold', $pkg );
    return 0 if $run->{'status'};

    return 1;
}

1;

} # --- END Cpanel/Binaries/Debian/AptMark.pm


{ # --- BEGIN Cpanel/Parser/Line.pm
package Cpanel::Parser::Line;



use strict;

my $idx;

sub process_data {
    my ( $self, $data ) = @_;

    if ( length $self->{'_buffer'} ) {
        substr( $data, 0, 0, $self->{'_buffer'} );
    }

    while ( -1 != ( $idx = index( $data, "\n" ) ) ) {
        $self->process_line( substr( $data, 0, 1 + $idx, '' ) ) || return 0;
    }

    $self->{'_buffer'} = $data;

    return 1;
}

sub process_error_data {
    my ( $self, $data ) = @_;

    if ( length $self->{'_error_buffer'} ) {
        substr( $data, 0, 0, $self->{'_error_buffer'} );
    }

    while ( -1 != ( $idx = index( $data, "\n" ) ) ) {
        $self->process_error_line( substr( $data, 0, 1 + $idx, '' ) ) || return 0;
    }

    $self->{'_error_buffer'} = $data;

    return 1;
}

sub clear_buffer {
    my ($self) = @_;

    $self->{'_buffer'} = '';

    return;
}

sub clear_error_buffer {
    my ($self) = @_;

    $self->{'_error_buffer'} = '';

    return;
}

1;

} # --- END Cpanel/Parser/Line.pm


{ # --- BEGIN Cpanel/Parser/Base.pm
package Cpanel::Parser::Base;


use strict;
use warnings;



# use Cpanel::Parser::Line();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Parser::Line); }



sub new {
    my ($class) = @_;

    my $self = { 'success' => 0 };

    return bless $self, $class;
}


sub process_error_line {

    return print STDERR $_[1];
}


sub output {

    return print $_[1];
}


sub finish {
    my ($self) = @_;

    $self->process_line( $self->{'_buffer'} );

    $self->clear_buffer();

    return exists $self->{'success'} ? $self->{'success'} : 1;
}

1;

} # --- END Cpanel/Parser/Base.pm


{ # --- BEGIN Cpanel/Parser/Callback.pm
package Cpanel::Parser::Callback;


use strict;

# use Cpanel::Parser::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Parser::Base); }

# use Cpanel::Exception ();

sub new {
    my ( $class, %OPTS ) = @_;

    die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'callback' ] ) if !$OPTS{'callback'};
    die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” must be a coderef.', ['callback'] ) if ref $OPTS{'callback'} ne 'CODE';

    my $self = { 'callback' => $OPTS{'callback'} };

    return bless $self, $class;
}

sub process_line {
    my ( $self, $line ) = @_;

    return $self->{'callback'}->($line);
}

sub finish {
    my ($self) = @_;

    if ( length $self->{'_buffer'} ) {
        return $self->process_line( $self->{'_buffer'} );
    }

    return 1;
}

1;

} # --- END Cpanel/Parser/Callback.pm


{ # --- BEGIN Cpanel/SysPkgs/APT/Preferences.pm
package Cpanel::SysPkgs::APT::Preferences;


use cPstrict;

# use Cpanel::LoadFile         ();
# use Cpanel::FileUtils::Write ();



sub DIR {
    return q[/etc/apt/preferences.d];
}


sub new ($pkg) {
    return bless {}, $pkg;
}


sub name ($self) {
    die q[name is not provided by ] . ref($self);
}


sub content ($self) {

    return $self->{content} //= $self->_parse;

}


sub write ($self) {

    my $content = $self->content;

    my $str = '';

    foreach my $k ( sort keys $content->%* ) {
        $str .= "Package: $k\n";
        my $entry = $content->{$k};
        foreach my $attr ( sort keys $entry->%* ) {
            next if $attr eq 'Package';
            $str .= "$attr: " . $entry->{$attr} . "\n";
        }
        $str .= "\n";
    }

    chomp $str;

    Cpanel::FileUtils::Write::overwrite( $self->_filename, $str );

    $self->{content} = undef;    # force a reload next time

    return 1;
}


sub _parse ($self) {

    my @lines = split( qr/\n/, Cpanel::LoadFile::load_if_exists( $self->_filename ) // '' );

    my $data = {};

    my $entry;

    foreach my $line (@lines) {

        if ( $line =~ m{^\s*$}a ) {
            if ( ref $entry ) {
                die q[Missing Package entry] unless defined $entry->{Package};
                $data->{ $entry->{Package} } = $entry;
                $entry = undef;
            }
            next;
        }

        if ( $line =~ m{^\s*(.+):\s*(.+)\s*$}a ) {
            my ( $k, $v ) = ( $1, $2 );
            $entry //= {};
            $entry->{$k} = $v;
        }
    }

    if ( ref $entry ) {
        die q[Missing Package entry] unless defined $entry->{Package};
        $data->{ $entry->{Package} } = $entry;
    }

    return $data;
}


sub _filename ($self) {
    return $self->{_filename} //= DIR . '/' . $self->name;
}

1;

} # --- END Cpanel/SysPkgs/APT/Preferences.pm


{ # --- BEGIN Cpanel/SysPkgs/APT/Preferences/ExcludePackages.pm
package Cpanel::SysPkgs::APT::Preferences::ExcludePackages;


use cPstrict;

# use Cpanel::SysPkgs::APT::Preferences();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::SysPkgs::APT::Preferences); }



sub name ($self) {
    return q[99-cpanel-exclude-packages];
}


sub add ( $self, $rule ) {

    my $data = $self->content();

    return 1 if $data->{$rule};    # rule already set

    $data->{$rule} = {
        'Pin'          => 'release *',
        'Pin-Priority' => -1,
    };

    return $self->write;
}


sub remove ( $self, $rule ) {

    my $data = $self->content();

    return unless defined $data->{$rule};

    delete $data->{$rule};

    return $self->write;
}


sub has_rule_for_package ( $self, $rule ) {

    my $data = $self->content();

    return 1 if defined $data->{$rule};

    return 0 if $rule =~ qr[\*];

    foreach my $k ( sort keys $data->%* ) {
        next unless $k =~ qr{\*};
        my $re = $k;
        $re =~ s{\*}{.*};

        return 1 if $rule =~ $re;
    }

    return 0;
}

1;

} # --- END Cpanel/SysPkgs/APT/Preferences/ExcludePackages.pm


{ # --- BEGIN Cpanel/EA4/Constants.pm
package Cpanel::EA4::Constants;



use strict;
use warnings;
# use Cpanel::OS ();


use constant nginx_pkg             => "ea-nginx";
use constant nginx_domain_logs_dir => "/var/log/nginx/domains";

our $public_key_url = 'https://securedownloads.cpanel.net/cPanelPublicPkgKey.asc';

our $ea4_dir       = '/etc/cpanel/ea4';
our $ea4_dir_perms = 0755;
our $ea4_flag_file = $ea4_dir . '/is_ea4';

our $public_key_path = '/etc/cpanel/ea4/cPanelPublicPkgKey.asc';

sub repo_file_url {
    return Cpanel::OS::ea4_from_custom_repo_url();
}

sub repo_file_path {
    return Cpanel::OS::ea4_from_custom_repo_path();
}

1;


} # --- END Cpanel/EA4/Constants.pm


{ # --- BEGIN Cpanel/Pkgr/Base.pm
package Cpanel::Pkgr::Base;



use cPstrict;

sub new ( $class, $opts = undef ) {
    $opts //= {};

    my $self = {%$opts};
    bless $self, $class;

    return $self;
}

sub name ($self) { die "name unimplemented" }

sub get_package_version ( $self, $pkg ) {
    my $results = $self->get_version_for_packages($pkg) // {};

    return $results->{$pkg};
}

sub what_package_owns_this_file ( $self, $file ) {
    my $pkg_v = $self->what_owns($file) // {};

    my ($owner) = keys $pkg_v->%*;

    return $owner;
}

1;

} # --- END Cpanel/Pkgr/Base.pm


{ # --- BEGIN Cpanel/Slurper.pm
package Cpanel::Slurper;


use cPstrict;

# use Cpanel::Exception        ();
# use Cpanel::LoadFile         ();
# use Cpanel::FileUtils::Write ();


sub read ($file) {
    return scalar Cpanel::LoadFile::load($file);
}


sub read_lines ($file) {
    return split( qr{\n}, __PACKAGE__->can('read')->($file) );
}


sub read_dir ($path) {
    my $dh;
    opendir( $dh, $path )    #
      or die Cpanel::Exception::create( "IO::DirectoryOpenError", [ path => $path, error => $! ] );
    return ( grep { $_ ne '.' && $_ ne '..' } readdir($dh) );
}


sub write ( $file, $content, $perms_or_callback = undef ) {
    return !!Cpanel::FileUtils::Write::overwrite( $file, $content, $perms_or_callback );
}


1;

} # --- END Cpanel/Slurper.pm


{ # --- BEGIN Cpanel/Pkgr/Apt.pm
package Cpanel::Pkgr::Apt;



use cPstrict;

# use Cpanel::Pkgr::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Pkgr::Base); }

# use Cpanel::Slurper                     ();
# use Cpanel::Binaries::Debian::Dpkg      ();
# use Cpanel::Binaries::Debian::DpkgQuery ();
# use Cpanel::Binaries::Debian::AptCache  ();
# use Cpanel::Binaries::Gpg               ();

sub name ($self) { return 'apt' }

sub binary_dpkg ($self) {

    return $self->{_dpkg} //= Cpanel::Binaries::Debian::Dpkg->new();
}

sub binary_dpkg_query ($self) {

    return $self->{_dpkg_query} //= Cpanel::Binaries::Debian::DpkgQuery->new();
}

sub binary_apt_cache ($self) {

    return $self->{_apt_cache} //= Cpanel::Binaries::Debian::AptCache->new();
}

sub is_installed ( $self, $pkg ) {
    my $r = $self->binary_dpkg_query->cmd( qw{--show --showformat}, q[${db:Status-Abbrev}\n], $pkg ) // {};
    return 0 unless defined $r->{status} && $r->{status} == 0;

    my $out = $r->{output} // '';
    return index( $out, 'ii' ) == 0 ? 1 : 0;
}


sub what_owns ( $self, @files ) {

    my $pkg_version = {};

    foreach my $file (@files) {
        my $pkg = $self->binary_dpkg->what_owns($file)
          or die("Cannot find the package which owns the file: $file");

        $pkg_version->{$pkg} //= $self->get_package_version($pkg) // 0;
    }

    return $pkg_version;
}

sub what_owns_no_errors ( $self, @files ) {
    my $packages = $self->binary_dpkg->what_owns_files_no_errors(@files);

    return unless ref $packages;

    my $pkg_version = {};

    foreach my $pkg ( $packages->@* ) {
        $pkg_version->{$pkg} //= $self->get_package_version($pkg) // 0;
    }

    return $pkg_version;
}

sub get_package_requires ( $self, $pkg ) {


    my $r = $self->binary_apt_cache->cmd( qw{show}, $pkg ) // {};

    return unless defined $r->{status} && $r->{status} == 0;

    my ($depends_line) = grep { m/^Depends:/ } split( "\n", $r->{output} // '' );
    length $depends_line or return {};

    $depends_line =~ s/^Depends:\s+//;

    my %deps;

    foreach my $package ( split( ', ', $depends_line ) ) {
        my $version = 0;

        next if $package =~ m{^<};    # skipping virtual package for now

        if ( index( $package, " " ) > 0 ) {
            ( $package, $version ) = split( " ", $package, 2 );
            $version =~ s{^\(\s*}{};
            $version =~ s{\s*\)$}{};
        }

        next if $package eq $pkg;     # Skip if it's depending on itself.

        $deps{$package} = $version;
    }

    return \%deps;
}

sub get_packages_dependencies ( $self, @filter ) {

    my $r = $self->binary_dpkg_query->cmd(
        qw{--show --showformat},
        q[${Depends}\n],    # maybe add the ${binary:Package} name
        @filter
    ) // {};

    return {} unless defined $r->{status} && $r->{status} == 0;

    my $deps = {};

    my @lines = split( "\n", $r->{output} // '' );

    foreach my $line (@lines) {

        my @deps = split( /\s*,\s*/, $line );

        foreach my $d (@deps) {
            if ( $d =~ s{^ (.+) \s+ \( ( [^)]+ ) \) }{}x ) {    # when having a rule
                my ( $name, $rule ) = ( $1, $2 );
                $deps->{$name} = $rule;
            }
            else {
                $deps->{$d} = undef;                            # common case
            }
        }
    }

    return $deps;
}

sub list_files_from_package_path ( $self, $package_path ) {

    my $r = $self->binary_dpkg->cmd(
        qw{-c},
        $package_path
    ) // {};

    return () unless defined $r->{status} && $r->{status} == 0;

    my @lines = split( "\n", $r->{output} // '' );

    my @files;

    foreach my $l (@lines) {
        my ( $perms, $owner, $size, $date, $time, $file ) = split( /\s+/, $l, 6 );
        next unless defined $file;
        $file =~ s{^\.}{};
        next if $file =~ m{/$};    # not a file but a directory
        push @files, $file if length $file;
    }

    return @files;
}

sub list_files_from_installed_package ( $self, $package ) {

    my $r = $self->binary_dpkg->cmd(
        qw{-L},
        $package
    ) // {};

    return () unless defined $r->{status} && $r->{status} == 0;

    my @files = split( "\n", $r->{output} // '' );

    return @files;
}


sub installed_packages ( $self, @filter ) {

    my $r = $self->binary_dpkg_query->cmd(
        qw{--show --showformat},
        q[${db:Status-Abbrev} ${Package} ${Version} ${Architecture}\n],
        @filter
    ) // {};

    return {} unless defined $r->{status};

    my $installed = {};

    my @lines = split( "\n", $r->{output} // '' );

    foreach my $line (@lines) {
        next unless index( $line, 'ii' ) == 0;

        my ( $state, $package, $version, $arch ) = split( /\s+/, $line );

        $installed->{$package} = $version;

        if ( $self->{with_arch_suffix} ) {
            $installed->{$package} .= '.' . $arch;
        }
    }

    return $installed;
}

sub get_version_for_packages ( $self, @list ) {

    return $self->installed_packages(@list);
}

sub get_version_with_arch_suffix ( $self, @list ) {

    local $self->{'with_arch_suffix'} = 1;

    return $self->get_version_for_packages(@list);
}

sub what_provides ( $self, $pkg_or_file ) {
    state %provides_cache;    # WARNING: This cache is never cleared during the life of the process.
    state $parsed = 0;

    return $provides_cache{$pkg_or_file} if exists $provides_cache{$pkg_or_file};


    if ( $pkg_or_file =~ qr{/} ) {
        my $r = $self->binary_dpkg->cmd( qw{-S}, $pkg_or_file ) // {};

        return unless defined $r->{status} && $r->{status} == 0;

        my ($first_line) = split( "\n", $r->{output} // '' );

        return unless defined $first_line;

        my ( $pkg, undef ) = split( ':', $first_line );
        return $pkg;
    }

    return $pkg_or_file if $self->is_installed($pkg_or_file);

    return if $parsed;

    my $r = $self->binary_dpkg_query->cmd('--status') // {};
    return unless defined $r->{status} && $r->{status} == 0;

    my $current_package;
    foreach my $line ( split( "\n", $r->{output} // '' ) ) {
        if ( $line =~ m/^Package:\s+([\.\-\+a-z0-9]+)/ ) {
            $current_package = $1;
            next;
        }

        if ( $line =~ m/^Provides:\s+(\S.+)/ ) {
            my @provides = split( ", ", "$1" );
            foreach my $provide (@provides) {
                if ( $provide =~ m/^([\.\-\+a-z0-9]+)\b/ ) {    #
                    $provides_cache{$1} = $current_package;
                }
            }
        }
    }
    $parsed = 1;

    return $provides_cache{$pkg_or_file} if exists $provides_cache{$pkg_or_file};

    return;
}


sub is_capability_available ( $self, $search ) {
    return 0 unless defined $search;
    return $self->what_provides($search) ? 1 : 0;
}


sub what_provides_with_details ( $self, $pkg_or_file ) {
    my $str = $self->binary_dpkg->whatprovides($pkg_or_file) // '';
    return [ map { $self->binary_apt_cache->show($_) } split( ", ", $str ) ];
}

sub query ( $self, @filter ) {

    return $self->binary_dpkg_query->query(@filter);
}


sub get_package_scripts ( $self, @pkgs ) {
    my $pkg_info_dir = '/var/lib/dpkg/info';

    my @info_files = Cpanel::Slurper::read_dir($pkg_info_dir);

    my @script_files;
    foreach my $file ( sort @info_files ) {
        next if $file =~ m/\.(?:md5sums|list|conffiles|shlibs|triggers)$/;
        next unless grep { $file =~ m/^\Q$_\E\.[a-z]+$/ } @pkgs;

        push @script_files, $file;
    }

    my %scripts;
    foreach my $file (@script_files) {
        my ( $package, $script_type ) = $file =~ m/(^.+)\.([a-z]+)$/;
        length $script_type or next;    # Something went wrong if we hit this.

        my $content = eval { Cpanel::Slurper::read("$pkg_info_dir/$file") };
        next unless length $content && $content =~ m/\S/;    # Empty file.

        $scripts{$package} //= '';
        $scripts{$package} .= "$script_type scriptlet:\n\n$content\n";
    }

    return \%scripts;
}


sub verify_package_manager_can_install_packages ( $self, $logger = undef ) {


    return ( 1, '' );
}


sub remove_packages_nodeps ( $self, @packages ) {
    return '' unless @packages;    # Nothing to do!
    my $r = $self->binary_dpkg->cmd(
        '--ignore-depends=' . join( ',', @packages ),
        '-r',
        @packages
    );
    return $r->{'output'} // '';
}


sub lock_for_external_install ( $self, $logger ) {
    return $self->binary_dpkg->get_lock_for_cmd( $logger, [ '-i', 'and install external system packages.' ] );    # dpkg -i needs a lock. we'll use this to make sure the system gives a lock.
}


sub installed_cpanel_obsoletes ($self) {
    die "installed_cpanel_obsoletes is not implemented for package " . __PACKAGE__ . "\n";
}

sub add_repo_keys ( $self, @keys2import ) {

    die "add_repo_keys is not implemented for package " . __PACKAGE__ . "\n";
}

sub install_or_upgrade_from_file ( $self, @pkg_paths ) {
    $self->binary_dpkg->run_or_die( '--skip-same-version', '--install', @pkg_paths );
    return;
}

sub verify_package ( $self, $package, $file = undef ) {


    my $r = $self->binary_dpkg->cmd(
        '-V',
        $package
    );

    my $out = $r->{'output'} // '';

    if ( $r->{status} ) {
        return 1 if $out =~ qr{not installed}i;
        return 0;
    }

    return length $out ? 1 : 0;
}

sub package_file_is_signed_by_cpanel ( $self, $file ) {

    return unless defined $file && $file =~ qr{\.deb$} && -e $file;

    my $gpg = Cpanel::Binaries::Gpg->new();
    return $gpg->is_file_signed_by_cpanel($file);
}

1;

} # --- END Cpanel/Pkgr/Apt.pm


{ # --- BEGIN Cpanel/Binaries/RepoQuery.pm
package Cpanel::Binaries::RepoQuery;



use cPstrict;

# use Cpanel::Context  ();
# use Cpanel::OS       ();
# use Cpanel::Binaries ();

# use Cpanel::Binaries::Cmd();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Cmd); }


sub bin_path {

    my $path = Cpanel::Binaries::path('repoquery');

    die("Unable to find the repoquery binary\n") unless -x $path;

    return $path;
}

sub lock_to_hold { return 'repoquery' }


sub lang { return 'en_US.UTF-8' }


sub get_all_packages ( $self, $baseurl, @attrs ) {

    Cpanel::Context::must_be_list();

    die "Need base URL!" if !$baseurl;

    if ( !@attrs ) {    # default attributes
        @attrs = (
            'name',
            'summary',
            'description',
            'version',
            'release',
            'url',
        );
    }

    my $attr_separator = _make_separator('attr');
    my $pkg_separator  = _make_separator('pkg');

    my $pkg_qf = join( $attr_separator, map { "%{$_}" } @attrs );

    my $id = '___REPOQUERY___';

    my @args = (
        "--repofrompath=$id,$baseurl",
        "--repoid=$id",
        '--all',
        "--qf=$pkg_qf$pkg_separator",
    );

    push @args, '--latest-limit=1' if Cpanel::OS::package_manager() eq 'dnf';

    my $answer = $self->cmd(@args);

    return [] unless $answer->{'status'} == 0;

    my $out = $answer->{'output'} // '';

    $out =~ s<\A\s+|\s+\z><>g;

    my @pkgs = split m<\Q$pkg_separator\E>, $out;

    foreach my $pkg (@pkgs) {
        my %pkgg;
        @pkgg{@attrs} = split m<\Q$attr_separator\E>, $pkg;
        s<\A\s+|\s+\z><>g for values %pkgg;
        $pkg = \%pkgg;
    }

    return @pkgs;
}


sub whatprovides ( $self, $item ) {

    _croak('You must specify a feature or file to search for.') unless defined $item;

    my @attrs = ( 'repoid', 'name', 'version', 'release', 'arch', 'group', 'summary', 'description' );

    my $attr_separator = _make_separator('attr');
    my $pkg_separator  = _make_separator('pkg');

    my $pkg_qf = join( $attr_separator, map { "%{$_}" } @attrs );

    my $query_format = join( $attr_separator, map { "\%{$_}" } @attrs ) . $pkg_separator;

    my $answer = $self->cmd( '--qf', $query_format, '--whatprovides', $item );


    my $output = $answer->{'output'} // '';

    my @records;
    for my $rpm_record ( split /\Q$pkg_separator\E/, $output ) {
        my %record;
        ( @record{@attrs} = map { my $e = $_; $e =~ s{^\n+}{}; chomp $e; $e; } split /\Q$attr_separator\E/, $rpm_record ) == scalar @attrs or next;
        push @records, \%record if scalar keys %record;
    }

    return \@records;
}

sub _make_separator ($type) {
    state $separator = '<>~:;' x 3;    # from RepoQuery

    return join( '-', $separator, time, $$, $type, $separator );
}

sub _croak {
    require Carp;
    goto \&Carp::croak;
}

1;

} # --- END Cpanel/Binaries/RepoQuery.pm


{ # --- BEGIN Cpanel/Pkgr/Yum.pm


package Cpanel::Pkgr::Yum;


use cPstrict;

# use Cpanel::Binaries::Rpm       ();
# use Cpanel::Binaries::RepoQuery ();

# use Cpanel::Pkgr::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Pkgr::Base); }

sub name ($self) { return 'yum' }

sub binary_rpm ($self) {

    return $self->{_rpm} //= Cpanel::Binaries::Rpm->new();
}

sub binary_repoquery ($self) {

    return $self->{_repoquery} //= Cpanel::Binaries::RepoQuery->new();
}

sub query ( $self, @filter ) {

    return $self->binary_rpm->query(@filter);
}

sub is_installed ( $self, $package ) {

    return $self->binary_rpm->has_rpm($package);
}


sub installed_packages ( $self, @filter ) {

    return $self->binary_rpm->installed_packages(@filter);
}


sub what_owns ( $self, @filter ) {

    return $self->binary_rpm->what_owns(@filter);
}


sub what_owns_no_errors ( $self, @list_of_files ) {

    return $self->binary_rpm->what_owns_no_errors(@list_of_files);
}


sub get_packages_dependencies ( $self, @filter ) {

    return $self->binary_rpm->qR(@filter);
}

sub list_files_from_package_path ( $self, $rpm_file_path ) {

    return $self->binary_rpm->list_files_from_package_path($rpm_file_path);
}

sub list_files_from_installed_package ( $self, $rpm_name ) {

    return $self->binary_rpm->list_files_from_installed_package($rpm_name);
}

sub what_provides ( $self, $pkg_or_file ) {

    return $self->binary_rpm->what_provides($pkg_or_file);
}


sub is_capability_available ( $self, $search ) {
    return 0 unless defined $search;
    return $self->what_provides($search) ? 1 : 0;
}

sub what_provides_with_details ( $self, $pkg_or_file ) {
    return $self->binary_rpm->what_provides_with_details($pkg_or_file);
}

sub get_package_requires ( $self, $pkg ) {


    return $self->binary_rpm->what_requires($pkg);
}


sub add_repo_keys ( $self, @keys2import ) {

    return $self->binary_rpm->add_repo_keys(@keys2import);
}


sub get_version_for_packages ( $self, @list ) {

    return $self->binary_rpm->get_version(@list);
}

sub get_version_with_arch_suffix ( $self, @list ) {

    local $self->binary_rpm->{'with_arch_suffix'} = 1;

    return $self->binary_rpm->get_version(@list);
}


sub install_or_upgrade_from_file ( $self, @rpm_paths ) {

    return $self->binary_rpm->install_or_upgrade_from_file(@rpm_paths);
}


sub verify_package ( $self, $package, $file = undef ) {

    return $self->binary_rpm->verify_package( $package, $file );
}


sub package_file_is_signed_by_cpanel ( $self, $file ) {

    return $self->binary_rpm->package_file_is_signed_by_cpanel($file);
}


sub get_package_scripts ( $self, @pkgs ) {
    return $self->binary_rpm->get_rpm_scripts(@pkgs);
}


sub verify_package_manager_can_install_packages ( $self, $logger = undef ) {

    my $do_log;
    if ($logger) {
        $do_log = sub ($msg) {
            return unless defined $msg;
            chomp $msg;
            $logger->info("$msg\n");
        };
    }
    else {
        $do_log = sub ($msg) { return };
    }

    my $answer = $self->binary_rpm->cmd_with_logger( $logger, qw{ -q --nosignature --nodigest glibc } );
    if ( my $status = $answer->{status} ) {
        my $exit_code = $status >> 8;
        my $output    = $answer->{output} // '';
        my $statusmsg = "FAIL: RPM DB error: $output (exit code $exit_code)";
        $do_log->($statusmsg);
        return ( 0, $statusmsg );
    }

    return ( 1, '' ) if $ENV{'CPANEL_BASE_INSTALL'};


    $do_log->("Testing if rpm_is_working RPM is installed");

    $answer = $self->binary_rpm->cmd(qw{ -q --nosignature --nodigest rpm_is_working });
    if ( $answer->{status} == 0 ) {    # success when the rpm is installed
        $do_log->("Removing RPM rpm_is_working");

        $answer = $self->binary_rpm->cmd_with_logger( $logger, qw{ -e --allmatches rpm_is_working } );    #

        if ( my $status = $answer->{status} ) {
            my $msg = $answer->{output} // q{Reason unknown.};
            $do_log->("Failed to remove rpm_is_working. $msg");
        }
    }

    my $local_pkg = '/usr/local/cpanel/src/rpm_is_working-1.0-0.noarch.rpm';

    if ( -e $local_pkg && !-z $local_pkg ) {

        $do_log->("Testing if it's possible to install a simple RPM");
        $answer = $self->binary_rpm->cmd_with_logger( $logger, '-Uvh', '--force', $local_pkg );

        if ( my $status = $answer->{status} ) {
            my $exit_code = $status >> 8;
            my $msg       = qq[Fail to install $local_pkg file (exit code $exit_code)];
            $do_log->($msg);
            return ( 0, $msg );
        }
        elsif ( !-e '/usr/local/cpanel/src/rpm_is_working' ) {
            my $msg = "The RPM did not appear to install.";
            $do_log->($msg);
            return ( 0, $msg );
        }
        else {
            $answer = $self->binary_rpm->cmd_with_logger( $logger, qw{ -e rpm_is_working } );

            if ( my $status = $answer->{status} ) {
                $do_log->("Failed to remove rpm_is_working.");
            }
        }
    }

    return ( 1, '' );
}


sub installed_cpanel_obsoletes ($self) {
    return $self->binary_rpm->installed_obsoletes();
}


sub remove_packages_nodeps ( $self, @pkgs ) {
    return $self->binary_rpm->remove_packages_nodeps(@pkgs);
}


sub lock_for_external_install ( $self, $logger ) {
    return $self->binary_rpm->get_lock_for_cmd( $logger, ['and install external system packages.'] );    # rpm -U needs a lock. we'll use this to make sure the system gives a lock.
}

1;

} # --- END Cpanel/Pkgr/Yum.pm


{ # --- BEGIN Cpanel/Pkgr.pm
package Cpanel::Pkgr;


use cPstrict;

# use Cpanel::OS    ();
# use Cpanel::Alarm ();

# use Cpanel::Pkgr::Apt ();    # PPI USE OK - make these available at runtime regardless of installed OS.
# use Cpanel::Pkgr::Yum ();    # PPI USE OK - make these available at runtime regardless of installed OS.

use constant TIMEOUT => 10 * 60;



our $PKGR;

sub factory {    # just a factory

    die "Cannot compile " . __PACKAGE__ if $INC{'B/C.pm'};

    my $pkg = "Cpanel::Pkgr::" . Cpanel::OS::package_manager_module();
    return $pkg->new;
}

sub instance {
    $PKGR //= factory();

    return $PKGR;
}


sub name() {
    return instance()->name();
}


sub get_package_version ($pkg) {    # ... maybe rename at the end...
    return instance()->get_package_version($pkg);
}


sub is_installed ($pkg) {
    return instance()->is_installed($pkg);
}


sub add_repo_keys (@keys2import) {
    return instance()->add_repo_keys(@keys2import);
}


sub get_version_for_packages (@pkg) {
    return instance()->get_version_for_packages(@pkg);
}


sub get_version_with_arch_suffix (@pkg) {
    return instance()->get_version_with_arch_suffix(@pkg);
}


sub query (@filter) {
    return instance()->query(@filter);
}


sub get_packages_dependencies (@filter) {
    return instance()->get_packages_dependencies(@filter);
}


sub installed_packages (@filter) {
    return instance()->installed_packages(@filter);
}



sub install_or_upgrade_from_file (@paths) {
    return instance()->install_or_upgrade_from_file(@paths);
}


sub list_files_from_package_path ($path) {
    return instance()->list_files_from_package_path($path);
}


sub list_files_from_installed_package ($pkg_name) {
    return instance()->list_files_from_installed_package($pkg_name);
}


sub package_file_is_signed_by_cpanel ($file) {
    return instance()->package_file_is_signed_by_cpanel($file);
}


sub verify_package ( $package, $file = undef ) {
    return instance()->verify_package( $package, $file );
}


sub what_package_owns_this_file ($file) {
    return instance()->what_package_owns_this_file($file);
}


sub what_owns (@list_of_files) {

    die('what_owns() requires at least one search filter')
      if !@list_of_files;

    return instance()->what_owns(@list_of_files);
}


sub what_owns_no_errors (@list_of_files) {

    die('what_owns() requires at least one search filter')
      if !@list_of_files;

    return instance()->what_owns_no_errors(@list_of_files);
}


sub what_provides ($search) {
    return instance()->what_provides($search);
}


sub is_capability_available ($search) {
    return instance->is_capability_available($search);
}


sub what_provides_with_details ($search) {
    return instance()->what_provides_with_details($search);
}


sub get_package_requires ($pkg) {
    return instance()->get_package_requires($pkg);
}


sub get_package_scripts (@pkgs) {
    return instance()->get_package_scripts(@pkgs);
}


sub verify_package_manager_can_install_packages ( $logger = undef ) {

    my $alarm_class = 'TimeoutAlarm';

    my $alarm = Cpanel::Alarm->new(
        TIMEOUT(),
        sub {    #
            die bless {}, $alarm_class;    #
        }
    );

    my ( $status, $msg );
    eval {
        ( $status, $msg ) = instance()->verify_package_manager_can_install_packages($logger);
        1;
    } or do {
        $msg //= $@ // q[Unknown PackageManager issue];
        if ( ref $@ eq $alarm_class ) {
            $msg = q[TIMEOUT: checking package manager sanity];
        }
        return ( 0, $msg );
    };

    return ( $status, $msg );
}


sub installed_cpanel_obsoletes () {
    my $obsoletes = instance()->installed_cpanel_obsoletes();

    my @cpanel_obsoletes = grep { m/^(cpanel-|dovecot|exim|p0f|proftpd|pure-ftpd|site-publisher).+\.cp11/ } @$obsoletes;
    return \@cpanel_obsoletes;
}


sub remove_packages_nodeps (@packages) {
    return instance()->remove_packages_nodeps(@packages);
}


sub lock_for_external_install ($logger) {
    return instance()->lock_for_external_install($logger);
}

1;

} # --- END Cpanel/Pkgr.pm


{ # --- BEGIN Cpanel/Output.pm
package Cpanel::Output;


use cPstrict;

our $debug = ( exists $ENV{'CPANEL_DEBUG_LEVEL'} && $ENV{'CPANEL_DEBUG_LEVEL'} ? int $ENV{'CPANEL_DEBUG_LEVEL'} : 0 );

eval {
    local $SIG{'__WARN__'};
    local $SIG{'__DIE__'};
    require Cpanel::JSON;
};


my $locale;

our $SOURCE_NONE      = '';
our $SOURCE_LOCAL     = 0;
our $SOURCE_REMOTE    = 1;
our $COMPLETE_MESSAGE = 0;
our $PARTIAL_MESSAGE  = 1;

our $PREPENDED_MESSAGE     = 1;
our $NOT_PREPENDED_MESSAGE = 0;

my @constructor_params = qw(
  source
  filehandle
);

sub new {
    my ( $class, %OPTS ) = @_;

    my $self = { map { ( $_ => $OPTS{$_} ) } @constructor_params };
    bless $self, $class;

    $self->{'filehandle'} ||= \*STDOUT;
    $self->{'_parent'} = $OPTS{'parent'};

    $self->{'_indent_level'} = 0;

    $self->_init( \%OPTS ) if $self->can('_init');

    return $self;
}

sub message {
    my ( $self, $message_type, $msg_contents, $source, $partial_message ) = @_;

    $source ||= $self->{'source'};

    die "Could not load Cpanel::JSON" if !$INC{'Cpanel/JSON.pm'};

    return $self->_RENDER(
        {
            'indent'   => $self->{'_indent_level'},
            'pid'      => $$,
            'type'     => $message_type,
            'contents' => $msg_contents,
            'partial'  => $partial_message ? $PARTIAL_MESSAGE : $COMPLETE_MESSAGE,
            $self->_MESSAGE_ADDITIONS( $message_type, $msg_contents ),
            ( $source ? ( 'source' => $source ) : () )
        },
    );
}

sub _RENDER {
    my ( $self, $msg_hr ) = @_;

    return syswrite(
        $self->{'filehandle'},
        Cpanel::JSON::Dump($msg_hr) . "\n",
    );
}

sub _MESSAGE_ADDITIONS { }

sub error {
    return $_[0]->message( 'error', @_[ 1 .. $#_ ] );
}

sub warn {
    return $_[0]->message( 'warn', @_[ 1 .. $#_ ] );
}

sub success {
    return $_[0]->message( 'success', @_[ 1 .. $#_ ] );
}

sub out {
    return $_[0]->message( 'out', @_[ 1 .. $#_ ] );
}

sub debug {
    return unless $debug;
    return $_[0]->message( 'debug', @_[ 1 .. $#_ ] );
}

{
    no warnings qw{once};
    *warning = \&warn;
    *info    = \&out;
}


sub output_highlighted_message {
    my ( $self, $message ) = @_;

    if ( $message =~ m{(?:(?:(?<!log-)error|(?<![a-zA-Z\.])err)[\]\s:]|:\s*bad \S+ name|\* (?:DIE|FATAL)|\] E )}i ) {
        return $self->error($message);
    }
    elsif ( $message =~ m{(?:warn(?:ing)?[\]\s:]|\] W )}i ) {
        return $self->warn($message);
    }
    else {
        return $self->out($message);
    }

    return 1;
}

sub display_message_set {
    my ( $self, $header, $messages ) = @_;

    $self->message( 'header', "$header\n" );

    {
        local $self->{'_indent_level'} = 1 + ( $self->{'_indent_level'} || 0 );

        foreach my $message ( split( m{\n+}, $messages ) ) {
            $self->output_highlighted_message($message);
        }
    }

    return $self->out("\n");
}

sub decrease_indent_level {
    my ($self) = @_;
    if ( !$self->{'_indent_level'} ) {
        CORE::warn("Implementor error! Cannot decrease indent level below 0");
        return;
    }
    return --$self->{'_indent_level'};
}

sub increase_indent_level {
    my ($self) = @_;
    return ++$self->{'_indent_level'};
}

sub get_indent_level ($self) {
    return $self->{'_indent_level'} || 0;
}

sub reset_indent_level {
    my ($self) = @_;
    return ( $self->{'_indent_level'} = 0 );
}

sub create_indent_guard ($self) {
    local ( $@, $! );
    require Cpanel::Context;
    require Cpanel::Finally;

    Cpanel::Context::must_not_be_void();

    $self->increase_indent_level();

    return Cpanel::Finally->new(
        sub {
            $self->decrease_indent_level();
        }
    );
}

sub set_source {
    my ( $self, $source ) = @_;

    $self->{'source'} = $source;
    return 1;
}

sub TO_JSON {
    return '*Cpanel::Output::dummy';
}
1;

} # --- END Cpanel/Output.pm


{ # --- BEGIN Cpanel/Output/Terminal.pm
package Cpanel::Output::Terminal;


use strict;
use warnings;



use constant {
    COLOR_SUCCESS => 'bold green',
    COLOR_WARN    => 'bold bright_yellow on_grey6',
    COLOR_ERROR   => 'bold bright_red on_grey6',
};

1;

} # --- END Cpanel/Output/Terminal.pm


{ # --- BEGIN Cpanel/UTF8.pm
package Cpanel::UTF8;


use strict;

use bytes;    #Required!


sub char_count {    # Get the number of characters, conceptually, of the given string regardless of the argument’s type.
    return scalar @{ get_unicode_as_code_point_list( $_[0] ) };    ##no critic (RequireArgUnpacking)
}

sub get_unicode_as_character_list {    # Get a “Unicode String” version as a list of characters of the given string regardless of the argument’s type.
    return [ map { pack 'U', $_ } @{ get_unicode_as_code_point_list( $_[0] ) } ];    ##no critic (RequireArgUnpacking)
}

sub get_unicode_as_code_point_list {    # Get a “Unicode String” version as a list of code poiints of the given string regardless of the argument’s type.
    return [ unpack 'C0U*', $_[0] ];    ##no critic (RequireArgUnpacking)
}

sub get_unicode_string_from_bytes_string {    ## no critic (RequireArgUnpacking)
    return pack 'U0C*', unpack 'C*', join( '', @_ );
}

sub get_bytes_string_from_unicode_string {    ## no critic (RequireArgUnpacking)
    no bytes;                                 # usage of bytes was causing this join to return a bytes string.
    return pack 'C0U*', unpack 'U*', join( '', @_ );
}

1;

} # --- END Cpanel/UTF8.pm


{ # --- BEGIN Cpanel/StringFunc/Fmt.pm


package Cpanel::StringFunc::Fmt;

use strict;

# use Cpanel::UTF8 ();

our $ALIGN_LEFT  = 0;
our $ALIGN_RIGHT = 1;

sub bare_wrap {
    my ( $text, $max )  = @_;
    my ( $ret,  $line ) = ( '', '' );
    $text =~ s{$/$/}{$/\f$/}g;
    for ( split m{[$/\t ]+}, $text ) {
        if ( ( $_ eq "\f" ) || ( $line && Cpanel::UTF8::char_count($line) + Cpanel::UTF8::char_count($_) > $max ) ) {
            $ret .= ( $ret ? $/ : '' ) . $line;
            if ( $_ eq "\f" ) {
                $ret .= $/;
                $line = '';
            }
            else {
                $line = $_;
            }
        }
        else {
            $line .= ( $line ? ' ' : '' ) . $_;
        }
    }

    if ( length $line ) {
        $ret .= ( length $ret ? $/ : q{} ) . $line;
    }

    return $ret;
}

sub wrap {
    my ( $text, $max ) = @_;

    return bare_wrap( $text, $max ) . $/;
}

sub fixed_length {
    my ( $text, $length, $align ) = @_;

    my $text_is_ascii = $text !~ tr/\x00-\x7E//c ? 1 : 0;
    my $fixed_txt;
    if ( defined $length ) {
        if ($text_is_ascii) {
            $fixed_txt = substr( $text, 0, $length );
        }
        else {
            my $chars_ar = Cpanel::UTF8::get_unicode_as_character_list($text);
            splice @$chars_ar, $length if $length < @$chars_ar;
            $fixed_txt = join( q<>, @$chars_ar );
        }
    }
    else {
        $fixed_txt = $text;
    }

    my $char_count = $text_is_ascii ? length $fixed_txt : Cpanel::UTF8::char_count($fixed_txt);

    if ( $char_count < $length ) {
        if ( $align && $align == $ALIGN_RIGHT ) {
            my $padding = ' ' x ( $length - $char_count );
            substr( $fixed_txt, 0, 0, $padding );
        }
        else {
            return pack( "A$length", $fixed_txt );
        }
    }

    return $fixed_txt;
}

1;

} # --- END Cpanel/StringFunc/Fmt.pm


{ # --- BEGIN Cpanel/Output/Formatted.pm
package Cpanel::Output::Formatted;


use strict;
use warnings;

# use Cpanel::Output();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Output); }

# use Cpanel::Output::Terminal ();
# use Cpanel::ScalarUtil       ();
# use Cpanel::StringFunc::Fmt  ();

use constant {
    _prepend_message => q{},

    INDENT_AFTER_PREPEND => 0,
};

sub _init {
    my ($self) = @_;

    return $self->reset();
}

sub reset {
    my ($self) = @_;

    $self->{'_indent_level'}             = 0;
    $self->{'_last_message_had_newline'} = 1;    # Assume we start on a fresh line

    return 1;
}

sub message {    ## no critic qw(Subroutines::ProhibitManyArgs)
    my ( $self, $message_type, $msg_contents, $source, $partial_message, $prepend_message ) = @_;

    my $message_as_text = ( 'HASH' eq ref $msg_contents ) ? $msg_contents->{'msg'} : $msg_contents;

    if ( ref($message_as_text) && Cpanel::ScalarUtil::blessed($message_as_text) ) {
        $message_as_text .= q<>;
    }

    if ( $message_type eq 'failed' || $message_type eq 'fail' || $message_type eq 'error' ) {
        $self->_safe_render_message( $message_as_text, Cpanel::Output::Terminal::COLOR_ERROR(), $partial_message, $prepend_message );
    }
    elsif ( $message_type eq 'warn' ) {
        $self->_safe_render_message( $message_as_text, Cpanel::Output::Terminal::COLOR_WARN(), $partial_message, $prepend_message );
    }
    elsif ( $message_type eq 'success' ) {
        $self->_safe_render_message( $message_as_text, Cpanel::Output::Terminal::COLOR_SUCCESS(), $partial_message, $prepend_message );
    }
    elsif ( $message_type eq 'header' ) {
        $self->_safe_render_message( $message_as_text, 'bold', $partial_message, $prepend_message );
    }
    elsif ( grep { $message_type eq $_ } qw{out debug} ) {
        if ( $source && $source->{'host'} ) {
            $self->_safe_render_message( $message_as_text, 'bold black on_white', $partial_message, $prepend_message );

        }
        else {
            $self->_safe_render_message( $message_as_text, $Cpanel::Output::SOURCE_NONE, $partial_message, $prepend_message );
        }
    }
    else {
        if ( ref $msg_contents ) {
            print { $self->{'filehandle'} } "UNHANDLED TYPE: [$message_type]: " . join( ', ', map { "$_ => $msg_contents->{$_}" } keys %{$msg_contents} ) . "\n";
        }
        else {
            print { $self->{'filehandle'} } "UNHANDLED TYPE: [$message_type]: $message_as_text\n";
        }
    }

    return;
}

sub format_message {

    return $_[0]->_format_text( $_[1] || '', $_[2] );
}

sub _safe_render_message {
    my ( $self, $msg, $color, $partial_message, $prepend_message ) = @_;

    $msg = join( "\n", @{$msg} ) if ref $msg;

    $msg = q<> if !defined $msg;

    my $last_line_ends_with_new_line = ( length $msg && substr( $msg, -1, 1 ) eq "\n" ) ? 1 : 0;
    my @lines                        = split( /\n/, $msg );

    @lines = ('') if !@lines;

    my $last_line_to_add_new_line = -1;
    if ( scalar @lines == 1 ) {
        if ( !$partial_message || $last_line_ends_with_new_line ) {
            $last_line_ends_with_new_line = 1;
            $last_line_to_add_new_line    = 1;
        }
    }
    else {
        $last_line_to_add_new_line    = $#lines - ( $partial_message ? 1 : 0 );
        $last_line_ends_with_new_line = $#lines == $last_line_to_add_new_line ? 1 : 0;
    }

    my $output;

    foreach my $count ( 0 .. $#lines ) {
        $output = $self->{'_last_message_had_newline'} ? $self->_indent() : '';

        my $prepend = $prepend_message ? $self->_prepend_message() : q{};

        if ( $self->INDENT_AFTER_PREPEND() ) {
            substr( $output, 0, 0, $prepend );
        }
        else {
            $output .= $prepend;
        }

        $output .=                                             #
          $self->format_message( $color, $lines[$count] ) .    #

          ( $count <= $last_line_to_add_new_line ? $self->_new_line() : q{} );    #

        if ( $self->{'_parent'} ) {
            my $pid = $self->{'_parent'}{'pid'};
            my ( $queue, $child_number, $item_name, $item ) = @{ $self->{'_parent'}{'contents'} }{ 'queue', 'child_number', 'item_name', 'item' };

            my $pid_info       = ( $self->{'fmt_cache_pid'}{$pid}                                  //= Cpanel::StringFunc::Fmt::fixed_length( $pid,                   6, $Cpanel::StringFunc::Fmt::ALIGN_RIGHT ) );
            my $job_info       = ( $self->{'fmt_cache_queue_child_number'}{"$queue:$child_number"} //= Cpanel::StringFunc::Fmt::fixed_length( "$queue:$child_number", 10 ) );
            my $item_info      = ( $self->{'fmt_cache_item_name'}{$item_name}                      //= Cpanel::StringFunc::Fmt::fixed_length( $item_name,             1 ) );
            my $item_formatted = ( $self->{'fmt_cache_item'}{$item}                                //= Cpanel::StringFunc::Fmt::fixed_length( $item,                  16 ) );
            substr(
                $output, 0, 0,
                $self->format_message( 'base1', "[" . $pid_info . "]" . "[" . $job_info . "]" . "[" . $item_info . ':' . $item_formatted . "]" . ": " )
            );
        }

        print { $self->{'filehandle'} } $output;
    }

    $self->{'_last_message_had_newline'} = $last_line_ends_with_new_line;

    return;
}

1;


} # --- END Cpanel/Output/Formatted.pm


{ # --- BEGIN Cpanel/Output/Formatted/Plain.pm
package Cpanel::Output::Formatted::Plain;



use strict;

our $VERSION = '1.0';

# use Cpanel::Output::Formatted();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Output::Formatted); }

our $product_dir = '/var/cpanel';

use constant _new_line => "\n";

sub _indent {
    return $_[0]->{'_indent_level'} ? ( "\t" x $_[0]->{'_indent_level'} ) : '';
}

sub _format_text {

    return $_[2];
}

1;

} # --- END Cpanel/Output/Formatted/Plain.pm


{ # --- BEGIN Cpanel/Output/Formatted/Terminal.pm
package Cpanel::Output::Formatted::Terminal;


use strict;

our $VERSION = '1.0';

# use Cpanel::Output::Formatted::Plain();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Output::Formatted::Plain); }

our $product_dir = '/var/cpanel';

my $_tried_to_load_solarize = 0;

sub _try_to_load_solarize {
    unless ( $INC{'Cpanel/Term/ANSIColor/Solarize.pm'} ) {
        local $SIG{'__DIE__'};
        local $SIG{'__WARN__'};
        eval q{require Cpanel::Term::ANSIColor::Solarize};    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
    }
    return ( $_tried_to_load_solarize = 1 );
}

my $_disable_color;

sub _format_text {
    my ( $self, $color, $text ) = @_;

    if ($color) {
        $self->_disable_color() if !defined $_disable_color;
        if ( !$_disable_color ) {
            _try_to_load_solarize() if !$_tried_to_load_solarize;
            if ( $INC{'Cpanel/Term/ANSIColor/Solarize.pm'} && $color ) {
                return Cpanel::Term::ANSIColor::Solarize::colored( [$color], $text );
            }
        }
    }

    return $self->SUPER::_format_text( $color, $text );
}

sub _disable_color {
    return $_disable_color if defined $_disable_color;

    local $@;
    eval {
        $_disable_color = -e $product_dir . '/disable_cpanel_terminal_colors' ? 1 : 0;
        $_disable_color ||= -e $product_dir . '/disabled/terminal-colors' ? 1 : 0;
    };

    return $_disable_color;
}

sub _clear_cache {
    undef $_disable_color;
    return;
}

1;


} # --- END Cpanel/Output/Formatted/Terminal.pm


{ # --- BEGIN Cpanel/SysPkgs/Base.pm
package Cpanel::SysPkgs::Base;


use cPstrict;

use Try::Tiny;

use Carp ();

# use Cpanel::EA4::Constants     ();
# use Cpanel::OS                 ();
# use Cpanel::Pkgr               ();
# use Cpanel::Config::LoadCpConf ();




sub new ( $class, $self ) {

    die unless ref $self;
    $self = bless $self, $class;

    if ( !$self->{'output_obj'} || ref $self->{'output_obj'} eq 'HASH' ) {
        if ( $self->{'logger'} ) {
            $self->{'output_is_logger'} = 1;
            $self->{'output_obj'}       = $self->{'logger'};
        }
        else {
            require Cpanel::Output::Formatted::Terminal;
            $self->{'output_obj'} = Cpanel::Output::Formatted::Terminal->new();
        }
    }

    $self->{'excludes'}        ||= $self->default_exclude_list();
    $self->{'exclude_options'} ||= {};
    $self->{'exclude_remove'}  ||= [];
    $self->{'system_perl_bin'} ||= '/usr/bin/perl';

    return $self;
}

sub is_system_perl_unaltered ($self) {
    return Cpanel::Pkgr::verify_package( Cpanel::OS::system_package_providing_perl(), $self->{'system_perl_bin'} );
}

sub is_system_ruby_unaltered ($self) {
    return Cpanel::Pkgr::verify_package( 'ruby', '/usr/bin/ruby' );
}



sub out ( $self, @args ) {
    return $self->{'output_obj'}->out(@args);
}

sub error ( $self, @args ) {
    return $self->{'output_obj'}->error(@args);
}

sub warn ( $self, @args ) {
    return $self->{'output_obj'}->warn(@args);
}


sub install ( $self, %opts ) {

    my ( $ret, $err );
    try {
        $ret = $self->install_packages(%opts);
    }
    catch {
        $err = $_;
    };

    if ($err) {
        require Cpanel::Exception;
        my $error_as_string = Cpanel::Exception::get_string($err);
        $self->error($error_as_string);
        return 0;
    }

    return $ret;
}


sub update ( $self, @args ) {
    ref $self or Carp::croak("update() must be called as a method.");

    return $self->install( @args, 'command' => ['update'] );
}


sub reinstall ( $self, @args ) {
    ref $self or Carp::croak("reinstall() must be called as a method.");

    return $self->install( @args, 'command' => ['reinstall'] );
}


sub default_exclude_list ($self) {

    return Cpanel::OS::system_exclude_rules();
}


sub reinit ( $self, $exclude_options ) {

    $self->{'excludes'}        = $self->default_exclude_list();
    $self->{'exclude_options'} = $exclude_options or die;

    return;
}


sub get_repo_details {
    my ( $self, $repo2eli5 ) = @_;

    my %desc = (
        EA4 => {
            remote_path => scalar( Cpanel::EA4::Constants::repo_file_url() ),     # ea4_from_custom_repo_url
            local_path  => scalar( Cpanel::EA4::Constants::repo_file_path() ),    # ea4_from_custom_repo_path
        }
    );

    die "Unknown repo $repo2eli5" unless exists $desc{$repo2eli5};

    return $desc{$repo2eli5};
}


sub add_repo_key {
    die "Defined in subclass";
}

sub ensure_plugins_turned_on {
    return;
}

sub add_repo {
    return { 'success' => 1 };
}


sub has_exclude_rule_for_package ( $self, $pkg ) {
    die "Defined in subclass";
}


sub drop_exclude_rule_for_package ( $self, $pkg ) {
    die "Defined in subclass";
}


sub add_exclude_rule_for_package ( $self, $pkg ) {
    die "Defined in subclass";
}

sub setup {
    return;
}

sub check_and_set_exclude_rules {
    die q[check_and_set_exclude_rules: Not implemented];
}

sub validate_excludes ($self) {

    $self->exclude_kernel(1) if $self->should_block_kernel_updates;

    $self->exclude_perl(0) if $self->is_system_perl_unaltered;

    $self->exclude_ruby(0) if $self->is_system_ruby_unaltered;

    return;
}

sub enable_module_stream ( $self, $module, $version ) {
    return;
}

sub disable_module ( $self, $module ) {
    return;
}

sub exclude_kernel ( $self, $set = undef ) {
    return $self->_get_set_exclude_for( 'kernel', $set );
}

sub exclude_ruby ( $self, $set = undef ) {
    return $self->_get_set_exclude_for( 'ruby', $set );
}

sub exclude_perl ( $self, $set = undef ) {
    return $self->_get_set_exclude_for( 'perl', $set );
}

sub exclude_bind_chroot ( $self, $set = undef ) {
    return $self->_get_set_exclude_for( 'bind-chroot', $set );
}

sub _get_set_exclude_for ( $self, $name, $set = undef ) {
    $self->{exclude_options}->{$name} = $set if defined $set;
    return $self->{exclude_options}->{$name} // 0;
}

sub check_is_enabled ($self) {

    return if -e '/etc/checkyumdisable';
    return if -e '/etc/checkaptdisable';

    return 1;
}

sub should_block_kernel_updates ($self) {

    return 1 if -e '/var/cpanel/checkyum-keepkernel';

    return 1 if -e '/var/cpanel/block-kernel-updates';

    my $cpconf = Cpanel::Config::LoadCpConf::loadcpconf_not_copy();
    return $cpconf->{'rpmup_allow_kernel'} ? 0 : 1;    # do not block kernel by default
}

1;

} # --- END Cpanel/SysPkgs/Base.pm


{ # --- BEGIN Cpanel/SysPkgs/APT.pm
package Cpanel::SysPkgs::APT;


use cPstrict;


use Try::Tiny;

# use Cpanel::Binaries::Debian::Apt                      ();
# use Cpanel::Binaries::Debian::AptCache                 ();
# use Cpanel::Binaries::Debian::AptGet                   ();
# use Cpanel::Binaries::Debian::AptKey                   ();
# use Cpanel::Binaries::Debian::AptMark                  ();
# use Cpanel::CPAN::IO::Callback::Write                  ();
# use Cpanel::Debug                                      ();
# use Cpanel::Exception                                  ();
# use Cpanel::Finally                                    ();
# use Cpanel::OS                                         ();
# use Cpanel::Parser::Callback                           ();
# use Cpanel::Set                                        ();
# use Cpanel::SysPkgs::APT::Preferences::ExcludePackages ();
# use Cpanel::TimeHiRes                                  ();
# use Cpanel::Validate::FilesystemNodeName               ();

use IO::Handle;

# use Cpanel::SysPkgs::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::SysPkgs::Base); }

use constant _ENOENT => 2;

our $APT_CONF      = '/etc/apt/apt.conf.d/01-cpanel';    # TODO: temporary guesstimate of what apt conf name we might use, if anything
our $VERSION       = '1.0';                              # TODO: This only appears to be used in a log message in one place, useless ?
our $FORCE_DRY_RUN = 0;                                  # For testing


sub new ( $class, $self ) {

    $self = $class->SUPER::new($self);
    bless $self, $class;

    $self->{'apt.conf'} = $APT_CONF;

    $self->{'VERSION'} = $VERSION;

    return $self;
}



sub haspkg {
    return;
}

sub update ( $self, %opts ) {
    ref $self or Carp::croak("update() must be called as a method.");

    my @command;
    if ( !$opts{'packages'} && !$opts{'pkglist'} ) {

        @command = $self->should_block_kernel_updates ? ('upgrade') : ( 'upgrade', '--with-new-pkgs' );
    }
    else {
        @command = ( 'install', '--only-upgrade' );
    }

    return $self->install( %opts, 'command' => \@command, is_update => 1 );
}

sub ensure ( $self, @args ) {
    ref $self or Carp::croak("ensure() must be called as a method.");

    return $self->install(@args);
}

sub reinstall ( $self, @args ) {

    ref $self or Carp::croak("reinstall() must be called as a method.");

    return $self->install( @args, 'command' => [ 'reinstall', '-yf' ] );
}



sub install ( $self, %opts ) {

    ref $self or Carp::croak("install() must be called as a method.");

    my ( $ret, $err );
    try {
        $ret = $self->install_packages(%opts);
    }
    catch {
        $err = $_;
    };

    if ($err) {
        my $error_as_string = Cpanel::Exception::get_string($err);
        $self->error($error_as_string);
        return 0;
    }

    return $ret;
}

sub uninstall_packages ( $self, %opts ) {

    $opts{'extra_args'} = '-yf';

    return $self->_call_apt( %opts, 'command' => ['purge'] );
}

sub install_packages ( $self, %opts ) {

    $opts{'extra_args'} = '-yf';

    return $self->_call_apt(%opts);
}

sub download_packages ( $self, %opts ) {

    $opts{'download_only'} = 1;
    $opts{'extra_args'}    = '-y';

    return $self->_call_apt( %opts, 'command' => ['install'] );
}

sub clean ($self) {
    return $self->_call_apt( 'command' => ['clean'] );
}

sub check_and_set_exclude_rules ($self) {


    $self->validate_excludes();

    my $exclude_customized = {
        kernel => $self->exclude_kernel(),

    };

    my $excludes      = $self->{'excludes'};
    my @current_rules = $self->list_exclude_rules;
    my @wanted_rules;

    foreach my $exclude_name ( sort keys $excludes->%* ) {

        next if exists $exclude_customized->{$exclude_name} && !$exclude_customized->{$exclude_name};

        my @rules = split( /\s+/, $excludes->{$exclude_name} );
        push @wanted_rules, @rules;
    }

    my @to_add  = Cpanel::Set::difference( \@wanted_rules,  \@current_rules );
    my @to_drop = Cpanel::Set::difference( \@current_rules, \@wanted_rules );

    $self->drop_exclude_rule_for_package($_) for @to_drop;
    $self->add_exclude_rule_for_package($_)  for @to_add;

    return 1;
}

sub checkdb {
    return 1;
}

sub checkconfig ($self) {
    ref $self or Carp::croak("checkconfig() must be called as a method.");

    my $res       = $self->_apt->cmd( info => 'libc6' );
    my $glibcinfo = $res->{output} // '';

    if ( $glibcinfo !~ m/^Package: libc6/m || $glibcinfo =~ m/No packages found/ ) {
        return 0;
    }

    return 1;
}


sub verify_package_version_is_available ( $self, %opts ) {

    die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'package' ] ) if !defined $opts{'package'};
    die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'version' ] ) if !defined $opts{'version'};

    my $details = $self->_apt_cache->show_all_versions( $opts{'package'} ) // [];
    foreach my $record (@$details) {
        return 1 if $record->{'version'} =~ m/^\Q$opts{'version'}\E/;
    }
    die "The package “$opts{'package'}” with version “$opts{'version'}” is not available via apt";
}

sub can_packages_be_installed ( $self, %opts ) {

    if ( !defined $opts{'packages'} ) {
        die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'packages' ] );
    }

    my $ignore_conflict_packages_regexp = $opts{'ignore_conflict_packages_regexp'};

    my $apt_stderr = '';
    my $err;

    try {
        $self->_call_apt(
            %opts,
            'command'         => ['install'],
            'dry_run'         => 1,
            'stderr_callback' => sub {
                my ($data) = @_;
                $apt_stderr .= $data;
                return 1;
            }
        );
    }
    catch {
        $err = $_;
    };

    if ($err) {
        if (   UNIVERSAL::isa( $err, 'Cpanel::Exception::ProcessFailed' )
            && $ignore_conflict_packages_regexp
            && $self->_should_ignore_package_conflicts_in_apt_error_output( $apt_stderr, $ignore_conflict_packages_regexp ) ) {
            return 1;
        }

        $self->error( Cpanel::Exception::get_string($err) );
        return 0;
    }

    return 0
      if ref( $opts{'check_apt_preinstall_stderr'} ) eq 'CODE'
      && $opts{'check_apt_preinstall_stderr'}->($apt_stderr);

    return 1;
}


sub add_repo_key ( $self, $key ) {

    my $run = $self->_apt_key->cmd( add => $key );
    return 1 if $run->{status} == 0;

    $self->warn("Could not import the public key '$key'");
    return 0;
}

sub add_repo_key_by_id ( $self, $key_id ) {

    my $run = $self->_apt_key->cmd( qw{adv --keyserver keyserver.ubuntu.com --recv-keys }, $key_id );

    return $run->{'status'} == 0 ? 1 : 0;
}

sub _apt_mark ($self) {
    return $self->{_apt_mark} //= Cpanel::Binaries::Debian::AptMark->new();
}

sub _apt_key ($self) {
    return $self->{_apt_key} //= Cpanel::Binaries::Debian::AptKey->new();
}

sub _apt_cache ($self) {
    return $self->{_apt_cache} //= Cpanel::Binaries::Debian::AptCache->new();
}

sub _apt ($self) {
    return $self->{_apt} //= Cpanel::Binaries::Debian::Apt->new();
}

sub _apt_pref_exclude_packages ($self) {
    return $self->{_apt_pref_exclude_packages} //= Cpanel::SysPkgs::APT::Preferences::ExcludePackages->new();
}



sub has_exclude_rule_for_package ( $self, $pkg ) {

    my $exclude_list = $self->_apt_mark->showhold();

    my $has_exclude = grep { $_ eq $pkg } $exclude_list->@*;
    return 1 if $has_exclude;

    return $self->_apt_pref_exclude_packages->has_rule_for_package($pkg);
}


sub drop_exclude_rule_for_package ( $self, $pkg ) {

    return unless $self->has_exclude_rule_for_package($pkg);

    $self->_apt_mark->unhold($pkg);

    return $self->_apt_pref_exclude_packages->remove($pkg);
}


sub add_exclude_rule_for_package ( $self, $pkg ) {

    return if $self->has_exclude_rule_for_package($pkg);

    return $self->_apt_pref_exclude_packages->add($pkg);
}


sub list_exclude_rules ($self) {
    return keys $self->_apt_pref_exclude_packages->content->%*;
}


sub reinit {
    my ( $self, $exclude_options ) = @_;
    $self->{'excludes'}        = default_exclude_list();
    $self->{'exclude_options'} = $exclude_options || die;
    return;
}


sub repolist ( $self, %opts ) {

    return 1;
}


my $updated;

sub _call_apt ( $self, %opts ) {

    my $packages         = $opts{'packages'}         || $opts{'pkglist'} || [];    # pkglist is for legacy calls
    my $exclude_packages = $opts{'exclude_packages'} || [];
    my $command          = $opts{'command'}          || ['install'];
    my $download_only    = $opts{'download_only'} ? 1 : 0;
    my $download_dir     = $opts{'download_dir'};
    my $dry_run          = $opts{'dry_run'} ? 1 : 0;
    my $disable_plugins  = $opts{'disable_plugins'} || [];
    my $is_base_install  = defined( $ENV{'CPANEL_BASE_INSTALL'} );
    my $extra_args       = $opts{'extra_args'} || '';

    my @args = $self->_base_apt_args();
    push @args, $extra_args       if $extra_args;
    push @args, '--assume-no'     if ( $dry_run || $FORCE_DRY_RUN );
    push @args, '--download-only' if $download_only;

    push @args, ( '-o', 'Dir::Cache=' . "$download_dir", '-o', 'Dir::Cache::archives=' . "$download_dir" ) if $download_dir;

    if ( scalar( @{$command} ) && $command->[0] && grep { $command->[0] eq $_ } qw{install upgrade} ) {
        $updated = $self->_exec_apt( '_args' => ['update'] ) if !$updated;
        push @args, qw(
          -o Acquire::Retries=3
          -o Dpkg::Options::=--force-confdef
          -o Dpkg::Options::=--force-confold
        );
    }

    foreach my $package ( @{$exclude_packages} ) {
        Cpanel::Validate::FilesystemNodeName::validate_or_die($package);

    }

    push @args, @{$command};
    foreach my $package ( @{$packages} ) {
        Cpanel::Validate::FilesystemNodeName::validate_or_die($package);
        push @args, $package;
    }

    my $restore_excludes_guard = $self->setup_excludes_file( $opts{'is_update'} );
    return $self->_exec_apt( %opts, '_args' => \@args );
}

sub setup_excludes_file ( $self, $is_update ) {

    $self->check_and_set_exclude_rules;

    my $kernel_rules    = Cpanel::OS::system_exclude_rules()->{'kernel'} or die;
    my @kernel_packages = split( /\s+/, $kernel_rules );

    if ( $is_update && $self->should_block_kernel_updates ) {
        my $f = Cpanel::Finally->new(
            sub {
                $self->out( '# Restoring updates for kernel packages: ' . join( ', ', @kernel_packages ) );
                $self->drop_exclude_rule_for_package($_) for @kernel_packages;
            }
        );
        $self->out( '# Excluding updates for kernel packages: ' . join( ', ', @kernel_packages ) );
        $self->add_exclude_rule_for_package($_) for @kernel_packages;
        return $f;
    }

    $self->drop_exclude_rule_for_package($_) for @kernel_packages;

    return;
}

sub _exec_apt ( $self, %opts ) {

    my $stdout_callback    = $opts{'stdout_callback'};
    my $stderr_callback    = $opts{'stderr_callback'};
    my $handle_child_error = $opts{'handle_child_error'} || \&_die_child_error;

    local @ENV{qw{LANG LANGUAGE LC_ALL LC_MESSAGES LC_CTYPE}} = qw{C C C C C};
    local @ENV{qw{DEBIAN_FRONTEND DEBIAN_PRIORITY}}           = qw{noninteractive critical};

    my $start_time = Cpanel::TimeHiRes::time();
    my $stderr     = '';

    my $callback_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->out(@_); return 1; } );

    my $callback_err_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->warn(@_); return 1; } );

    $self->{'logger'}->info("Starting apt execution “@{$opts{'_args'}}”.") if $self->{'logger'};
    Cpanel::Debug::log_info("Starting apt execution “@{$opts{'_args'}}”.");

    my $apt_obj = Cpanel::Binaries::Debian::AptGet->new();
    my $result  = $apt_obj->run(
        'args'   => $opts{'_args'},
        'stdin'  => $opts{'stdin'},
        'stdout' => Cpanel::CPAN::IO::Callback::Write->new(
            sub {
                my ($data) = @_;
                $data .= "\n" if substr( $data, -1 ) ne "\n";    # ensure a newline here so we don't make Cpanel::Parser::Line’s buffer keep concatenating lines without a newline and repeating them over and over and …

                if ( $data =~ m{\w+\s*:\s.*\d+/\d+}m ) {
                    $data =~ s/[\x00-\x0A]+//go;
                    $data .= "\n";                               # re-add the newline we just stripped out
                }

                if ($stdout_callback) {
                    $stdout_callback->($data);
                }
                else {
                    $callback_obj->process_data($data);
                }
                return;
            }
        ),
        'stderr' => Cpanel::CPAN::IO::Callback::Write->new(
            sub {
                my ($data) = @_;
                $data .= "\n" if substr( $data, -1 ) ne "\n";    # ensure a newline here so we don't make Cpanel::Parser::Line’s buffer keep concatenating lines without a newline and repeating them over and over and …

                $stderr .= $data;
                if ($stderr_callback) {
                    $stderr_callback->($data);
                }
                else {
                    $callback_err_obj->process_data($data);
                }
                return;
            }
        ),
        'timeout' => 7200,    # 2 hour timeout
    );

    $callback_obj->finish();
    $callback_err_obj->finish();
    my $end_time  = Cpanel::TimeHiRes::time();
    my $exec_time = sprintf( "%.3f", ( $end_time - $start_time ) );
    $self->{'logger'}->info("Completed apt execution “@{$opts{'_args'}}”: in $exec_time second(s).") if $self->{'logger'};
    Cpanel::Debug::log_info("Completed apt execution “@{$opts{'_args'}}”: in $exec_time second(s).");

    if ( $result->CHILD_ERROR() && !grep( /^(?:--assumeno|--assume-no)$/, @{ $opts{'_args'} } ) ) {
        return $handle_child_error->( $result, $stderr, %opts );
    }

    return 1;
}

sub _base_apt_args ($self) {

    return;
}

sub _die_child_error ( $result, $stderr, %opts ) {

    if ( $stderr =~ m/does not have a stable CLI interface/ ) {
        return;
    }
    $result->die_if_error();

    return;    ## Just to satisfy cplint; we never actually get here.
}

sub _should_ignore_package_conflicts_in_apt_error_output ( $self, $apt_stderr, $ignore_conflict_packages_regexp ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    my @output = split( m{\n}, $apt_stderr );

    my ( $has_error_summary, $in_error_summary, $has_transaction_check_error, $in_transaction_check_error );

    foreach my $line (@output) {
        if ( $line =~ m{^---} ) {
            next;
        }
        elsif ( $line =~ m/^[ \t]*Error Summary/i ) {
            $has_error_summary = $in_error_summary = 1;
        }
        elsif ( $line =~ m/^[ \t]*Transaction Check Error/i ) {
            $has_transaction_check_error = $in_transaction_check_error = 1;
        }
        elsif ( $line =~ m{^\s*$} ) {
            $in_error_summary = $in_transaction_check_error = 0;
        }
        elsif ($in_transaction_check_error) {
            if ( $line =~ m{conflicts with.*?package $ignore_conflict_packages_regexp} ) {

                next;
            }
            else {
                return 0;
            }
        }
        elsif ($in_error_summary) {
            return 0;
        }
    }

    if ($has_transaction_check_error) {
        $self->out("All Package conflicts matched allowed.");
        return 1;
    }

    return 0;
}

sub ensure_plugins_turned_on {
    return 1;
}

sub search ( $self, %opts ) {
    return $self->_search(%opts);
}

sub search_installed ( $self, %opts ) {
    my $result = $self->_search(%opts);
    return unless ref $result;

    return [ grep { $_->{installed} && $_->{installed} =~ qr{installed} } $result->@* ];
}

sub _search ( $self, %opts ) {

    my $bin = $self->_apt;
    my $got = $bin->cmd( 'search', $opts{'pattern'} );

    return if $got->{'status'};    # Non-zero exit code leads to no result.

    my $re = qr/$opts{'pattern'}/;

    my @lines = grep { $_ && $_ =~ $re } map { split( m/\n/, $_ ) } $got->{'output'};

    $re = qr{^([a-zA-Z-]+)-([0-9.-]+)-([a-zA-Z]+)[/a-zA-Z,-]+\s\2\.(\d+).*\s([a-zA-Z0-9]+)\s{0,1}(\[.+\])?$}x;
    my @found = map {
        my $str = $_;
        $str =~ $re;
        {
            name      => $1,
            version   => $2,
            type      => $3,
            release   => $4,
            arch      => $5,
            installed => $6,
            package   => "$1-$2-$3"
        }
    } @lines;

    if (@found) {
        if ( $opts{'all'} ) {
            return \@found;
        }
        else {
            my @sorted = sort { $a->{'release'} <=> $b->{'release'} } @found;
            return [ ( $sorted[-1] ) ];
        }
    }
    else {
        return;
    }
}

sub add_repo ( $self, %opts ) {

    my ( $remote_path, $real_path ) = @opts{qw{remote_path local_path}};

    my $renamed_to = $real_path . substr( rand, 1 ) . '-' . ( localtime =~ tr< ><_>r );

    if ( open my $rfh, '<', $real_path ) {
        require File::Copy;
        if ( File::Copy::copy( $rfh => $renamed_to ) ) {
            CORE::warn "“$real_path” is about to be rewritten. The old file has been copied to “$renamed_to”.\n";
        }
        else {
            die "The system failed to copy “$real_path” to “$renamed_to” ($!).\n";
        }
    }
    elsif ( $! != _ENOENT() ) {
        CORE::warn "open(< $real_path): $!";
    }

    require Cpanel::HTTP::Tiny::FastSSLVerify;
    my $http = Cpanel::HTTP::Tiny::FastSSLVerify->new();
    my $ret  = $http->mirror( $remote_path, $real_path );

    return $ret;
}

sub reinstall_packages {
    die "Unimplemented!";
}


sub list_available ( $self, %opts ) {
    my @args;

    my $pattern = $opts{'search_pattern'} // '.';    # This should be safe from a shell injection.

    my $apt_obj = $self->_apt;
    my $result  = $apt_obj->cmd( 'search', $pattern );
    $result->{'status'} == 0 or return {};           # Error should not happen.
    my @lines = split "\n", $result->{'output'};
    delete $result->{'output'};                      # Save some memory.

    my @packages;
    my $p = 0;
    while ( scalar @lines ) {
        my $line = shift @lines;

        $line =~ m{^(\S[^/]*)/(\S+)\s+(\S+)\s+(\S+)\s*$} or next;    # 0ad/focal 0.0.23.1-4ubuntu3 amd64
        my ( $package_name, $repo, $version, $arch ) = ( $1, $2, $3, $4 );

        my $description = '';
        while ( $lines[0] && $lines[0] =~ /^  (\S.+)/ ) {
            $description .= "$1\n";
            shift @lines;
        }
        chomp $description;

        next if $opts{'disable_ea4'} && $package_name =~ m/^ea-/i;

        push @packages, {
            'name'          => $package_name,            #
            'version'       => $version,                 #
            'repo'          => $repo,                    #
            'arch'          => $arch,                    #
            'name_and_arch' => "$package_name:$arch",    #
            'description'   => $description
        };
    }

    return \@packages;
}

sub is_epel_installed {
    return 0;
}

sub is_epel_enabled {
    return 0;
}

1;

} # --- END Cpanel/SysPkgs/APT.pm


{ # --- BEGIN Cpanel/Binaries/Yum.pm
package Cpanel::Binaries::Yum;



use cPstrict;

# use Cpanel::Binaries::Cmd();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Cmd); }


sub bin_path ($self) {
    return '/usr/bin/yum';
}


sub locks_to_wait_for { return qw{/var/lib/rpm/.rpm.lock /var/run/yum.pid} }


sub lock_to_hold { return 'rpmdb' }


sub needs_lock ( $self, $action, @args ) {
    return 0 if grep { $action eq $_ } qw/version repolist repo-pkgs provides list info history/;

    return 1;
}

1;

} # --- END Cpanel/Binaries/Yum.pm


{ # --- BEGIN Cpanel/Repos/Utils.pm
package Cpanel::Repos::Utils;


use cPstrict;

# use Cpanel::OS            ();
# use Cpanel::Binaries::Yum ();


sub post_install() {

    return unless Cpanel::OS::can_clean_plugins_repo();

    require Cpanel::Binaries::Yum;

    my $result = Cpanel::Binaries::Yum->new->cmd( 'clean', 'plugins' );
    warn $result->{'output'} if $result->{'status'};

    return 1;

}

1;

} # --- END Cpanel/Repos/Utils.pm


{ # --- BEGIN Cpanel/SysPkgs/YUM.pm
package Cpanel::SysPkgs::YUM;


use cPstrict;


# use Cpanel::SysPkgs::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::SysPkgs::Base); }

use Try::Tiny;

# use Cpanel::SafeFile                     ();
# use Cpanel::Exception                    ();
# use Cpanel::FileUtils::Write             ();
# use Cpanel::TimeHiRes                    ();
# use Cpanel::Debug                        ();
# use Cpanel::Binaries                     ();
# use Cpanel::CPAN::IO::Callback::Write    ();
# use Cpanel::Parser::Callback             ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::StringFunc::Trim             ();
# use Cpanel::OS                           ();
# use Cpanel::Repos::Utils                 ();
# use Cpanel::SafeRun::Errors              ();
# use Cpanel::SafeRun::Object              ();
# use Cpanel::SysPkgs                      ();
# use Cpanel::Binaries::Yum                ();    # For locking. We should probably directly use it eventually.
# use Cpanel::Finally                      ();
# use Cpanel::Set                          ();

use IO::Handle;

use constant _ENOENT => 2;

our $VERSION       = '22.3';
our $YUM_BIN       = '/usr/bin/yum';
our $YUM_CONF      = '/etc/yum.conf';
our $FORCE_DRY_RUN = 0;                         # For testing


sub new {
    my $class = shift;
    my $self  = shift or die;

    $self = $class->SUPER::new($self);
    bless $self, $class;

    $self->{'yum_tolerant'}   = 1;
    $self->{'yum_errorlevel'} = 1;           # default value is 2
    $self->{'yum.conf'}       = $YUM_CONF;

    $self->{'exe'}     = $YUM_BIN;
    $self->{'VERSION'} = $VERSION;

    return $self;
}


sub uninstall_packages ( $self, %opts ) {

    return $self->_call_yum( %opts, 'command' => ['erase'] );
}

sub install_packages ( $self, %opts ) {

    my $exclude_rules = Cpanel::OS::system_exclude_rules();

    $opts{exclude} //= [];
    if ( $opts{'nasty_hack_to_exclude_kernel'} && $self->should_block_kernel_updates ) {
        foreach my $k (qw{kernel kmod-}) {
            push $opts{exclude}->@*, split( /\s+/, $exclude_rules->{$k} ) if $exclude_rules->{$k};
        }
    }

    return $self->_call_yum(%opts);
}

sub download_packages ( $self, %opts ) {

    return $self->_call_yum( %opts, 'download_only' => 1 );
}

sub do_warn ($msg) {
    return CORE::warn($msg);

}

sub add_repo_key {
    my ( $self, $key ) = @_;
    my $run = Cpanel::SafeRun::Object->new(
        program => Cpanel::Binaries::path('rpm'),
        args    => [ '--import', $key ],
    );

    do_warn("Could not import the public key") if $run->error_code();
    return !$run->error_code();
}


sub add_repo ( $self, %opts ) {

    my ( $remote_path, $real_path ) = @opts{qw{remote_path local_path}};


    if ( open my $rfh, '<', $real_path ) {
        require File::Copy;
        my $renamed_to = $real_path . substr( rand, 1 ) . '-' . ( localtime =~ tr< ><_>r );
        if ( File::Copy::copy( $rfh => $renamed_to ) ) {
            do_warn("“$real_path” is about to be rewritten. The old file has been copied to “$renamed_to”.\n");
        }
        else {
            die "The system failed to copy “$real_path” to “$renamed_to” ($!).\n";
        }
    }
    elsif ( $! != _ENOENT() ) {
        do_warn("open(< $real_path): $!");
    }

    my $response;
    if ( $remote_path =~ qr{^/} ) {

        my $success = 0;

        require File::Copy;
        $success = 1 if File::Copy::copy( $remote_path, $real_path );

        $response = { 'success' => $success };

        if ( !$success ) {
            $response->{status} = $!;
            if ( !-e $remote_path ) {
                $response->{reason} = qq[$remote_path missing];
            }
        }

    }
    else {
        require Cpanel::HTTP::Tiny::FastSSLVerify;
        my $http = Cpanel::HTTP::Tiny::FastSSLVerify->new();
        $response = $http->mirror( $remote_path, $real_path );
    }

    Cpanel::Repos::Utils::post_install();

    return $response;
}

sub reinstall_packages {
    my ( $self, %OPTS ) = @_;

    return $self->_call_yum( %OPTS, 'command' => ['reinstall'] );
}

sub clean ($self) {
    return $self->_call_yum( 'command' => [ 'clean', 'all' ] );
}


sub check_and_set_exclude_rules ( $self, %opts ) {

    return 1 unless $self->check_is_enabled;

    $self->parse_pkgmgr_conf() or return;
    $self->write_pkgmgr_conf();

    return 1;
}

sub checkdb {
    return 1;
}

sub checkconfig {
    my $self = shift or Carp::croak('checkconfig() method called without arguments.');
    ref $self        or Carp::croak("checkconfig() must be called as a method.");

    my $yum       = Cpanel::Binaries::Yum->new;
    my $result    = $yum->cmd( 'info', 'glibc' );
    my $glibcinfo = $result->{'output'} || '';
    if ( $glibcinfo !~ m{ (?: Installed | Available) \s+ Packages }xmsi || $glibcinfo =~ /No\s+Repositories\s+Available/ ) {
        return 0;
    }
    return 1;
}


sub verify_package_version_is_available {
    my ( $self, %OPTS ) = @_;

    die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'version' ] ) if !defined $OPTS{'version'};

    my $stdout = $self->_list_versions_for_package( $OPTS{'package'} );

    my $regexp = _get_regexp_to_match_yum_list(
        map { quotemeta } @OPTS{ 'package', 'version' },
    );

    foreach my $line ( split m{\n+}, $stdout ) {
        return 1 if $line =~ $regexp;
    }

    die "The package “$OPTS{'package'}” with version “$OPTS{'version'}” is not available via yum: $stdout";
}

sub _get_regexp_to_match_yum_list {
    my ( $pkg_re, $version_re ) = @_;

    return qr/
        ^
        [ \t]*
        $pkg_re         #e.g., MariaDB-server.i686
        (?:\.\S+)*
        [ \t]+
        $version_re     #e.g., 10.0.14-1.el6

    /x;
}

sub _list_versions_for_package {
    my ( $self, $pkg ) = @_;

    Cpanel::Validate::FilesystemNodeName::validate_or_die($pkg);

    my $result = Cpanel::SafeRun::Object->new_or_die(
        'program' => $self->{'exe'},
        'args'    => [ $self->_base_yum_args(), 'list', $pkg ],
    );

    return $result->stdout();
}

sub can_packages_be_installed {
    my ( $self, %OPTS ) = @_;

    if ( !defined $OPTS{'packages'} ) {
        die Cpanel::Exception::create( 'MissingParameter', [ 'name' => 'packages' ] );
    }

    my $ignore_conflict_packages_regexp = $OPTS{'ignore_conflict_packages_regexp'};

    my $yum_stderr = '';
    my $err;

    try {
        $self->_call_yum(
            %OPTS,
            'command'         => ['install'],
            'dry_run'         => 1,
            'stderr_callback' => sub {
                my ($data) = @_;
                $yum_stderr .= $data;
                return 1;
            }
        );
    }
    catch {
        $err = $_;
    };

    if ($err) {
        if (   UNIVERSAL::isa( $err, 'Cpanel::Exception::ProcessFailed' )
            && $ignore_conflict_packages_regexp
            && $self->_should_ignore_package_conflicts_in_yum_error_output( $yum_stderr, $ignore_conflict_packages_regexp ) ) {
            return 1;
        }

        $self->error( Cpanel::Exception::get_string($err) );
        return 0;
    }

    if ( ref( $OPTS{'check_yum_preinstall_stderr'} ) eq 'CODE' && $OPTS{'check_yum_preinstall_stderr'}->($yum_stderr) ) {
        $self->error("The following error occurred while attempting to install the requested packages with yum:\n\n$yum_stderr\nThis error must be resolved in order to complete this upgrade.");
        return 0;
    }

    return 1;
}

sub has_exclude_rule_for_package ( $self, $pkg ) {

    $self->parse_pkgmgr_conf;

    my $is_excluded = grep {    # for readability
        $_ eq $pkg                     #
          || $_ eq '^' . $pkg . '$'    #
          || $_ eq '^' . $pkg          #
          || $_ eq $pkg . '$'          #
    } split /\s+/, $self->{original_exclude_string};

    return $is_excluded ? 1 : 0;
}

sub drop_exclude_rule_for_package ( $self, $pkg ) {

    return unless $self->has_exclude_rule_for_package($pkg);

    $self->{exclude_string} =~ s/(?:^$pkg$|^$pkg\s+|\s+$pkg\s+|\s+$pkg$)//g;

    return $self->write_pkgmgr_conf;
}

sub add_exclude_rule_for_package ( $self, $pkg ) {

    return if $self->has_exclude_rule_for_package($pkg);

    $self->{exclude_string} .= " $pkg";

    return $self->write_pkgmgr_conf;
}



sub _parse_existing_excludes ( $self, $pkgs = '' ) {

    $pkgs ||= '';
    my @PKGS = split( /\s+/, $pkgs );

    @PKGS = grep( !m/^\s*$/, @PKGS );

    my @remove_excludes = $self->_determine_remove_from_excludes();

    $self->{'excludes'} or die "No excludes found in " . __PACKAGE__;
    my %excludes = $self->{'excludes'}->%*;

    foreach my $excl ( sort keys %excludes ) {

        @PKGS = grep( !m/$excl/, @PKGS );

        if ( $excl eq 'kernel' ) {
            @PKGS = grep( !m/^kmod$/, @PKGS );
        }

        push @PKGS, $excludes{$excl};
    }

    foreach my $remove (@remove_excludes) {
        @PKGS = grep( !m/$remove/, @PKGS );
    }

    return ( $self->{'exclude_string'} = join( ' ', sort @PKGS ) );
}


sub _determine_remove_from_excludes ($self) {

    $self->validate_excludes();


    my @remove_excludes = qw[ apache wget mysql mysql* ];

    if ( !$self->exclude_kernel ) {
        push @remove_excludes, qw( ^kernel ^kmod );
    }

    push @remove_excludes, 'perl' unless $self->exclude_perl;

    push @remove_excludes, 'ruby' unless $self->exclude_ruby;

    push @remove_excludes, 'bind-chroot' unless $self->exclude_bind_chroot;

    return @remove_excludes;
}


sub parse_pkgmgr_conf ($self) {    # Please do not use outside of this package
    ref $self or Carp::croak("parse_pkgmgr_conf() must be called as a method.");

    return 1 unless $self->check_is_enabled();

    my $msg = "checkyum version $self->{VERSION}";
    if ( my @excluded_packages = grep { $self->{'exclude_options'}->{$_} } sort keys %{ $self->{'exclude_options'} } ) {
        $msg .= "  (excludes: @excluded_packages)";
    }

    $self->out($msg);

    if ( !-e $self->{'yum.conf'} ) {
        require Fcntl;
        sysopen my $fh, $self->{'yum.conf'}, Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL() or die "Couldn't create $self->{'yum.conf'}: $!";
        close $fh;
    }

    my @YUM_CONF_CONTENTS;

    my $yum_conf_fh = IO::Handle->new();
    my $la          = Cpanel::SafeFile::safeopen( $yum_conf_fh, '<', $self->{'yum.conf'} );
    if ( !$la ) {
        $self->{'logger'}->fatal( "Could not read from " . $self->{'yum.conf'} ) if ( $self->{'logger'} );
        Cpanel::Debug::log_die( "Could not read from " . $self->{'yum.conf'} );
    }

    my @all_exclude_lines;
    my $saw_exclude = 0;
    while ( my $line = <$yum_conf_fh> ) {

        next if ( $line =~ m/^\s*tolerant=/i );
        next if ( $line =~ m/^\s*errorlevel=/i );

        if ( $saw_exclude && ( $line =~ m/^[^\s]+/ ) ) { $saw_exclude = 0; }    #We have now left the Exclude statement.
        if ( $line =~ m/^\s*exclude\s*=/i )            { $saw_exclude = 1; }    #We have encountered the Exclude statement.
        if ( $saw_exclude && ( ( $line =~ m/^\s*exclude\s*=\s*(.*)/i ) || ( $line =~ m/^\s*(.*)/i ) ) ) {
            push @all_exclude_lines, $1;
            next;
        }
        push @YUM_CONF_CONTENTS, $line;                                         #If nothing was triggered, then
    }

    my $excludes = join ' ', @all_exclude_lines;

    $self->{'original_exclude_string'} = $excludes;

    $self->_parse_existing_excludes($excludes);
    Cpanel::SafeFile::safeclose( $yum_conf_fh, $la );

    $self->{'yum_conf_file_contents'} = \@YUM_CONF_CONTENTS;

    return 1;
}


sub write_pkgmgr_conf ($self) {    # Please do not use outside of this package
    ref $self or Carp::croak("write_pkgmgr_conf() must be called as a method.");

    my @temp_file_contents;

    if ( grep { $_ =~ /[^\s]+/ } @{ $self->{'yum_conf_file_contents'} } ) {

        foreach my $line ( @{ $self->{'yum_conf_file_contents'} } ) {

            push @temp_file_contents, $line;

            if ( $line =~ m/^\[main\]/i ) {

                push @temp_file_contents, 'exclude=' . $self->{'exclude_string'} . "\n";
                push @temp_file_contents, 'tolerant=' . $self->{'yum_tolerant'} . "\n";
                push @temp_file_contents, 'errorlevel=' . $self->{'yum_errorlevel'} . "\n";
            }
        }

    }
    else {

        my $yum_string = "[main]\n";
        $yum_string .= 'exclude=' . $self->{'exclude_string'} . "\n";
        $yum_string .= 'tolerant=' . $self->{'yum_tolerant'} . "\n" . 'errorlevel=' . $self->{'yum_errorlevel'} . "\n";
        push @temp_file_contents, $yum_string;
    }

    if ( !Cpanel::FileUtils::Write::overwrite_no_exceptions( $self->{'yum.conf'}, join( '', @temp_file_contents ), 0644 ) ) {
        $self->{'logger'}->fatal( "Could not write to " . $self->{'yum.conf'} ) if ( $self->{'logger'} );
        Cpanel::Debug::log_die( "Could not write to " . $self->{'yum.conf'} );
    }

    return 1;
}

sub repolist {
    my ( $self, %OPTS ) = @_;
    return $self->_call_yum( %OPTS, 'command' => ['repolist'] );
}


sub _call_yum ( $self, %OPTS ) {

    my $packages         = $OPTS{'packages'}         || $OPTS{'pkglist'} || [];    # pkglist is for legacy calls
    my $exclude_packages = $OPTS{'exclude_packages'} || [];
    my $command          = $OPTS{'command'}          || ['install'];
    my $usecache         = $OPTS{'usecache'}      ? 1 : 0;
    my $download_only    = $OPTS{'download_only'} ? 1 : 0;
    my $download_dir     = $OPTS{'download_dir'};
    my $dry_run          = $OPTS{'dry_run'} ? 1 : 0;
    my $disable_plugins  = $OPTS{'disable_plugins'} || [];
    my $is_base_install  = defined( $ENV{'CPANEL_BASE_INSTALL'} );

    my $keepcache = $OPTS{'keepcache'} // ( $is_base_install ? 1 : undef );

    my @args = $self->_base_yum_args();

    push @args, '--cacheonly' if $usecache;

    if ( $dry_run || $FORCE_DRY_RUN ) {
        push @args, '--assumeno';
    }

    push @args, '--downloadonly' if $download_only;
    push @args, ( '--downloaddir' => $download_dir ) if $download_dir;

    if ( defined($keepcache) ) {
        push @args, '--setopt', sprintf( 'keepcache=%d', $keepcache ? 1 : 0 );
    }

    foreach my $package ( $exclude_packages->@* ) {
        push @args, '--exclude', $package;
    }

    foreach my $plugin ( $disable_plugins->@* ) {
        push @args, '--disableplugin', $plugin;
    }

    push @args, @{$command};
    foreach my $package ( @{$packages} ) {
        Cpanel::Validate::FilesystemNodeName::validate_or_die($package);
        push @args, $package;
    }

    my @repos = grep { $_ ne 'epel' } Cpanel::OS::package_repositories()->@*;
    foreach my $repo (@repos) {
        push @args, '--enablerepo=' . $repo;
    }

    if ( is_epel_installed() ) {
        push @args, '--enablerepo=epel';
    }

    my $finally;
    if ( exists $self->{'original_exclude_string'} ) {
        my @exclude_rules     = map { split /\s+/, Cpanel::OS::system_exclude_rules()->{$_} } qw(kernel kmod-);
        my @orig_excludes     = split /\s+/, $self->{'original_exclude_string'} // '';
        my @filtered_excludes = Cpanel::Set::difference( \@orig_excludes, \@exclude_rules );
        $finally = Cpanel::Finally->new( sub { $self->{'exclude_string'} = join( ' ', @filtered_excludes ); $self->write_pkgmgr_conf(); } );
    }

    return $self->_exec_yum( %OPTS, '_args' => \@args );
}

sub _exec_yum ( $self, %OPTS ) {

    my $stdout_callback    = $OPTS{'stdout_callback'};
    my $stderr_callback    = $OPTS{'stderr_callback'};
    my $handle_child_error = $OPTS{'handle_child_error'} || \&_die_child_error;

    local $ENV{'LANG'}   = 'C';
    local $ENV{'LC_ALL'} = 'C';

    my $start_time = Cpanel::TimeHiRes::time();
    my $stderr     = '';

    my $callback_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->out(@_); return 1; } );

    my $callback_err_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->warn(@_); return 1; } );

    $self->{'logger'}->info("Starting yum execution “@{$OPTS{'_args'}}”.") if $self->{'logger'};
    Cpanel::Debug::log_debug("Starting yum execution “@{$OPTS{'_args'}}”.");

    my $lock = Cpanel::Binaries::Yum->new->get_lock_for_cmd( $self->{'logger'}, $OPTS{'_args'} );

    my $result = Cpanel::SafeRun::Object->new(
        'program' => $self->{'exe'},
        'args'    => $OPTS{'_args'},
        'stdin'   => $OPTS{'stdin'},
        'stdout'  => Cpanel::CPAN::IO::Callback::Write->new(
            sub {
                my ($data) = @_;
                $data .= "\n" if substr( $data, -1 ) ne "\n";    # ensure a newline here so we don't make Cpanel::Parser::Line’s buffer keep concatenating lines without a newline and repeating them over and over and …

                if ( $data =~ m{\w+\s*:\s.*\d+/\d+}m ) {
                    $data =~ s/[\x00-\x0A]+//go;
                    $data .= "\n";                               # re-add the newline we just stripped out
                }

                if ($stdout_callback) {
                    $stdout_callback->($data);
                }
                else {
                    $callback_obj->process_data($data);
                }
                return;
            }
        ),
        'stderr' => Cpanel::CPAN::IO::Callback::Write->new(
            sub {
                my ($data) = @_;
                $data .= "\n" if substr( $data, -1 ) ne "\n";    # ensure a newline here so we don't make Cpanel::Parser::Line’s buffer keep concatenating lines without a newline and repeating them over and over and …

                $stderr .= $data;
                if ($stderr_callback) {
                    $stderr_callback->($data);
                }
                else {
                    $callback_err_obj->process_data($data);
                }
                return;
            }
        ),
        'timeout' => 7200,    # 2 hour timeout
    );

    $callback_obj->finish();
    $callback_err_obj->finish();
    my $end_time  = Cpanel::TimeHiRes::time();
    my $exec_time = sprintf( "%.3f", ( $end_time - $start_time ) );
    $self->{'logger'}->info("Completed yum execution “@{$OPTS{'_args'}}”: in $exec_time second(s).") if $self->{'logger'};
    Cpanel::Debug::log_debug("Completed yum execution “@{$OPTS{'_args'}}”: in $exec_time second(s).");

    if ( $result->CHILD_ERROR() && !grep( /^--assumeno$/, @{ $OPTS{'_args'} } ) ) {
        return $handle_child_error->( $result, $stderr, %OPTS );
    }

    return 1;
}

sub _base_yum_args ($self) {

    return ( '--assumeyes', '--color=never', '--config', $self->{'yum.conf'} );
}

sub _die_child_error {
    my ( $result, $stderr, %opts ) = @_;

    $result->die_if_error();

    return;    ## Just to satisfy cplint; we never actually get here.
}

sub _should_ignore_package_conflicts_in_yum_error_output ( $self, $yum_stderr, $ignore_conflict_packages_regexp ) {    ## no critic qw(Subroutines::ProhibitManyArgs)

    my @output = split( m{\n}, $yum_stderr );

    my ( $has_error_summary, $in_error_summary, $has_transaction_check_error, $in_transaction_check_error );
    foreach my $line (@output) {
        if ( $line =~ m{^---} ) {
            next;
        }
        elsif ( $line =~ m/^[ \t]*Error Summary/i ) {
            $has_error_summary = $in_error_summary = 1;
        }
        elsif ( $line =~ m/^[ \t]*Transaction Check Error/i ) {
            $has_transaction_check_error = $in_transaction_check_error = 1;
        }
        elsif ( $line =~ m{^\s*$} ) {
            $in_error_summary = $in_transaction_check_error = 0;
        }
        elsif ($in_transaction_check_error) {
            if ( $line =~ m{conflicts with.*?package $ignore_conflict_packages_regexp} ) {

                next;
            }
            else {
                return 0;
            }
        }
        elsif ($in_error_summary) {
            return 0;
        }
    }

    if ($has_transaction_check_error) {
        $self->out("All Package conflicts matched allowed.");
        return 1;
    }

    return 0;
}

sub is_epel_installed {
    return -e '/etc/yum.repos.d/epel.repo' ? 1 : 0;
}

sub is_epel_enabled {
    my $repo_file = '/etc/yum.repos.d/epel.repo';
    open( my $fh, '<', $repo_file ) or return 0;

    while ( my $line = <$fh> ) {
        next unless $line =~ m{^enabled\s*=};
        my ($enabled) = $line =~ m{enabled\s*=\s*(\d*)}a;
        return $enabled ? 1 : 0;
    }

    return 0;    # Couldn't find the enabled=1 setting!
}

sub ensure_plugins_turned_on ($self) {

    if ( !exists $self->{'yum_conf_file_contents'} ) {

        return unless $self->parse_pkgmgr_conf();
    }


    my $plugins;

    my @yum_conf;

    foreach my $line ( @{ $self->{'yum_conf_file_contents'} } ) {
        if ( $line =~ m/^plugins=(.*)\n$/ ) {
            $plugins = Cpanel::StringFunc::Trim::ws_trim($1);
            if ( $plugins == 0 ) {
                push( @yum_conf, "plugins=1\n" );
            }
            else {
                push( @yum_conf, $line );
            }
        }
        else {
            push( @yum_conf, $line );
        }
    }

    if ( !defined $plugins ) {
        $plugins  = 0;
        @yum_conf = ();
        foreach my $line ( @{ $self->{'yum_conf_file_contents'} } ) {
            if ( $line =~ m/^\[main\]/ ) {
                push( @yum_conf, $line );
                push( @yum_conf, "plugins=1\n" );
            }
            else {
                push( @yum_conf, $line );
            }
        }
    }

    if ( !$plugins ) {
        $self->{'yum_conf_file_contents'} = \@yum_conf;
        $self->write_pkgmgr_conf();
    }

    return 1;
}


sub search ( $self, %opts ) {

    return $self->_search( 'available', %opts );
}



sub search_installed ( $self, %opts ) {

    return $self->_search( 'installed', %opts );
}

sub _search ( $self, $state, %opts ) {

    my @args = ();
    push @args, '--disableexcludes=all' if $opts{force};
    push @args, '--showduplicates'      if $opts{all};     # By default, only the latest one is shown

    my $syspkgs = Cpanel::SysPkgs->new();
    my $proc    = Cpanel::SafeRun::Object->new(
        program => scalar Cpanel::Binaries::path('yum'),
        args    => [ @args, '-q', 'info', $state, $opts{pattern} ],
    );
    return if $proc->stderr() =~ m/^Error: No matching Packages to list/mi;
    $proc->die_if_error();

    my $re = qr/
        ^Name\s*:\s*(?<name>\S*)\s*
        ^Arch\s*:\s*(?<arch>\S*)\s*
        ^Version\s*:\s*(?<version>\S*)\s*
        ^Release\s*:\s*(?<release>\S*)\s*
    /imx;
    my $stdout = $proc->stdout();
    my @found;
    while ( $stdout =~ m/$re/g ) {
        push @found, { %+, package => "$+{name}-$+{version}-$+{release}.$+{arch}" };
    }
    return \@found;
}


sub list_available ( $self, %opts ) {
    my $pattern = $opts{'search_pattern'} // '';    # This should be safe from a shell injection.

    my @args;
    if ( $opts{'disable_epel'} && is_epel_enabled() ) {
        push @args, '--disablerepo=epel';
    }

    my @rpms = split /\n/, Cpanel::SafeRun::Errors::saferunallerrors( $YUM_BIN, '-d', '0', @args, 'list', 'available' );
    shift @rpms;                                    # Strip the header.
    my @packages;
    while ( my $rpm = shift @rpms ) {
        while ( length $rpms[0] && $rpms[0] =~ m/^ / ) {    # yum does strange column wrapping. we're fixing that here.
            $rpm .= shift @rpms;
        }
        my ( $package, $version, $repo ) = split( " ", $rpm );
        length $repo or next;

        next if $opts{'disable_ea4'} && $repo =~ m/^ea4-/i;

        my ( $name, $arch ) = $package =~ m{^(.+)\.([^.]+)$};

        next if length $pattern && index( $name, $pattern ) == -1;

        push @packages, {
            'name'          => $name,       #
            'version'       => $version,    #
            'repo'          => $repo,       #
            'arch'          => $arch,       #
            'name_and_arch' => $package
        };    #, 'description' => $description };
    }

    return \@packages;
}

1;

} # --- END Cpanel/SysPkgs/YUM.pm


{ # --- BEGIN Cpanel/Binaries/Dnf.pm
package Cpanel::Binaries::Dnf;



use cPstrict;

# use Cpanel::Binaries::Yum();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Binaries::Yum); }


sub bin_path ($self) {
    return '/usr/bin/dnf';
}

sub locks_to_wait_for {
    return (
        __PACKAGE__->SUPER::locks_to_wait_for(),
        qw{ /var/lib/dnf/rpmdb_lock.pid }
    );
}

1;

} # --- END Cpanel/Binaries/Dnf.pm


{ # --- BEGIN Cpanel/SysPkgs/DNF.pm
package Cpanel::SysPkgs::DNF;


use cPstrict;

# use Cpanel::SysPkgs::YUM();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::SysPkgs::YUM); }


# use Cpanel::Binaries::Dnf ();

sub _dnf ($self) {
    return $self->{_dnf} //= Cpanel::Binaries::Dnf->new();
}


sub enable_module_stream ( $self, $module, $version ) {

    die "enable_module_stream needs a module and a version" unless defined $module && defined $version;

    my $name = qq[${module}:${version}];

    $self->out("Enabling dnf module '$name'");
    my $run = $self->_dnf->cmd( qw(module enable -y), $name );

    if ( $run->{status} != 0 ) {
        die "Failed to enable module '$name': " . ( $run->{output} // '' );
    }

    return 1;
}


sub disable_module ( $self, $module ) {
    die "disable_module needs a module name" unless defined $module;

    $self->out("Disabling package module $module");

    my $run = $self->_dnf->cmd( qw(module disable -y --quiet), $module );

    if ( $run->{status} != 0 ) {
        die "Failed to disable module '$module': " . ( $run->{output} // '' );
    }

    return 1;
}

1;

} # --- END Cpanel/SysPkgs/DNF.pm


{ # --- BEGIN Cpanel/SysPkgs.pm
package Cpanel::SysPkgs;



use cPstrict;

# use Cpanel::OS ();

# use Cpanel::SysPkgs::APT ();    # PPI USE OK - See above line
# use Cpanel::SysPkgs::DNF ();    # PPI USE OK - See above line
# use Cpanel::SysPkgs::YUM ();    # PPI USE OK - See above line

$Cpanel::SysPkgs::VERSION = '1.1';

our $OUTPUT_OBJ_SINGLETON;      # For EasyApache

our %DEFAULT_EXCLUDE_OPTIONS = (
    'kernel'      => 0,
    'bind-chroot' => 1,
);

sub new ( $class, %args ) {
    my $self = bless {%args}, $class;

    $self->{'exclude_options'} ||= {%DEFAULT_EXCLUDE_OPTIONS};
    $self->{'output_obj'} = $OUTPUT_OBJ_SINGLETON;

    my $pkg_mgr = uc( Cpanel::OS::package_manager() );
    my $pkg_nam = "Cpanel::SysPkgs::$pkg_mgr";

    my $new = $pkg_nam->can("new") or die("Couldn't load $pkg_nam!");
    $self = $new->( $pkg_nam, $self ) or die("Could not convert SysPkgs Object to $pkg_nam");

    return $self;
}

1;

} # --- END Cpanel/SysPkgs.pm


{ # --- BEGIN Cpanel/EA4/Install.pm


package Cpanel::EA4::Install;

use cPstrict;

# use Cpanel::OS                        ();
# use Cpanel::Mkdir                     ();
# use Cpanel::SysPkgs                   ();
# use Cpanel::Pkgr                      ();
# use Cpanel::EA4::Constants            ();
# use Cpanel::HTTP::Tiny::FastSSLVerify ();

use File::Temp ();

use constant _ENOENT => 2;


sub install_ea4_repo (%options) {

    return if $options{skip_repo_setup};
    return if -e '/etc/apachedisable';

    $options{log_error} //= sub { warn shift };
    $options{log_info}  //= sub { say shift };

    my $syspkg = Cpanel::SysPkgs->new();
    $syspkg->ensure_plugins_turned_on();

    if ( Cpanel::OS::ea4_install_repo_from_package() ) {
        my $cl_pkg_url = Cpanel::OS::ea4_from_pkg_url();
        my $pkg        = Cpanel::OS::ea4_from_pkg_reponame();

        $options{log_info}->( "ea4: installing " . Cpanel::OS::display_name() . " public key and EA4 package from the “$pkg” package" );

        if ( Cpanel::Pkgr::get_package_version($pkg) ) {
            $options{log_info}->("ea4: “$pkg” is already installed");
        }
        else {
            my $url_name = $cl_pkg_url;
            $url_name =~ s{.*/([^/]+)$}{$1};
            my $http     = Cpanel::HTTP::Tiny::FastSSLVerify->new();
            my $response = $http->mirror( $cl_pkg_url, $url_name );
            if ( !$response->{success} ) {
                $options{log_error}->( "Could not download “$cl_pkg_url”: " . join( ' ', map { $response->{$_} // '' } qw{ status reason } ) );
                return 0;
            }

            eval { $syspkg->install_packages( packages => [$url_name] ) };
            if ($@) {
                $options{log_error}->("Could not install “$url_name”: $@");
                return 0;
            }

            unlink $url_name;    # try not to leave cruft
        }

        return 1;
    }
    else {
        if ( !$options{skip_gpg_key} ) {
            $options{log_info}->("ea4: installing public key");

            Cpanel::Mkdir::ensure_directory_existence_and_mode( $Cpanel::EA4::Constants::ea4_dir, 0755 );

            if ( my $err = _load_io_socket_ssl_or_return_error() ) {
                $options{log_error}->("Could not download the public key from “$Cpanel::EA4::Constants::public_key_url”: IO::Socket::SSL unavailable: $err");
                return 0;
            }
            else {
                my $http     = Cpanel::HTTP::Tiny::FastSSLVerify->new();
                my $response = $http->mirror( $Cpanel::EA4::Constants::public_key_url, $Cpanel::EA4::Constants::public_key_path );
                if ( !$response->{success} ) {
                    $options{log_error}->("Could not download the public key from “$Cpanel::EA4::Constants::public_key_url”: $response->{status} $response->{reason}: $response->{content}");
                    return 0;

                }
                my $imported = $syspkg->add_repo_key($Cpanel::EA4::Constants::public_key_path);
                return 0 if !$imported;
            }
        }

        $options{log_info}->("  - ea4: installing package repository config");

        if ( -f Cpanel::OS::ea4_from_custom_repo_path() && !-z _ ) {
            $options{log_info}->("ea4: package repo is already installed");
            return 1;
        }

        my $opts = $syspkg->get_repo_details('EA4');
        my $res  = $syspkg->add_repo(%$opts);
        if ( !$res->{success} ) {
            $options{log_error}->("Could not install EA4 package repo: $res->{status} $res->{reason}");
            return 0;
        }
    }

    return 1;
}

sub ea4_repo_already_installed() {

    if ( Cpanel::OS::ea4_install_repo_from_package() ) {

        my $pkg = Cpanel::OS::ea4_from_pkg_reponame();

        if ( !defined $pkg ) {
            die q[ea4_from_pkg_reponame is not defined for the current distro ] . Cpanel::OS::display_name();
        }

        return Cpanel::Pkgr::is_installed($pkg) ? 1 : 0;
    }

    my $local_repo_file = Cpanel::OS::ea4_from_custom_repo_path();

    if ( !defined $local_repo_file ) {
        die q[ea4_from_custom_repo_path is not defined for the current distro ] . Cpanel::OS::display_name();
    }

    return 1 if $local_repo_file && -f $local_repo_file;
    return 0;
}

sub _load_io_socket_ssl_or_return_error() {
    local $@;
    eval { require IO::Socket::SSL; };
    return $@;
}

1;

} # --- END Cpanel/EA4/Install.pm


{ # --- BEGIN Cpanel/Sysup.pm
package Cpanel::Sysup;



use cPstrict;

use Try::Tiny;

# use Cpanel::EA4::Install      ();
# use Cpanel::Debug             ();
# use Cpanel::ConfigFiles       ();
# use Cpanel::OS                ();
# use Cpanel::Pkgr              ();
# use Cpanel::SysPkgs           ();
# use Cpanel::LoadModule        ();
# use Cpanel::Update::Logger    ();
# use Cpanel::Version           ();
# use Cpanel::Services::Enabled ();
# use Cpanel::Server::Type      ();


sub new ( $class, $self = undef ) {
    $self //= {};
    bless $self, $class;

    return $self;
}

sub logger ($self) {
    ref $self eq __PACKAGE__ or die("You must call this as a method.");

    return $self->{'logger'} //= Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'info', 'timestamp' => 0 } );
}

sub run ( $self, %opts ) {
    ref $self eq __PACKAGE__ or _croak("run() must be called as a method.");

    if ( !$opts{'skipreposetup'} && !$ENV{CPANEL_BASE_INSTALL} ) {
        ensure_ea4_repo_is_installed(
            log_info        => sub { Cpanel::Debug::log_info(@_); },
            log_error       => sub { Cpanel::Debug::log_warn(@_); return $self->_notify(@_) },
            skip_repo_setup => -f $Cpanel::ConfigFiles::SKIP_REPO_SETUP_FLAG,
        );
    }

    my $pkg_list = $self->needed_packages( $opts{'supplemental_packages'} );
    push @$pkg_list, $self->optional_packages();
    push @$pkg_list, get_ea4_tooling_pkgs() unless $ENV{CPANEL_BASE_INSTALL};

    return $self->install_packages($pkg_list);
}

sub get_ea4_tooling_pkgs {

    if ( Cpanel::Server::Type::is_dnsonly() ) {
        return Cpanel::OS::ea4tooling_dnsonly()->@*;
    }

    return Cpanel::OS::ea4tooling()->@*;
}

sub ensure_ea4_repo_is_installed (%options) {

    if ( !Cpanel::EA4::Install::ea4_repo_already_installed() ) {
        $options{log_info}->("ea4: installing repo");
        return Cpanel::EA4::Install::install_ea4_repo(%options);
    }

    $options{log_info}->("ea4: repo already installed");

    return 1;
}


sub install_packages ( $self, $pkgs_wanted ) {
    ref $self eq __PACKAGE__ or _croak("install_packages() must be called as a method.");

    my @pkgs_needed = $self->get_outstanding_packages( $pkgs_wanted->@* )->@*;

    if (@pkgs_needed) {

        if ( grep { $_ eq 'nscd' } @pkgs_needed ) {
            Cpanel::Services::Enabled::touch_disable_file('nscd');
        }

        $self->_syspkgs->check_and_set_exclude_rules();    # previously known as checkyum
        $self->_syspkgs->install( 'pkglist' => \@pkgs_needed );

        my @uninstalled_pkgs = @{ $self->get_outstanding_packages( $pkgs_wanted->@* ) };
        if (@uninstalled_pkgs) {
            my $message = "Sysup: Needed system packages were not installed: " . join( ", ", @uninstalled_pkgs );
            $self->logger->error($message);
            $self->_notify($message);
            return;
        }

        return 1;
    }

    $self->logger->info("All Needed Packages are already installed.\n");

    return 1;
}

sub _syspkgs ($self) {
    return $self->{'_syspkg'} if $self->{'_syspkg'};
    return $self->{'_syspkg'} = Cpanel::SysPkgs->new( $self->{'logger'} ? ( 'logger' => $self->{'logger'} ) : () )
      || die "The system could not create the SysPkgs object.\n";
}


sub get_outstanding_packages ( $self, @pkgs_wanted ) {
    ref $self eq __PACKAGE__ or _croak("get_outstanding_packages() must be called as a method.");

    pop @pkgs_wanted if !defined $pkgs_wanted[-1];


    my $installed_pkgs = Cpanel::Pkgr::installed_packages();

    my @pkgs_tocheck;
    foreach my $pkgs (@pkgs_wanted) {
        $pkgs = [$pkgs] unless ref $pkgs eq 'ARRAY';

        push @pkgs_tocheck, $pkgs unless grep { $installed_pkgs->{$_} } @$pkgs;
    }

    my %missings;
    foreach my $pkgs (@pkgs_tocheck) {

        foreach my $pkg (@$pkgs) {

            if ( Cpanel::Pkgr::is_capability_available($pkg) ) {
                $missings{ $pkgs->[0] } = 0;
                last;
            }
            $missings{ $pkgs->[0] } = 1;
        }
    }

    return [ grep { $missings{$_} } sort keys %missings ];
}

sub _notify ( $self, $message ) {

    my $fullmessage = <<END;
Updating to the latest version of cPanel & WHM $Cpanel::Version::LTS did not succeed. Basic requirements for cPanel & WHM were unable to be installed. The specific failure was:

$message

For more information on this error, and guidance on resolving the error, please go to go.cpanel.net/sysupfailed
END

    if ( try { Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::sysup::Notify') } ) {

        require Cpanel::Notify;
        Cpanel::Notify::notification_class(
            'class'            => 'sysup::Notify',
            'application'      => 'sysup::Notify',
            'constructor_args' => [
                'origin'          => 'cPanel',
                'update_version'  => $Cpanel::Version::LTS,
                'failure_message' => $message
            ]
        );
    }
    else {
        require Cpanel::iContact;
        Cpanel::iContact::icontact(
            application => 'sysup',
            subject     => 'cPanel update failure during sysup',
            message     => $fullmessage,
        );
    }
    return;
}


sub needed_packages ( $self, $include_supplemental_packages = 1 ) {
    ref $self eq __PACKAGE__ or _croak("needed_packaged() must be called as a method.");

    $include_supplemental_packages //= 1;    #defaults to on

    my @packages = Cpanel::OS::packages_required()->@*;
    if ($include_supplemental_packages) {
        push @packages, Cpanel::OS::packages_supplemental()->@*;

        push @packages, Cpanel::OS::packages_supplemental_epel()->@* if $self->_syspkgs->is_epel_installed;
    }

    return \@packages;
}


sub optional_packages ($self) {
    ref $self or die("You must call this as a method.");

    my @entries = (

        [qw/nscd unscd/],
    );

    my @results;
    my $syspkgs = $self->_syspkgs();

    foreach my $entry (@entries) {
        my ( $main_pkg, @others ) = $entry->@*;

        push @results, $entry unless $syspkgs->has_exclude_rule_for_package($main_pkg);
    }

    return @results;
}

sub _croak {
    require Carp;
    goto \&Carp::croak;
}


1;

} # --- END Cpanel/Sysup.pm


{ # --- BEGIN Cpanel/StateFile.pm
package Cpanel::StateFile;


use cPstrict;

use Fcntl        ();
use Scalar::Util ();

my $the_logger;
my $the_locker;

my $pkg = __PACKAGE__;


{

    package DefaultLogger;

    use Carp ();
    our @CARP_NOT = qw/DefaultLogger/;

    sub new {
        my ($class) = @_;
        return bless {}, $class;
    }

    sub throw ( $self, @message ) {
        return Carp::croak(@message);
    }

    sub warn ( $self, @message ) {

        return Carp::carp(@message);
    }

    sub info ( $self, @message ) {
        return Carp::carp(@message);
    }

    sub notify {
        return;
    }
}

sub _throw {
    my $self = shift;
    _get_logger()->throw(@_);
    return;
}

sub _warn {
    my $self = shift;
    _get_logger()->warn(@_);
    return;
}

sub _notify {
    my $self = shift;
    _get_logger()->notify(@_);
    return;
}


sub _get_logger {
    unless ( defined $the_logger ) {
        $the_logger = DefaultLogger->new();
    }
    return $the_logger;
}

sub _get_locker {
    unless ( defined $the_locker ) {
        eval 'use Cpanel::StateFile::FileLocker;';    ## no critic (ProhibitStringyEval)
        $pkg->_throw(@_) if $@;
        $the_locker = Cpanel::StateFile::FileLocker->new( { logger => _get_logger() } );
    }
    return $the_locker;
}

my $are_policies_set = 0;

sub import {
    my ( $class, @args ) = @_;
    die 'Not an even number of arguments to the $pkg module' if @args % 2;
    die 'Policies already set elsewhere'                     if $are_policies_set;
    return 1 unless @args;    # Don't set the policies flag.

    while (@args) {
        my ( $policy, $object ) = splice( @args, 0, 2 );
        next unless defined $object;
        if ( '-logger' eq $policy ) {
            unless ( ref $object ) {
                eval "use $object;";    ## no critic (ProhibitStringyEval)
                die $@ if $@;

                $object = $object->new;
            }
            die 'Supplied logger object does not support the correct interface.'
              unless _valid_logger($object);
            $the_logger = $object;
        }
        elsif ( '-filelock' eq $policy ) {
            unless ( ref $object ) {
                eval "use $object;";    ## no critic (ProhibitStringyEval)
                die $@ if $@;

                $object = $object->new;
            }
            die 'Supplied filelock object does not support the correct interface.'
              unless _valid_file_locker($object);
            $the_locker = $object;
        }
        else {
            die "Unrecognized policy '$policy'";
        }
    }
    $are_policies_set = 1;
    return 1;
}

{

    package Cpanel::StateFile::Guard;

    sub new {
        my ( $class, $args_ref ) = @_;
        $pkg->throw('Args parameter must be a hash reference.') unless 'HASH' eq ref $args_ref;
        $pkg->throw('No StateFile.')                            unless exists $args_ref->{state};

        my $self = bless { state_file => $args_ref->{state} }, $class;

        $self->_lock();

        return $self;
    }

    sub DESTROY {
        my ($self) = @_;

        --$self->{'state_file'}{'guard_exists'} if $self->{'state_file'}{'guard_exists'};

        local $@;
        warn if !eval { $self->_unlock(); 1 };

        return;
    }

    sub _lock {
        my $self       = shift;
        my $state_file = $self->{state_file};

        my $filename = $state_file->{file_name};
        $self->{lock_file} = $state_file->{locker}->file_lock($filename);
        $state_file->throw("Unable to acquire file lock for '$filename'.") unless $self->{lock_file};
        return;
    }

    sub _in_child {
        my ($self) = @_;

        $self->{'lock_file'}   = undef;
        $self->{'file_handle'} = undef;

        return;
    }

    sub _unlock {
        my $self       = shift;
        my $state_file = $self->{state_file};
        return unless $self->{lock_file};

        if ( $state_file->{file_handle} ) {

            if ( !flock $state_file->{file_handle}, 8 | Fcntl::LOCK_NB() ) {

                eval {
                    local $SIG{'ALRM'} = sub { die "flock 8 timeout\n"; };
                    my $orig_alarm = alarm $state_file->{flock_timeout};
                    flock $state_file->{file_handle}, 8;
                    alarm $orig_alarm;
                };
            }
            close $state_file->{file_handle};
            $state_file->{file_handle} = undef;

            @{$state_file}{qw(file_size file_mtime)} = ( stat( $state_file->{file_name} ) )[ 7, 9 ];
        }
        $state_file->{locker}->file_unlock( $self->{lock_file} );
        $self->{lock_file} = undef;
        return;
    }

    sub call_unlocked {
        my ( $self, $code ) = @_;
        my $state_file = $self->{state_file};
        $state_file->throw('Cannot nest call_unlocked calls.')  unless defined $self->{lock_file};
        $state_file->throw('Missing coderef to call_unlocked.') unless 'CODE' eq ref $code;

        $self->_unlock();
        eval { $code->(); };
        my $ex = $@;

        $self->_lock();

        $state_file->_resynch($self);

        $pkg->_throw($ex) if $ex;

        return;
    }

    sub _open {
        my ( $self, $mode ) = @_;
        my $state_file = $self->{state_file};
        $state_file->throw('Cannot open state file inside a call_unlocked call.') unless defined $self->{lock_file};

        open my $fh, $mode, $state_file->{file_name}
          or $state_file->throw("Unable to open state file '$state_file->{file_name}': $!");

        if ( !flock $fh, 2 | Fcntl::LOCK_NB() ) {

            eval {
                local $SIG{'ALRM'} = sub { die "flock 2 timeout\n"; };
                my $orig_alarm = alarm $state_file->{flock_timeout};
                flock $fh, 2;
                alarm $orig_alarm;
                1;
            } or do {
                close($fh);
                if ( $@ eq "flock 2 timeout\n" ) {
                    $state_file->throw('Guard timed out trying to open state file.');
                }
                else {
                    $state_file->throw($@);
                }
            };
        }
        $state_file->{file_handle} = $fh;
        return;
    }

    sub update_file {
        my ($self) = @_;
        my $state_file = $self->{state_file};
        $state_file->throw('Cannot update_file inside a call_unlocked call.') unless defined $self->{lock_file};

        if ( !$state_file->{file_handle} ) {
            if ( -e $state_file->{file_name} ) {
                $self->_open('+<');
            }
            else {
                sysopen( my $fh, $state_file->{file_name}, Fcntl::O_CREAT() | Fcntl::O_EXCL() | Fcntl::O_RDWR() )
                  or $state_file->throw("Cannot create state file '$state_file->{file_name}': $!");
                $state_file->{file_handle} = $fh;
            }
        }
        seek( $state_file->{file_handle}, 0, 0 );
        truncate( $state_file->{file_handle}, 0 )
          or $state_file->throw("Unable to truncate the state file: $!");

        $state_file->{data_object}->save_to_cache( $state_file->{file_handle} );
        $state_file->{file_mtime} = ( stat( $state_file->{file_handle} ) )[9];

        seek( $state_file->{file_handle}, 0, 2 )
          or $state_file->throw("Unable to go to end of file: $!");
        $state_file->{file_size} = tell( $state_file->{file_handle} );
        return;
    }

}


sub new {
    my ( $class, $args_ref ) = @_;
    my $self = bless {}, $class;
    if ( exists $args_ref->{logger} && _valid_logger( $args_ref->{logger} ) ) {
        $self->{logger} = $args_ref->{logger};
    }
    else {
        $self->{logger} = $pkg->_get_logger();
        if ( exists $args_ref->{logger} ) {
            $self->throw('Supplied logger does not support required methods.');
        }
    }
    if ( exists $args_ref->{locker} && _valid_file_locker( $args_ref->{locker} ) ) {
        $self->{locker} = $args_ref->{locker};
    }
    else {
        $self->{locker} = $pkg->_get_locker();
        if ( exists $args_ref->{locker} ) {
            $self->throw('Supplied locker does not support required methods.');
        }
    }
    $args_ref->{state_file} ||= $args_ref->{cache_file} if exists $args_ref->{cache_file};
    $self->throw('No state filename supplied.') unless exists $args_ref->{state_file};
    $self->throw('No data object supplied.')    unless exists $args_ref->{data_obj};
    my $data_obj = $args_ref->{data_obj};
    $self->throw('Data object does not have required interface.')
      unless eval { $data_obj->can('load_from_cache') }
      and eval { $data_obj->can('save_to_cache') };

    my ( $dirname, $file ) = ( $args_ref->{state_file} =~ m{^(.*)/([^/]*)$}g );
    $dirname =~ s{[^/]+/\.\./}{/}g;    # resolve parent references
    $dirname =~ s{[^/]+/\.\.$}{};
    $dirname =~ s{/\./}{/}g;           # resolve self references
    $dirname =~ s{/\.$}{};
    if ( !-d $dirname ) {
        require File::Path;
        File::Path::mkpath( $dirname, 0, 0700 )
          or $self->throw("Unable to create Cache directory ('$dirname').");
    }
    else {
        chmod( 0700, $dirname ) if ( ( stat(_) )[2] & 0777 ) != 0700;
    }

    $self->{file_name} = "$dirname/$file";

    $self->{data_object}   = $data_obj;
    $self->{file_mtime}    = -1;
    $self->{file_size}     = -1;
    $self->{file_handle}   = undef;
    $self->{flock_timeout} = $args_ref->{timeout} || 60;
    Scalar::Util::weaken( $self->{data_object} );

    $self->synch();

    return $self;
}

sub _valid_logger {
    my ($logger) = @_;

    foreach my $method (qw/throw warn info notify/) {
        return unless eval { $logger->can($method) };
    }

    return 1;
}

sub _valid_file_locker {
    my ($locker) = @_;

    foreach my $method (qw/file_lock file_unlock/) {
        return unless eval { $locker->can($method) };
    }

    return 1;
}

sub synch {
    my ($self) = @_;

    if ( $self->{'guard_exists'} ) {
        require Carp;
        die Carp::longmess("A guard is already held in the object");
    }

    my $caller_needs_a_guard = defined wantarray;

    my $guard;

    if ( !-e $self->{file_name} ) {
        $guard = Cpanel::StateFile::Guard->new( { state => $self } );

        $guard->update_file();
    }
    elsif ( -z _ ) {

        $guard = Cpanel::StateFile::Guard->new( { state => $self } );

        if ( -z $self->{file_name} ) {

            $guard->update_file();
        }
        else {
            my ( $mtime, $size ) = ( stat(_) )[ 9, 7 ];
            $self->_resynch( $guard, $mtime, $size );

        }
    }
    else {
        if ($caller_needs_a_guard) {
            $guard = Cpanel::StateFile::Guard->new( { state => $self } );
        }
        my ( $mtime, $size ) = ( stat(_) )[ 9, 7 ];
        $self->_resynch( $guard, $mtime, $size );
    }

    return if !$caller_needs_a_guard;

    $self->{'guard_exists'} = 1;

    return $guard;
}

sub _resynch {
    my ( $self, $guard, $mtime, $size ) = @_;

    if ( !$mtime || !$size ) {
        ( $mtime, $size ) = ( stat( $self->{file_name} ) )[ 9, 7 ];
    }

    if ( $self->{file_mtime} < $mtime || $self->{file_size} != $size || $self->{file_mtime} > time() ) {

        $guard ||= Cpanel::StateFile::Guard->new( { state => $self } );
        $guard->_open('+<');
        $self->{data_object}->load_from_cache( $self->{file_handle} );
        ( $self->{file_mtime}, $self->{file_size} ) = ( stat( $self->{file_handle} ) )[ 9, 7 ];
    }

    return $guard;
}

sub get_logger { return $_[0]->{logger}; }

sub throw {
    my $self = shift;
    return $self->{logger}->throw(@_);
}

sub warn {
    my $self = shift;
    return $self->{logger}->warn(@_);
}

sub info {
    my $self = shift;
    return $self->{logger}->info(@_);
}

1;


} # --- END Cpanel/StateFile.pm


{ # --- BEGIN Cpanel/SafeFile/FileLocker.pm
package Cpanel::SafeFile::FileLocker;


use strict;
use warnings;

our $VERSION = '1.0';

# use Cpanel::SafeFile ();


sub new {
    my ( $class, $args_hr ) = @_;
    $args_hr = {} unless defined $args_hr;
    die "Argument to new must be a hash reference, not “$args_hr”.\n" unless 'HASH' eq ref $args_hr;
    die "Required “logger” argument is missing.\n"                    unless exists $args_hr->{logger};
    return bless { 'logger' => $args_hr->{'logger'} }, $class;
}


sub file_lock {
    my ( $self, $file ) = @_;

    my $lock_obj = Cpanel::SafeFile::safelock($file);

    $lock_obj or $self->{'logger'}->throw("Failed to lock $file as $> ($!)");
    return $lock_obj;
}


sub file_unlock {
    my ( $self, $lock_obj ) = @_;

    if ( !Cpanel::SafeFile::safeunlock($lock_obj) ) {
        my $error = $!;
        my $filename;
        foreach my $method (qw{file get_path}) {
            my $sub = $lock_obj->can($method) or next;
            $filename = $sub->($lock_obj);
            last;
        }
        $filename //= 'unknown';

        my $msg = "Failed to unlock " . $filename . " ($error)";

        $self->{'logger'}->throw($msg);
    }
    return 1;

}

1;

} # --- END Cpanel/SafeFile/FileLocker.pm


{ # --- BEGIN Cpanel/TaskQueue/Base.pm
package Cpanel::TaskQueue::Base;


use strict;
use warnings;


sub do_under_guard {
    my ( $self, $todo_cr ) = @_;

    local $self->{'_guard'} = $self->_disk_state()->synch() if !$self->{'_guard'};

    $todo_cr->($self);

    return $self->{'_guard'};
}

1;

} # --- END Cpanel/TaskQueue/Base.pm


{ # --- BEGIN Cpanel/TaskQueue/Task.pm
package Cpanel::TaskQueue::Task;


use cPstrict;

my $task_uuid = 'TaskQueue-Task';

my @fields                 = qw/_command _argstring _args _timestamp _uuid _child_timeout _started _pid _retries _userdata/;
my @must_be_defined_fields = grep { $_ ne '_pid' && $_ ne '_started' } @fields;

sub _throw {
    my $class = shift;
    die @_;
}


sub new {
    my ( $class, $args ) = @_;

    $class->_throw('Missing arguments')                  unless defined $args;
    $class->_throw('Args parameter must be a hash ref.') unless 'HASH' eq ref $args;
    $class->_throw('Missing command string.')            unless exists $args->{cmd} and $args->{cmd} =~ /\S/;
    $class->_throw('Invalid Namespace UUID.') if exists $args->{nsid} && !_is_valid_ns( $args->{nsid} );
    $class->_throw('Invalid id.') unless _is_pos_int( $args->{id} );

    my $uuid = _make_name_based_uuid(
        exists $args->{nsid} ? $args->{nsid} : $task_uuid,
        $args->{id}
    );

    my $timeout = -1;
    if ( exists $args->{timeout} ) {
        $timeout = $args->{timeout};
        $class->_throw('Invalid child timeout.') unless _is_pos_int($timeout);
    }
    my $retries = 1;
    if ( exists $args->{retries} ) {
        $retries = $args->{retries};
        $class->_throw('Invalid value for retries.') unless _is_pos_int($retries);
    }
    my $userdata = {};
    if ( exists $args->{userdata} ) {
        $class->_verify_userdata_arg( $args->{userdata} );
        $userdata = { %{ $args->{userdata} } };
    }

    my ( $command, $argstring ) = split( /\s+/, $args->{cmd}, 2 );
    $argstring = '' unless defined $argstring;

    my @args = ( $argstring =~ m/('(?: \\' | [^'] )*' | "(?: \\" | [^"] )*" | \S+ )/xg );
    foreach my $arg (@args) {
        if ( $arg =~ tr{'"\\}{} ) {

            $arg =~ s/^['"]//;
            $arg =~ s/["']$//;
            $arg =~ s/\\(['"])/$1/g;
        }
    }

    return bless {
        _command       => $command,
        _argstring     => $argstring,
        _args          => \@args,
        _timestamp     => time,
        _uuid          => $uuid,
        _child_timeout => $timeout,
        _started       => undef,
        _pid           => undef,
        _retries       => $retries,
        _userdata      => $userdata,
    }, $class;
}

sub reconstitute {
    my ( $class, $hash ) = @_;

    return unless defined $hash;
    return $hash if ref $hash eq $class;

    $class->_throw('Argument is not a hash reference.') unless ref {} eq ref $hash;
    if ( my $field = ( grep { !defined $hash->{$_} } @must_be_defined_fields )[0] ) {

        $class->_throw("Missing '$field' field in supplied hash") unless exists $hash->{$field};
        $class->_throw("Field '$field' has no value");
    }
    $class->_throw("Missing '_pid' field in supplied hash")     unless exists $hash->{_pid};
    $class->_throw("Missing '_started' field in supplied hash") unless exists $hash->{_started};
    $class->_throw(q{The '_args' field must be an array})       unless ref [] eq ref $hash->{_args};

    return bless {
        %$hash,

        '_args' => [ @{ $hash->{'_args'} } ]
    }, $class;
}

sub clone {
    my $self = shift;

    my $new = bless { %{$self} }, __PACKAGE__;

    foreach ( grep { ref $_ } values %{$new} ) {
        if ( ref [] eq ref $_ ) {
            $_ = [ @{$_} ];
        }
    }
    return $new;
}

sub mutate {
    my $self  = shift;
    my %parms = %{ shift() };

    my $new = $self->clone();

    if ( exists $parms{timeout} ) {
        $self->_throw('Invalid child timeout.') unless _is_pos_int( $parms{timeout} );
        $new->{_child_timeout} = $parms{timeout};
    }
    if ( exists $parms{retries} ) {
        $self->_throw('Invalid value for retries.') unless _is_pos_int( $parms{retries} );
        $new->{_retries} = $parms{retries};
    }
    if ( exists $parms{userdata} ) {
        $self->_verify_userdata_arg( $parms{userdata} );
        while ( my ( $k, $v ) = each %{ $parms{userdata} } ) {
            $new->{_userdata}->{$k} = $v;
        }
    }

    return $new;
}

sub command                 { return $_[0]->{_command}; }
sub full_command            { return "$_[0]->{_command} $_[0]->{_argstring}"; }
sub normalized_full_command { return ( $_[0]->{'_normalized_full_command'} ||= ( $_[0]->{_command} . ' ' . join( ' ', @{ $_[0]->{_args} } ) ) ) }
sub argstring               { return $_[0]->{_argstring}; }
sub args                    { return @{ $_[0]->{_args} }; }
sub timestamp               { return $_[0]->{_timestamp}; }
sub uuid                    { return $_[0]->{_uuid}; }
sub child_timeout           { return $_[0]->{_child_timeout}; }
sub started                 { return $_[0]->{_started}; }
sub pid                     { return $_[0]->{_pid}; }
sub retries_remaining       { return $_[0]->{_retries}; }

sub get_userdata {
    my $self = shift;
    my $key  = shift;
    $self->_throw('No userdata key specified') unless defined $key;
    return                                     unless exists $self->{_userdata}->{$key};
    return $self->{_userdata}->{$key};
}

sub get_arg {
    my ( $self, $index ) = @_;
    return $self->{_args}->[$index];
}

sub set_pid { $_[0]->{_pid}     = $_[1]; return; }
sub begin   { $_[0]->{_started} = time;  return; }

sub decrement_retries {
    my $self = shift;
    return unless $self->{_retries};
    $self->{_retries}--;
    return;
}


sub _make_name_based_uuid {
    my ( $nsid, $name ) = @_;

    return sprintf( 'TQ:%s:%s', $nsid, $name );
}

sub _is_pos_int {
    my $val = shift;
    return unless defined $val;
    return unless $val =~ /^\d+$/;
    return $val > 0;
}

sub _is_valid_ns {
    my $val = shift;
    return defined $val && length $val && $val !~ /:/;
}

sub is_valid_taskid {
    my $val = shift;
    return defined $val && $val =~ /^TQ:[^:]+:\d+$/;
}

sub _verify_userdata_arg {
    my $class = shift;
    my $arg   = shift;
    $class->_throw('Expected a hash reference for userdata value.') unless 'HASH' eq ref $arg;
    my @bad_keys;
    while ( my ( $k, $v ) = each %{$arg} ) {
        push @bad_keys, $k if ref $v;
    }
    if (@bad_keys) {
        @bad_keys = sort @bad_keys;
        $class->_throw("Reference values not allowed as userdata. Keys containing references: @bad_keys");
    }
    return;
}

sub TO_JSON {
    return { %{ $_[0] } };
}

1;


} # --- END Cpanel/TaskQueue/Task.pm


{ # --- BEGIN Cpanel/TaskQueue/Processor.pm
package Cpanel::TaskQueue::Processor;


use strict;
use warnings;

use constant {
    is_valid_args => 1,
    overrides     => undef,
    get_timeout   => undef,
};

{

    sub new {
        return bless {}, $_[0];
    }

    sub is_dupe {
        return ( $_[1]->{'_normalized_full_command'} || $_[1]->normalized_full_command() ) eq ( $_[2]->{'_normalized_full_command'} || $_[2]->normalized_full_command() ) ? 1 : 0;
    }

    sub process_task {
        my ( $self, $task, $logger ) = @_;

        if ($logger) {
            $logger->throw("No processing has been specified for this task.\n");
        }
        else {
            die "No processing has been specified for this task.\n";
        }
        return;
    }

    sub deferral_tags {
        return;
    }

    sub is_task_deferred {
        my ( $self, $task, $defer_hash ) = @_;
        return unless $defer_hash && keys %{$defer_hash};

        foreach my $tag ( $self->deferral_tags($task) ) {
            return 1 if exists $defer_hash->{$tag};
        }

        return;
    }

    sub checked_system {
        my ( $self, $args ) = @_;
        die "Argument must be a hashref."         unless ref $args eq 'HASH';
        die "Missing required 'logger' argument." unless $args->{'logger'};
        $args->{'logger'}->throw("Missing required 'cmd' argument.")
          unless defined $args->{'cmd'} && length $args->{'cmd'};
        $args->{'logger'}->throw("Missing required 'name' argument.")
          unless defined $args->{'name'} && length $args->{'name'};
        $args->{'args'} ||= [];

        my $rc = system $args->{'cmd'}, @{ $args->{'args'} };
        return 0 unless $rc;

        my $message;
        if ( $rc == -1 ) {
            $message = "Failed to run $args->{'name'}";
        }
        elsif ( $rc & 127 ) {
            $message = "$args->{'name'} dies with signal: " . ( $rc & 127 );
        }
        else {
            $message = "$args->{'name'} exited with value " . ( $rc >> 8 );
        }
        $args->{'logger'}->warn($message);

        return $rc;
    }
}

{

    package Cpanel::TaskQueue::Processor::CodeRef;

# use Cpanel::TaskQueue::Processor();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::TaskQueue::Processor); }

    {

        sub new {
            my ( $class, $args_ref ) = @_;
            die "Args must be a hash ref.\n" unless 'HASH' eq ref $args_ref;

            unless ( exists $args_ref->{code} and 'CODE' eq ref $args_ref->{code} ) {
                die "Missing required code parameter.\n";
            }
            return bless { proc => $args_ref->{code} }, $class;
        }

        sub process_task {
            my ( $self, $task, $logger ) = @_;

            eval {
                $self->{proc}->( $task->args() );
                1;
            } or do {
                $logger->throw($@);
            };

            return 0;
        }
    }
}

1;


} # --- END Cpanel/TaskQueue/Processor.pm


{ # --- BEGIN Cpanel/TaskQueue/Serializer.pm
package Cpanel::TaskQueue::Serializer;


use cPstrict;

# use Cpanel::JSON ();

use constant SERIALIZER_FILE_EXTENSION => 'json';

sub load ( $class, $fh ) {
    my $ref = Cpanel::JSON::LoadFile($fh);
    return undef if !$ref || !ref $ref;
    return @{$ref};
}

sub save ( $class, $fh, @text ) {
    return Cpanel::JSON::DumpFile( $fh, \@text );
}

sub filename ( $class, $stub ) {
    return $stub . '.' . SERIALIZER_FILE_EXTENSION;
}

sub decode_param ($encoded_string) {
    require Cpanel::Encoder::URI;
    require Cpanel::AdminBin::Serializer;
    my $json = Cpanel::Encoder::URI::uri_decode_str($encoded_string);
    return Cpanel::AdminBin::Serializer::Load($json);
}

1;

} # --- END Cpanel/TaskQueue/Serializer.pm


{ # --- BEGIN Cpanel/Wait/Constants.pm
package Cpanel::Wait::Constants;


use strict;

our $WNOHANG   = 1;
our $WUNTRACED = 2;

1;

} # --- END Cpanel/Wait/Constants.pm


{ # --- BEGIN Cpanel/TaskQueue.pm
package Cpanel::TaskQueue;




use cPstrict;

# use Cpanel::TaskQueue::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::TaskQueue::Base); }

# use Cpanel::TaskQueue::Task       ();
# use Cpanel::TaskQueue::Processor  ();    # PPI USE OK -- This module needs to be import()ed
# use Cpanel::TaskQueue::Serializer ();
# use Cpanel::StateFile             ();
# use Cpanel::Wait::Constants       ();

my $WNOHANG = $Cpanel::Wait::Constants::WNOHANG;


my $are_policies_set = 0;

sub import {
    my ( $class, @args ) = @_;

    die 'Not an even number of arguments to the ' . __PACKAGE__ . " module\n" if @args % 2;
    die "Policies already set elsewhere\n"                                    if $are_policies_set;
    return 1 unless @args;    # Don't set the policies flag.

    while (@args) {
        my ( $policy, $module ) = splice( @args, 0, 2 );
        my @methods = ();
        if ( '-logger' eq $policy ) {
            Cpanel::StateFile->import( '-logger' => $module );
        }
        else {
            die "Unrecognized policy '$policy'\n";
        }
    }
    $are_policies_set = 1;
    return 1;
}

sub _disk_state {
    my ($self) = @_;

    return $self->{'disk_state'};
}

sub _first ( $pred, @list ) {

    foreach (@list) {
        return $_ if $pred->($_);
    }

    return;
}

my $taskqueue_uuid = 'TaskQueue';

my %valid_processors;
END { undef %valid_processors }    # case CPANEL-10871 to avoid a SEGV during global destruction

{
    my $FILETYPE      = 'TaskQueue';    # Identifier at the beginning of the state file
    my $CACHE_VERSION = 3;              # Cache file version number.

    sub get_name                  { return $_[0]->{queue_name}; }
    sub get_default_timeout       { return $_[0]->{default_task_timeout}; }
    sub get_max_timeout           { return $_[0]->{max_task_timeout}; }
    sub get_max_running           { return $_[0]->{max_in_process}; }
    sub get_default_child_timeout { return $_[0]->{default_child_timeout}; }

    sub pause_processing {
        my ($self) = @_;
        my $guard = $self->{disk_state}->synch();
        $self->{paused} = 1;
        $guard->update_file();
        return;
    }

    sub resume_processing {
        my ($self) = @_;
        my $guard = $self->{disk_state}->synch();
        $self->{paused} = 0;
        $guard->update_file();
        return;
    }
    sub _is_paused { return $_[0]->{paused} || 0; }

    sub is_paused {
        my ($self) = @_;
        $self->{disk_state}->synch();
        return $self->_is_paused();
    }


    sub register_task_processor {
        my ( $class, $command, $processor ) = @_;

        unless ( defined $command and length $command ) {
            Cpanel::StateFile->_throw("Missing command in register_task_processor.\n");
        }
        unless ( defined $processor ) {
            Cpanel::StateFile->_throw("Missing task processor in register_task_processor.\n");
        }
        if ( exists $valid_processors{$command} ) {
            Cpanel::StateFile->_throw("Command '$command' already has a TaskQueue::Processor registered.\n");
        }
        if ( 'CODE' eq ref $processor ) {
            $valid_processors{$command} = Cpanel::TaskQueue::Processor::CodeRef->new( { code => $processor } );    # PPI USE OK -- Loaded by Cpanel::TaskQueue::Loader
            return 1;
        }
        elsif ( eval { $processor->isa('Cpanel::TaskQueue::Processor') } ) {
            $valid_processors{$command} = $processor;
            return 1;
        }

        Cpanel::StateFile->_throw("Unrecognized task processor object.\n");
        return;
    }

    sub unregister_task_processor {
        my ( $class, $command ) = @_;

        unless ( defined $command and length $command ) {
            Cpanel::StateFile->_throw("Missing command in unregister_task_processor.\n");
        }
        unless ( exists $valid_processors{$command} ) {
            Cpanel::StateFile->_throw("Command '$command' not registered, ignoring.\n");
            return;
        }

        delete $valid_processors{$command};
        return 1;
    }

    sub new {
        my ( $class, $args_ref ) = @_;
        Cpanel::StateFile->_throw("Args parameter must be a hash reference\n") unless 'HASH' eq ref $args_ref;

        $args_ref->{state_dir} ||= $args_ref->{cache_dir} if exists $args_ref->{cache_dir};
        Cpanel::StateFile->_throw("No state directory supplied.\n") unless exists $args_ref->{state_dir};
        Cpanel::StateFile->_throw("No queue name supplied.\n")      unless exists $args_ref->{name};

        my $self = bless {
            queue_name            => $args_ref->{name},
            default_task_timeout  => 60,
            max_task_timeout      => 300,
            max_in_process        => 2,
            default_child_timeout => 3600,
            disk_state_file       => Cpanel::TaskQueue::Serializer->filename("$args_ref->{state_dir}/$args_ref->{name}_queue"),
            next_id               => 1,
            queue_waiting         => [],
            processing_list       => [],
            deferral_queue        => [],
            disk_state            => undef,
            defer_obj             => undef,
            paused                => 0,
            serializer            => 'Cpanel::TaskQueue::Serializer',
        }, $class;

        my $state_args = {
            state_file => $self->{disk_state_file}, data_obj => $self,
            exists $args_ref->{state_timeout} ? ( timeout => $args_ref->{state_timeout} ) : (),
            exists $args_ref->{logger}        ? ( logger  => $args_ref->{logger} )        : (),
        };
        eval {
            $self->{disk_state} = Cpanel::StateFile->new($state_args);
            1;
        } or do {
            my $ex = $@;

            if ( $ex !~ /Not a recognized|Invalid version/ && !eval { $ex->isa('Cpanel::Exception::JSONParseError') } ) {
                Cpanel::StateFile->_throw($ex);
            }
            Cpanel::StateFile->_warn($ex);
            Cpanel::StateFile->_warn("Moving bad state file and retry.\n");
            Cpanel::StateFile->_notify(
                'Unable to load TaskQueue metadata',
                "Loading of [$self->{disk_state_file}] failed: $ex\n" . "Moving bad file to [$self->{disk_state_file}.broken] and retrying.\n"
            );
            unlink "$self->{disk_state_file}.broken";
            rename $self->{disk_state_file}, "$self->{disk_state_file}.broken";

            $self->{disk_state} = Cpanel::StateFile->new($state_args);
        };

        if ( grep { exists $args_ref->{$_} } qw/default_timeout max_timeout max_running default_child_timeout/ ) {
            my $altered;

            my $guard = $self->do_under_guard(
                sub {
                    for my $settings (
                        [qw(default_task_timeout  default_timeout)],
                        [qw(max_task_timeout      max_timeout)],
                        [qw(max_in_process        max_running)],
                        [qw(default_child_timeout default_child_timeout)],
                        [qw{_bump_size _bump_size}],
                    ) {
                        my ( $internal_name, $arg_name ) = @$settings;
                        if ( exists $args_ref->{$arg_name} && $self->{$internal_name} ne $args_ref->{$arg_name} ) {
                            $self->{$internal_name} = $args_ref->{$arg_name};
                            ++$altered;
                        }
                    }
                }
            );

            $guard->update_file() if $altered;
        }

        return $self;
    }

    sub throw {
        my $self = shift;
        return $self->{disk_state} ? $self->{disk_state}->throw(@_) : Cpanel::StateFile->_throw(@_);
    }

    sub warn {
        my $self = shift;
        return $self->{disk_state} ? $self->{disk_state}->warn(@_) : warn @_;
    }

    sub info {
        my $self = shift;
        return $self->{disk_state} ? $self->{disk_state}->info(@_) : undef;
    }

    sub _serializer {
        my ($self) = @_;
        return $self->{serializer};
    }

    sub _state_file {
        my ($self) = @_;
        return $self->{disk_state_file};
    }

    sub load_from_cache {
        my ( $self, $fh ) = @_;

        local $/;
        my ( $magic, $version, $meta ) = $self->_serializer()->load($fh);

        $self->throw('Not a recognized TaskQueue state file.')   unless defined $magic   and $magic eq $FILETYPE;
        $self->throw('Invalid version of TaskQueue state file.') unless defined $version and $version eq $CACHE_VERSION;

        $self->{next_id} = $meta->{nextid} if $meta->{nextid} > $self->{next_id};

        $self->{default_task_timeout}  = $meta->{def_task_to}  if $meta->{def_task_to} > 0;
        $self->{max_task_timeout}      = $meta->{max_task_to}  if $meta->{max_task_to} > 0;
        $self->{max_in_process}        = $meta->{max_running}  if $meta->{max_running} > 0;
        $self->{default_child_timeout} = $meta->{def_child_to} if $meta->{def_child_to} > 0;
        $self->{_bump_size}            = $meta->{_bump_size} // '';
        $self->{paused}                = ( exists $meta->{paused} && $meta->{paused} ) ? 1                  : 0;
        $self->{defer_obj}             = exists $meta->{defer_obj}                     ? $meta->{defer_obj} : undef;

        $self->{queue_waiting}   = _clean_task_list( $meta->{waiting_queue} );
        $self->{processing_list} = _clean_task_list( $meta->{processing_queue} );
        $self->{deferral_queue}  = _clean_task_list( $meta->{deferral_queue} );

        return 1;
    }

    sub _clean_task_list {
        my ($task_list) = @_;
        return [] unless defined $task_list;
        return [
            grep {
                defined $_
                  and eval { $_->isa('Cpanel::TaskQueue::Task') }
            } map {
                eval { Cpanel::TaskQueue::Task->reconstitute($_) }
            } @{$task_list}
        ];
    }

    sub save_to_cache {
        my ( $self, $fh ) = @_;

        my $meta = {
            nextid           => $self->{next_id},
            def_task_to      => $self->{default_task_timeout},
            max_task_to      => $self->{max_task_timeout},
            max_running      => $self->{max_in_process},
            def_child_to     => $self->{default_child_timeout},
            waiting_queue    => $self->{queue_waiting},
            processing_queue => $self->{processing_list},
            deferral_queue   => $self->{deferral_queue},
            paused           => ( $self->{paused} ? 1 : 0 ),
            defer_obj        => $self->{defer_obj},
            _bump_size       => $self->{_bump_size} // '',
        };

        $meta->{_bump_size} .= "x";
        $meta->{_bump_size} = 'x' if length $meta->{_bump_size} > 1_024;

        return $self->_serializer()->save( $fh, $FILETYPE, $CACHE_VERSION, $meta );
    }

    sub queue_tasks {
        my ( $self, @commands ) = @_;

        foreach my $command (@commands) {
            $self->throw('Cannot queue an empty command.') unless defined $command;
            if ( !eval { $command->isa('Cpanel::TaskQueue::Task') } ) {

                $self->throw('Cannot queue an empty command.') unless $command =~ /\S/;
            }
        }

        my ( @uuids, @invalid_tasks );

        my $guard = $self->do_under_guard(
            sub {
                foreach my $command (@commands) {
                    my $task;

                    if ( eval { $command->isa('Cpanel::TaskQueue::Task') } ) {
                        if ( 0 == $command->retries_remaining() ) {
                            $self->info('Task with 0 retries not queued.');
                            next;
                        }
                        $task = $command->mutate( { timeout => $self->{default_child_timeout} } );
                    }
                    else {
                        $task = Cpanel::TaskQueue::Task->new(
                            {
                                cmd     => $command,
                                nsid    => $taskqueue_uuid,
                                id      => $self->{next_id}++,
                                timeout => $self->{default_child_timeout},
                            }
                        );
                    }

                    my $proc = _get_task_processor($task);
                    if ( !$proc || !$proc->is_valid_args($task) ) {
                        push @invalid_tasks, $task;
                        next;
                    }

                    if ( $self->_add_task_to_waiting_queue($task) ) {
                        push @uuids, $task->uuid();
                    }
                    else {
                        push @uuids, undef;    # failed task
                    }
                }
            }
        );

        $guard->update_file();

        foreach my $task (@invalid_tasks) {
            $self->_get_task_processor_for_task_or_throw($task);
        }

        return @uuids;
    }

    sub queue_task {
        my ( $self, $command ) = @_;

        my @uuids = $self->queue_tasks($command);

        return @uuids ? $uuids[0] : ();
    }

    sub unqueue_task {
        my ( $self, $uuid ) = @_;

        unless ( _is_valid_uuid($uuid) ) {
            $self->throw('No Task uuid argument passed to unqueue_cmd.');
        }

        my $guard     = $self->{disk_state}->synch();
        my $old_count = @{ $self->{queue_waiting} };

        $self->{queue_waiting} = [ grep { $_->uuid() ne $uuid } @{ $self->{queue_waiting} } ];

        $guard->update_file();
        return $old_count > @{ $self->{queue_waiting} };
    }

    sub _is_task_in_list {
        my ( $self, $uuid, $list, $subname ) = @_;

        unless ( _is_valid_uuid($uuid) ) {
            $self->throw("No Task uuid argument passed to $subname.");
        }

        $self->{disk_state}->synch();
        return defined _first( sub { $_->uuid() eq $uuid }, @{ $self->{$list} } );
    }

    sub is_task_queued     { return $_[0]->_is_task_in_list( $_[1], 'queue_waiting',   'is_task_queued' ); }
    sub is_task_processing { return $_[0]->_is_task_in_list( $_[1], 'processing_list', 'is_task_processing' ); }
    sub is_task_deferred   { return $_[0]->_is_task_in_list( $_[1], 'deferral_queue',  'is_task_deferred' ); }

    sub _list_of_all_tasks {
        my ($self) = @_;
        return @{ $self->{queue_waiting} }, @{ $self->{deferral_queue} }, @{ $self->{processing_list} };
    }

    sub find_task {
        my ( $self, $uuid ) = @_;

        $self->{disk_state}->synch();
        my $task = _first( sub { $_->uuid() eq $uuid }, $self->_list_of_all_tasks() );

        return unless defined $task;
        return $task->clone();
    }

    sub find_command {
        my ( $self, $command ) = @_;

        $self->{disk_state}->synch();
        my $task = _first( sub { $_->command() eq $command }, $self->_list_of_all_tasks() );

        return unless defined $task;
        return $task->clone();
    }

    sub find_commands {
        my ( $self, $command ) = @_;

        $self->{disk_state}->synch();
        my @tasks = grep { $_->command() eq $command } $self->_list_of_all_tasks();

        return unless @tasks;
        return map { $_->clone() } @tasks;
    }

    sub _how_many {
        my ( $self, $listname ) = @_;

        $self->{disk_state}->synch();
        return scalar @{ $self->{$listname} };
    }

    sub how_many_queued     { return $_[0]->_how_many('queue_waiting'); }
    sub how_many_deferred   { return $_[0]->_how_many('deferral_queue'); }
    sub how_many_in_process { return $_[0]->_how_many('processing_list'); }

    sub has_work_to_do {
        my ($self) = @_;

        $self->{disk_state}->synch();
        $self->_clean_completed_tasks();

        return if $self->_is_paused;

        return scalar( @{ $self->{processing_list} } ) < $self->{max_in_process} && 0 != @{ $self->{queue_waiting} };
    }

    sub peek_next_task {
        my ($self) = @_;

        $self->{disk_state}->synch();
        return unless @{ $self->{queue_waiting} };

        return $self->{queue_waiting}->[0]->clone();
    }

    sub process_next_task {
        my ($self) = @_;

        my $guard = $self->{disk_state}->synch();

        $self->_handle_already_running_tasks($guard);

        if ( _first( sub { !defined $_ }, @{ $self->{queue_waiting} } ) ) {

            $self->warn('Undefined tasks found in the queue, removing...');
            $self->{queue_waiting} = [ grep { defined $_ } @{ $self->{queue_waiting} } ];

            $guard->update_file();
        }

        return 1 if $self->_is_paused;

        my ( $task, $processor );
        while ( !$task ) {

            return 1 unless @{ $self->{queue_waiting} };
            $task = shift @{ $self->{queue_waiting} };

            $processor = _get_task_processor($task);
            unless ($processor) {

                $self->warn( q{No processor found for '} . $task->full_command() . q{'.} );
                $guard->update_file();
                return 1;
            }

            if ( $processor->is_task_deferred( $task, $self->{defer_obj} ) ) {
                unshift @{ $self->{deferral_queue} }, $task;
                $task = undef;
            }
        }

        $task->begin();
        push @{ $self->{processing_list} }, $task;
        $self->_add_task_to_deferral_object( $task, $processor );

        my $pid;
        my $ex;

        if ( $processor->isa('Cpanel::TaskQueue::ChildProcessor') ) {

            eval { $pid = $processor->process_task( $task->clone(), $self->{disk_state}->get_logger(), $guard ) } or do {
                $ex = $@;
            };
        }
        else {
            $guard->update_file();

            $guard->call_unlocked(
                sub {
                    my $orig_alarm;
                    eval {
                        local $SIG{'ALRM'} = sub { die "time out reached\n"; };
                        $orig_alarm = alarm( $self->_timeout($processor) );
                        $pid        = $processor->process_task( $task->clone(), $self->{disk_state}->get_logger() );
                        alarm $orig_alarm;
                        1;
                    } or do {
                        $ex = $@;    # save exception for later
                        alarm $orig_alarm;
                    };
                }
            );
        }

        if ($pid) {
            $task->set_pid($pid);
        }
        else {
            my $uuid = $task->uuid();

            $self->{processing_list} = [ grep { $_->uuid() ne $uuid } @{ $self->{processing_list} } ];
            $self->_remove_task_from_deferral_object($task);
        }

        if ($ex) {
            if ( $ex eq "time out reached\n" ) {

                $self->warn( q{Task '} . $task->full_command() . q{' timed out during processing.} );
            }
            else {
                $self->throw($ex);
            }
        }

        $guard->update_file();
        if ( defined($pid) ) {
            return $pid == 0;
        }
        else {
            return;
        }
    }

    sub finish_all_processing {
        my ($self) = @_;

        my $guard = $self->{disk_state}->synch();
        while ( @{ $self->{processing_list} } ) {

            my $pid;

            $guard->call_unlocked( sub { $pid = waitpid( -1, 0 ) } );

            next unless $pid;
            $self->{processing_list} = [
                grep { 0 == waitpid( $_->pid(), $WNOHANG ) }
                grep { $_->pid() && $_->pid() != $pid } @{ $self->{processing_list} }
            ];
            $self->_process_deferrals();
            $guard->update_file();
        }
        return;
    }

    sub snapshot_task_lists {
        my ($self) = @_;

        $self->{disk_state}->synch();

        return {
            waiting    => [ map { $_->clone() } @{ $self->{queue_waiting} } ],
            processing => [ map { $_->clone() } @{ $self->{processing_list} } ],
            deferred   => [ map { $_->clone() } @{ $self->{deferral_queue} } ],
        };
    }

    sub delete_all_unprocessed_tasks {
        my ($self) = @_;
        my $guard = $self->{disk_state}->synch();

        my $count = @{ $self->{deferral_queue} };
        $self->{deferral_queue} = [];
        $count += @{ $self->{queue_waiting} };
        $self->{queue_waiting} = [];
        $guard->update_file();

        return $count;
    }


    sub _get_task_processor {
        my ($task) = @_;
        return $valid_processors{ $task->command() };
    }

    sub _is_duplicate_command {
        my ( $self, $task ) = @_;
        my $proc = _get_task_processor($task);

        return defined _first( sub { $proc->is_dupe( $task, $_ ) }, reverse @{ $self->{queue_waiting} } );
    }

    sub _process_overrides {
        my ( $self, $task ) = @_;
        my $proc = _get_task_processor($task);

        $self->{queue_waiting} = [ grep { !$proc->overrides( $task, $_ ) } @{ $self->{queue_waiting} } ];

        return;
    }

    sub _get_task_processor_for_task_or_throw {
        my ( $self, $task ) = @_;

        my $proc = _get_task_processor($task);
        unless ($proc) {
            $self->throw( q{No known processor for '} . $task->command() . q{'.} );
        }
        unless ( $proc->is_valid_args($task) ) {
            $self->throw( q{Requested command [} . $task->full_command() . q{] has invalid arguments.} );
        }
        return $proc;
    }

    sub _queue_the_task {
        my ( $self, $task ) = @_;

        $self->_get_task_processor_for_task_or_throw($task);

        my $guard = $self->{disk_state}->synch();

        $self->_add_task_to_waiting_queue($task) or return;

        $guard->update_file();

        return $task->uuid();
    }

    sub _add_task_to_waiting_queue {
        my ( $self, $task ) = @_;

        $self->_process_overrides($task);
        return if $self->_is_duplicate_command($task);

        push @{ $self->{queue_waiting} }, $task;

        return 1;
    }

    sub _timeout {
        my ( $self, $processor ) = @_;

        my $timeout = $processor->get_timeout() || $self->{default_task_timeout};

        return $timeout > $self->{max_task_timeout} ? $self->{max_task_timeout} : $timeout;
    }

    sub _clean_completed_tasks {
        my ( $self, $guard ) = @_;

        my $num_processing = @{ $self->{processing_list} };
        my $num_deferred   = @{ $self->{deferral_queue} };

        return if !$num_processing && !$num_deferred;

        $self->_remove_completed_tasks_from_list();

        return
          if @{ $self->{processing_list} } == $num_processing
          && @{ $self->{deferral_queue} } == $num_deferred;

        if ( !$guard ) {
            $guard = $self->{disk_state}->synch();
            $self->_remove_completed_tasks_from_list();
        }
        $guard->update_file();
        return;
    }

    sub _remove_completed_tasks_from_list {
        my ($self) = @_;
        $self->{processing_list} = [ grep { $_->pid() && 0 == waitpid( $_->pid(), $WNOHANG ) } @{ $self->{processing_list} } ];
        $self->_process_deferrals();
        return;
    }

    sub _add_task_to_deferral_object {
        my ( $self, $task, $processor ) = @_;
        return unless $task;

        $processor ||= _get_task_processor($task);
        $self->{defer_obj}->{$_} = 1 foreach $processor->deferral_tags($task);
        return;
    }

    sub _remove_task_from_deferral_object {
        my ( $self, $task, $processor ) = @_;
        return unless $task;

        $processor ||= _get_task_processor($task);
        delete $self->{defer_obj}->{$_} foreach $processor->deferral_tags($task);
        return;
    }

    sub _process_deferrals {
        my ($self) = @_;

        $self->{defer_obj} = {};
        foreach my $task ( @{ $self->{processing_list} } ) {
            $self->{defer_obj}->{$_} = 1 foreach _get_task_processor($task)->deferral_tags($task);
        }

        my @defer;
        foreach my $task ( @{ $self->{deferral_queue} } ) {
            if ( _get_task_processor($task)->is_task_deferred( $task, $self->{defer_obj} ) ) {
                push @defer, $task;
            }
            else {

                $self->_process_overrides($task);
                next if $self->_is_duplicate_command($task);

                unshift @{ $self->{queue_waiting} }, $task;
            }
        }

        $self->{deferral_queue} = \@defer;
        return;
    }

    sub _handle_already_running_tasks {
        my ( $self, $guard ) = @_;

        $self->_clean_completed_tasks($guard);

        while ( $self->{max_in_process} <= scalar @{ $self->{processing_list} } ) {

            my $pid;

            $guard->call_unlocked( sub { $pid = waitpid( -1, 0 ) } );

            next if $pid < 1;
            $self->{processing_list} = [ grep { $_->pid() != $pid } @{ $self->{processing_list} } ];
            $self->_process_deferrals();
            $guard->update_file();
        }
        $self->_clean_completed_tasks($guard);
        return;
    }

    sub _is_valid_uuid {
        return Cpanel::TaskQueue::Task::is_valid_taskid(shift);
    }
}

__PACKAGE__->register_task_processor( 'noop', sub { } );

1;


} # --- END Cpanel/TaskQueue.pm


{ # --- BEGIN Cpanel/TaskQueue/Scheduler.pm
package Cpanel::TaskQueue::Scheduler;



use strict;
use warnings;

# use Cpanel::TaskQueue::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::TaskQueue::Base); }

# use Cpanel::TaskQueue             ();    # PPI USE OK -- import() needs to be called on this module
# use Cpanel::TaskQueue::Serializer ();
# use Cpanel::TaskQueue::Task       ();
# use Cpanel::StateFile             ();


my $are_policies_set = 0;
my $pkg              = __PACKAGE__;

sub import {
    my ( $class, @args ) = @_;
    die "Not an even number of arguments to the $pkg module\n" if @args % 2;
    die "Policies already set elsewhere\n"                     if $are_policies_set;
    return 1 unless @args;    # Don't set the policies flag.

    while (@args) {
        my ( $policy, $module ) = splice( @args, 0, 2 );
        my @methods = ();
        if ( '-logger' eq $policy ) {
            Cpanel::StateFile->import( '-logger' => $module );
        }
        else {
            die "Unrecognized policy '$policy'\n";
        }
    }
    $are_policies_set = 1;
    return 1;
}

sub _disk_state {
    my ($self) = @_;

    return $self->{'disk_state'};
}

sub TO_JSON {
    return { %{ $_[0] } };
}

my $tasksched_uuid = 'TaskQueue-Scheduler';

{
    my $FILETYPE      = 'TaskScheduler';    # Identifier at the beginning of the state file
    my $CACHE_VERSION = 2;                  # Cache file version number.

    sub get_name { return $_[0]->{scheduler_name}; }


    sub new {
        my ( $class, $args_ref ) = @_;
        my $self = bless {
            next_id    => 1,
            time_queue => [],
            disk_state => undef,
        }, $class;

        if ( exists $args_ref->{token} ) {
            my ( $version, $name, $file ) = split( ':\|:', $args_ref->{token} );

            Cpanel::StateFile->_throw('Invalid token.')
              unless defined $version
              and defined $name
              and defined $file;

            my $name_match = Cpanel::TaskQueue::Serializer->filename("${name}_sched");
            Cpanel::StateFile->_throw('Invalid token.')
              unless 'tqsched1' eq $version and $file =~ m{/\Q$name_match\E$};

            $self->{scheduler_name}  = $name;
            $self->{disk_state_file} = $file;
        }
        else {
            $args_ref->{state_dir} ||= $args_ref->{cache_dir} if exists $args_ref->{cache_dir};
            Cpanel::StateFile->_throw('No caching directory supplied.') unless exists $args_ref->{state_dir};
            Cpanel::StateFile->_throw('No scheduler name supplied.')    unless exists $args_ref->{name};

            $self->{disk_state_file} = Cpanel::TaskQueue::Serializer->filename("$args_ref->{state_dir}/$args_ref->{name}_sched");
            $self->{scheduler_name}  = $args_ref->{name};
        }

        my $state_args = {
            state_file => $self->{disk_state_file}, data_obj => $self,

            exists $args_ref->{cache_timeout} ? ( timeout => $args_ref->{cache_timeout} ) : (),
            exists $args_ref->{state_timeout} ? ( timeout => $args_ref->{state_timeout} ) : (),
            exists $args_ref->{logger}        ? ( logger  => $args_ref->{logger} )        : (),
        };
        eval {
            $self->{disk_state} = Cpanel::StateFile->new($state_args);
            1;
        } or do {
            my $ex = $@;

            if ( $ex !~ /Not a recognized|Invalid version/ && !eval { $ex->isa('Cpanel::Exception::JSONParseError') } ) {
                Cpanel::StateFile->_throw($ex);
            }
            Cpanel::StateFile->_warn($ex);
            Cpanel::StateFile->_warn("Moving bad state file and retry.\n");
            Cpanel::StateFile->_notify(
                'Unable to load TaskQueue::Scheduler metadata',
                "Loading of [$self->{disk_state_file}] failed: $ex\n" . "Moving bad file to [$self->{disk_state_file}.broken] and retrying.\n"
            );
            unlink "$self->{disk_state_file}.broken";
            rename $self->{disk_state_file}, "$self->{disk_state_file}.broken";

            $self->{disk_state} = Cpanel::StateFile->new($state_args);
        };
        return $self;
    }

    sub throw {
        my $self = shift;
        return $self->{disk_state} ? $self->{disk_state}->throw(@_) : Cpanel::StateFile->_throw(@_);
    }

    sub info {
        my $self = shift;
        return $self->{disk_state} ? $self->{disk_state}->info(@_) : undef;
    }

    sub _state_file {
        my ($self) = @_;
        return $self->{disk_state_file};
    }

    sub load_from_cache {
        my ( $self, $fh ) = @_;

        local $/;
        my ( $magic, $version, $meta ) = Cpanel::TaskQueue::Serializer->load($fh);

        $self->throw("Not a recognized TaskQueue Scheduler state file.\n")   unless defined $magic   and $magic eq $FILETYPE;
        $self->throw("Invalid version of TaskQueue Scheduler state file.\n") unless defined $version and $version eq $CACHE_VERSION;

        $self->{next_id} = $meta->{nextid} if $meta->{nextid} > $self->{next_id};

        $self->{time_queue} = [ grep { _is_item_sane($_) } @{ $meta->{waiting_queue} } ];

        return 1;
    }

    sub save_to_cache {
        my ( $self, $fh ) = @_;

        my $meta = {
            nextid        => $self->{next_id},
            waiting_queue => $self->{time_queue},
        };
        return Cpanel::TaskQueue::Serializer->save( $fh, $FILETYPE, $CACHE_VERSION, $meta );
    }

    sub schedule_task {
        my ( $self, $command, $args ) = @_;
        return ( $self->schedule_tasks( [ [ $command, $args ] ] ) )[0];
    }

    sub schedule_tasks {
        my ( $self, $command_args_ars ) = @_;

        my $now = time();
        my @uuids;
        my $can_schedule_multiple_under_single_lock = $self->can('_schedule_the_task_under_lock') ? 1                               : 0;
        my $schedule_function                       = $can_schedule_multiple_under_single_lock    ? '_schedule_the_task_under_lock' : '_schedule_the_task';

        my $schedule_cr = sub {
            foreach my $command_args_ar (@$command_args_ars) {
                my ( $command, $args ) = @$command_args_ar;

                $self->throw('Cannot queue an empty command.') unless defined $command;
                $self->throw('Args is not a hash ref.')        unless defined $args and 'HASH' eq ref $args;

                my $time = $now;
                $time += $args->{delay_seconds} if exists $args->{delay_seconds};
                $time = $args->{at_time}        if exists $args->{at_time};

                if ( eval { $command->isa('Cpanel::TaskQueue::Task') } ) {
                    if ( 0 == $command->retries_remaining() ) {
                        $self->info('Task with 0 retries not scheduled.');
                        push @uuids, undef;
                        next;
                    }
                    push @uuids, $self->$schedule_function( $time, $command );
                    next;
                }

                $self->throw('Cannot queue an empty command.') unless $command =~ /\S/;

                my @retry_attrs = ();
                if ( exists $args->{attempts} ) {
                    if ( $args->{attempts} <= 0 ) {
                        push @uuids, undef;
                        next;
                    }
                    @retry_attrs = (
                        retries  => $args->{attempts},
                        userdata => { sched => $self->get_token() }
                    );
                }
                my $task = Cpanel::TaskQueue::Task->new(
                    {
                        cmd => $command, nsid => $tasksched_uuid, id => $self->{next_id}++,
                        @retry_attrs
                    }
                );
                push @uuids, $self->$schedule_function( $time, $task );
            }
        };

        if ($can_schedule_multiple_under_single_lock) {
            $self->do_under_guard($schedule_cr)->update_file();
        }
        else {
            $schedule_cr->();
        }

        return @uuids;
    }

    sub unschedule_task {
        my ( $self, $uuid ) = @_;

        unless ( _is_valid_uuid($uuid) ) {
            $self->throw('No Task uuid argument passed to unschedule_task.');
        }

        my $guard     = $self->{disk_state}->synch();
        my $old_count = @{ $self->{time_queue} };

        $self->{time_queue} = [ grep { $_->{task}->uuid() ne $uuid } @{ $self->{time_queue} } ];

        $guard->update_file();
        return $old_count > @{ $self->{time_queue} };
    }

    sub is_task_scheduled {
        my ( $self, $uuid ) = @_;

        unless ( _is_valid_uuid($uuid) ) {
            $self->throw('No Task uuid argument passed to is_task_scheduled.');
        }

        $self->{disk_state}->synch();

        return Cpanel::TaskQueue::_first( sub { $_->{task}->uuid() eq $uuid }, @{ $self->{time_queue} } );
    }

    sub when_is_task_scheduled {
        my ( $self, $uuid ) = @_;

        unless ( _is_valid_uuid($uuid) ) {
            $self->throw('No Task uuid argument passed to when_is_task_scheduled.');
        }

        $self->{disk_state}->synch();

        my $task = Cpanel::TaskQueue::_first( sub { $_->{task}->uuid() eq $uuid }, @{ $self->{time_queue} } );
        return unless defined $task;
        return $task->{time};
    }

    sub how_many_scheduled {
        my ($self) = @_;

        $self->{disk_state}->synch();
        return scalar @{ $self->{time_queue} };
    }

    sub peek_next_task {
        my ($self) = @_;

        $self->{disk_state}->synch();
        return unless @{ $self->{time_queue} };

        return $self->{time_queue}->[0]->{task}->clone();
    }

    sub seconds_until_next_task {
        my ($self) = @_;

        $self->{disk_state}->synch();
        return unless @{ $self->{time_queue} };

        return $self->{time_queue}->[0]->{time} - time;
    }

    sub process_ready_tasks {
        my ( $self, $queue ) = @_;

        unless ( defined $queue and eval { $queue->can('queue_task') } ) {
            $self->throw('No valid queue supplied.');
        }

        $self->{disk_state}->synch();
        my $count = 0;
        my $guard;
        eval {
            while ( @{ $self->{time_queue} } ) {
                my $item = $self->{time_queue}->[0];

                last if time() < $item->{time};
                if ( !$guard ) {

                    $guard ||= $self->{disk_state}->synch();
                    next;
                }

                $queue->queue_task( $item->{task} );
                ++$count;

                shift @{ $self->{time_queue} };
            }
        };
        my $ex = $@;
        $guard->update_file() if $count && $guard;
        $self->throw($ex)     if $ex;

        return $count;
    }

    sub flush_all_tasks {
        my ( $self, $queue ) = @_;

        unless ( defined $queue and eval { $queue->can('queue_task') } ) {
            $self->throw('No valid queue supplied.');
        }

        my @ids;
        my $guard = $self->{disk_state}->synch();
        eval {
            while ( @{ $self->{time_queue} } ) {
                my $item = $self->{time_queue}->[0];

                my $id = $queue->queue_task( $item->{task} );
                push @ids, $id if $id;

                shift @{ $self->{time_queue} };
            }
        };
        my $ex = $@;
        $guard->update_file() if @ids;
        $self->throw($ex)     if $ex;

        return @ids;
    }

    sub delete_all_tasks {
        my ($self) = @_;
        my $guard  = $self->{disk_state}->synch();
        my $count  = @{ $self->{time_queue} };
        $self->{time_queue} = [];
        $guard->update_file() if $count;

        return $count;
    }

    sub get_token {
        my ( $self, $command, $time ) = @_;

        return join( ':|:', 'tqsched1', $self->{scheduler_name}, $self->{disk_state_file} );
    }

    sub snapshot_task_schedule {
        my ($self) = @_;

        $self->{disk_state}->synch();

        return [ map { { time => $_->{time}, task => $_->{task}->clone() } } @{ $self->{time_queue} } ];
    }

    sub _schedule_the_task {
        my ( $self, $time, $task ) = @_;

        my $guard = $self->{disk_state}->synch();
        my $item  = { time => $time, task => $task };

        if ( !@{ $self->{time_queue} } || $time >= $self->{time_queue}->[-1]->{time} ) {
            push @{ $self->{time_queue} }, $item;
        }
        elsif ( $time < $self->{time_queue}->[0]->{time} ) {

            unshift @{ $self->{time_queue} }, $item;
        }
        else {

            foreach my $i ( 1 .. $#{ $self->{time_queue} } ) {
                next unless $self->{time_queue}->[$i]->{time} > $time;
                splice( @{ $self->{time_queue} }, $i, 0, $item );
                last;
            }
        }

        $guard->update_file();
        return $task->uuid();
    }

    sub _is_item_sane {
        my ($item) = @_;
        return unless 'HASH' eq ref $item;
        return unless exists $item->{task} and exists $item->{time};
        $item->{task} = Cpanel::TaskQueue::Task->reconstitute( $item->{task} );
        return unless eval { $item->{task}->isa('Cpanel::TaskQueue::Task') };
        return ( length $item->{time} && $item->{time} !~ tr{0-9}{}c );
    }

    sub _is_valid_uuid {
        return Cpanel::TaskQueue::Task::is_valid_taskid(shift);
    }
}

1;


} # --- END Cpanel/TaskQueue/Scheduler.pm


{ # --- BEGIN Cpanel/TaskQueue/Scheduler/DupeSupport.pm
package Cpanel::TaskQueue::Scheduler::DupeSupport;


use strict;
use warnings;

# use Cpanel::TaskQueue::Scheduler();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::TaskQueue::Scheduler); }

sub _schedule_the_task_under_lock {
    my ( $self, $time, $task ) = @_;

    $self->_process_overrides($task);
    return if $self->_is_duplicate_command($task);

    my $item = { time => $time, task => $task };

    if ( !@{ $self->{time_queue} } || $time >= $self->{time_queue}->[-1]->{time} ) {
        push @{ $self->{time_queue} }, $item;
    }
    elsif ( $time < $self->{time_queue}->[0]->{time} ) {

        unshift @{ $self->{time_queue} }, $item;
    }
    else {

        foreach my $i ( 1 .. $#{ $self->{time_queue} } ) {
            next unless $self->{time_queue}->[$i]->{time} > $time;
            splice( @{ $self->{time_queue} }, $i, 0, $item );
            last;
        }
    }

    return $task->uuid();
}

sub _schedule_the_task {
    my ( $self, $time, $task ) = @_;

    my $guard = $self->{disk_state}->synch();

    my $uuid = $self->_schedule_the_task_under_lock( $time, $task );

    $guard->update_file();

    return $uuid;
}

sub _is_duplicate_command {
    my ( $self, $task ) = @_;

    my $proc = Cpanel::TaskQueue::_get_task_processor($task) or die "Cannot find a processor module for “" . $task->full_command() . "”";    # PPI USE OK - Already loaded

    return defined Cpanel::TaskQueue::_first( sub { $proc->is_dupe( $task, $_->{'task'} ) }, reverse @{ $self->{time_queue} } );             # PPI USE OK - Already loaded
}

sub _process_overrides {
    my ( $self, $task ) = @_;
    my $proc = Cpanel::TaskQueue::_get_task_processor($task) or die "Cannot find a processor module for “" . $task->full_command() . "”";    # PPI USE OK - Already loaded

    $self->{time_queue} = [ grep { !$proc->overrides( $task, $_->{'task'} ) } @{ $self->{time_queue} } ];

    return;
}

1;

} # --- END Cpanel/TaskQueue/Scheduler/DupeSupport.pm


{ # --- BEGIN Cpanel/TaskQueue/PluginManager.pm
package Cpanel::TaskQueue::PluginManager;


use strict;
use warnings;
# use Cpanel::TaskQueue ();

my %plugins_list;

sub load_all_plugins {
    my %opts = @_;

    die "No directory list supplied.\n" unless exists $opts{'directories'} and 'ARRAY' eq ref $opts{'directories'};
    die "No namespace list supplied.\n" unless exists $opts{'namespaces'}  and 'ARRAY' eq ref $opts{'namespaces'};
    foreach my $dir ( @{ $opts{'directories'} } ) {
        foreach my $ns ( @{ $opts{'namespaces'} } ) {
            load_plugins( $dir, $ns );
        }
    }
    return;
}

sub load_plugins {
    my ( $root_dir, $namespace ) = @_;

    die "No directory supplied for finding plugins.\n"                      unless defined $root_dir and length $root_dir;
    die "Supplied directory '$root_dir' does not exist.\n"                  unless -d $root_dir;
    die "Supplied directory '$root_dir' not part of Perl's include path.\n" unless grep { $_ eq $root_dir } @INC;

    die "No namespace for plugins specified.\n" unless defined $namespace and length $namespace;
    die "Namespace '$namespace' not a valid Perl namespace.\n"
      unless $namespace =~ m{^ \w+ (?: :: \w+ )* $}x;

    my $ns_dir = join( '/', $root_dir, split( '::', $namespace ) );

    return unless -d $ns_dir;

    opendir( my $dir, $ns_dir ) or die "Unable to read directory '$ns_dir': $!\n";
    my @files = grep { !/^\.\.?$/ } readdir($dir);
    closedir($dir) or die "Failed to close directory '$ns_dir': $!\n";

    my @modules = map { ( /^(\w+)\.pm$/ and -f "$ns_dir/$_" ) ? $1 : () } @files;
    foreach my $mod (@modules) {
        load_plugin_by_name( $namespace . '::' . $mod );
    }
    return;
}

sub load_plugin_by_name {
    my ($modname) = @_;

    return 1 if exists $plugins_list{$modname};

    eval "require $modname;";    ## no critic (ProhibitStringyEval)
    if ($@) {
        warn "Failed to load '$modname' plugin: $@\n";
        return;
    }

    my $register = UNIVERSAL::can( $modname, 'to_register' );
    unless ( defined $register ) {
        warn "Plugin '$modname' not registered, no 'to_register' method.\n";
        return;
    }
    my $num_reg = 0;
    my @commands;
    foreach my $reg ( $register->() ) {
        unless ( 'ARRAY' eq ref $reg and 2 == @{$reg} ) {
            warn "Plugin '$modname': invalid registration entry\n";
            next;
        }
        eval { Cpanel::TaskQueue->register_task_processor( @{$reg} ); } or do {
            warn "Plugin '$modname' register failed: $@\n";
            next;
        };
        ++$num_reg;
        push @commands, $reg->[0];    # Add command name to list.
    }

    if ($num_reg) {
        $plugins_list{$modname} = \@commands;
        return 1;
    }
    return;
}

sub list_loaded_plugins {
    return keys %plugins_list;
}

sub get_plugins_hash {
    my %clone;
    while ( my ( $module, $commands ) = each %plugins_list ) {
        $clone{$module} = [ @{$commands} ];
    }
    return \%clone;
}

1;


} # --- END Cpanel/TaskQueue/PluginManager.pm


{ # --- BEGIN Cpanel/TaskQueue/Loader.pm
package Cpanel::TaskQueue::Loader;


use cPstrict;



sub load_taskqueue_modules ($logger) {
    die 'Usage: load_taskqueue_modules($logger)' if !$logger;
    if ( !$INC{'Cpanel/StateFile.pm'} || !$INC{'Cpanel/TaskQueue.pm'} ) {
        no warnings 'redefine';
        no warnings 'once';
        my $has_posix = $INC{'POSIX.pm'} ? 1 : 0;
        local $INC{'POSIX.pm'} = '__MOCK__' if !$has_posix;
        local *POSIX::WNOHANG = sub { return 1; }
          if !$has_posix;

        if ( !$INC{'Cpanel/StateFile.pm'} ) {
            require Cpanel::StateFile;    # PPI USE OK -- Code imported from GitHub
            require Cpanel::SafeFile::FileLocker;

            my $filelocker = Cpanel::SafeFile::FileLocker->new( { 'logger' => $logger } );
            'Cpanel::StateFile'->import( '-filelock' => $filelocker, '-logger' => $logger );
        }

        if ( !$INC{'Cpanel/TaskQueue.pm'} ) {
            my $was_using_scheduler = $INC{'Cpanel/TaskQueue/Scheduler.pm'} ? 1 : 0;

            require Cpanel::TaskQueue;
            if ( !$was_using_scheduler && $INC{'Cpanel/TaskQueue/Scheduler.pm'} ) {
                Cpanel::TaskQueue::Scheduler->import;
            }
        }
    }

    require Cpanel::TaskQueue::Scheduler::DupeSupport;    # PPI USE OK - used later
    require Cpanel::TaskQueue::PluginManager;             # PPI USE OK - used later

    return 1;
}

1;

} # --- END Cpanel/TaskQueue/Loader.pm


{ # --- BEGIN Cpanel/Logger/Persistent.pm


package Cpanel::Logger::Persistent;

use strict;
# use Cpanel::Logger();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Logger); }


sub new {
    my ( $class, $arg_ref ) = @_;

    $arg_ref ||= {};

    return $class->SUPER::new( { %{$arg_ref}, 'open_now' => 1 } );
}

1;

} # --- END Cpanel/Logger/Persistent.pm


{ # --- BEGIN Cpanel/LoggerAdapter.pm
package Cpanel::LoggerAdapter;


use strict;
use warnings;

# use Cpanel::Logger::Persistent ();

our $VERSION = '0.0.4';

sub new {
    my ( $class, $arg_ref ) = @_;

    return bless { _logger => Cpanel::Logger::Persistent->new($arg_ref) }, $class;
}

sub info {
    return $_[0]->{'_logger'}->info( @_[ 1 .. $#_ ] );
}

sub warn {
    return $_[0]->{'_logger'}->warn( @_[ 1 .. $#_ ] );
}

sub throw {
    my $self = shift;
    eval { $self->{'_logger'}->die(@_); };
    require Cpanel::Carp;
    die Cpanel::Carp::safe_longmess(@_);
}

sub notify {
    my ( $self, $subj, $msg ) = @_;
    return $self->{'_logger'}->notify( 'notify', { 'subject' => $subj, 'message' => $msg } );
}

1;    # Magic true value required at end of module

} # --- END Cpanel/LoggerAdapter.pm


{ # --- BEGIN Cpanel/LoggerAdapter/Lazy.pm
package Cpanel::LoggerAdapter::Lazy;


use strict;
use warnings;


our $_ACTUAL_CLASS = 'Cpanel::LoggerAdapter';

sub new {
    my ( $class, $args_ref ) = @_;

    return bless { _args => $args_ref }, $class;
}


sub info {
    my $self = shift;
    return $self->_load( 'info', @_ );
}


sub warn {
    my $self = shift;
    return $self->_load( 'warn', @_ );
}


sub throw {
    my $self = shift;
    return $self->_load( 'throw', @_ );
}


sub notify {
    my $self = shift;
    return $self->_load( 'notify', @_ );
}

sub _load {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $self     = shift;
    my $funcname = shift;

    local ( $@, $! );

    require Cpanel::LoggerAdapter;    # PPI USE OK - blessed below
    require Cpanel::Logger::Persistent;

    $self->{'_logger'} = Cpanel::Logger::Persistent->new( $self->{'_args'} );

    bless $self, $_ACTUAL_CLASS;
    return $self->$funcname(@_);
}

1;    # Magic true value required at end of module

} # --- END Cpanel/LoggerAdapter/Lazy.pm


{ # --- BEGIN Cpanel/ServerTasks.pm
package Cpanel::ServerTasks;


use strict;
# use Cpanel::TaskQueue::Loader ();

use Try::Tiny;

our $VERSION = '0.0.7';

my $logger;
my $qname = 'servers';
my $queue;
my $sched;

our $queue_dir = '/var/cpanel/taskqueue';

sub encode_param {
    my $reference = shift;
    require Cpanel::AdminBin::Serializer;
    require Cpanel::Encoder::URI;
    my $json           = Cpanel::AdminBin::Serializer::Dump($reference);
    my $encoded_string = Cpanel::Encoder::URI::uri_encode_str($json);
    return $encoded_string;
}

sub queue_task {
    my ( $plugins, @cmds ) = @_;

    if ( ref $plugins ne 'ARRAY' ) {
        die "Implementor Error: queue_task requires a list of plugins to load as the first argument";
    }
    if ( !@cmds ) {
        die "Implementor Error: queue_task requires a list of tasks to queue";
    }
    _init_task_queue_and_plugins($plugins);

    $logger ||= Cpanel::LoggerAdapter::Lazy->new();
    $queue  ||= Cpanel::TaskQueue->new( { name => $qname, cache_dir => $queue_dir, logger => $logger } );    # PPI USE OK -- This is loaded by Cpanel::TaskQueue::Loader

    $queue->do_under_guard( sub { $_[0]->queue_tasks(@cmds) } );

    return 1;
}

sub schedule_task {    ## no critic qw(Subroutines::RequireArgUnpacking)
    my $plugins = shift;
    my $delay   = shift;    # seconds
    if ( ref $plugins ne 'ARRAY' ) {
        die "Implementor Error: schedule_task requires a list of plugins to load as the first argument";
    }
    if ( !$delay || $delay !~ m{^[0-9]+$} ) {
        die "Implementor Error: schedule_task requires a numeric delay as the second argument";
    }
    if ( !@_ ) {
        die "Implementor Error: schedule_task requires a list of tasks to schedule";
    }
    return schedule_tasks( $plugins, [ map { [ $_, { 'delay_seconds' => $delay } ] } @_ ] );
}

sub schedule_tasks {
    my ( $plugins, $command_args_ars ) = @_;
    _init_task_queue_and_plugins($plugins);
    if ( ref $command_args_ars ne 'ARRAY' ) {
        die "Implementor Error: schedule_tasks requires an arrayref of commands and taskqueue schedule arguments";
    }

    require Cpanel::TaskQueue::Scheduler::DupeSupport;

    $logger ||= Cpanel::LoggerAdapter::Lazy->new();
    $sched  ||= Cpanel::TaskQueue::Scheduler::DupeSupport->new( { name => $qname, cache_dir => $queue_dir, logger => $logger } );

    my $ret;

    $sched->do_under_guard(
        sub {
            $ret = $_[0]->schedule_tasks($command_args_ars);
        }
    );

    return $ret;
}

sub load_taskqueue_modules {
    if ( !$logger ) {
        require Cpanel::LoggerAdapter::Lazy if !$INC{'Cpanel/LoggerAdapter/Lazy.pm'};
        $logger ||= Cpanel::LoggerAdapter::Lazy->new();
    }
    return Cpanel::TaskQueue::Loader::load_taskqueue_modules($logger);
}

sub _init_task_queue_and_plugins {
    my $plugins = shift;

    load_taskqueue_modules();

    local @INC = ( '/var/cpanel/perl', @INC );

    foreach my $p (@$plugins) {
        my $mod     = index( $p, '::' ) > -1 ? $p : 'Cpanel::TaskProcessors::' . $p;
        my $inc_key = $mod;
        substr( $inc_key, index( $inc_key, '::' ), 2, '/' ) while index( $inc_key, '::' ) > -1;
        next if $INC{"$inc_key.pm"};
        unless ( Cpanel::TaskQueue::PluginManager::load_plugin_by_name($mod) ) {    # PPI USE OK -- This is loaded by Cpanel::TaskQueue::Loader
            die "ERROR: Unable to load plugin: $p ($mod)\n";
        }
    }
    return 1;
}

1;

} # --- END Cpanel/ServerTasks.pm


{ # --- BEGIN Cpanel/Proc/Bin.pm
package Cpanel::Proc::Bin;


use strict;
use warnings;

sub getbin {
    return !length $_[0]
      ? ''
      : (
        (
            split(
                /\s/,
                ( readlink("/proc/$_[0]/exe") // readlink("/proc/.$_[0]/exe") ) || ''
            )
        )[0]
          || ''
      );
}

1;

} # --- END Cpanel/Proc/Bin.pm


{ # --- BEGIN Cpanel/Proc/Basename.pm
package Cpanel::Proc::Basename;


sub getbasename {
    my ($name) = @_;

    return '' if !length $name;

    $name = ( split( /\s+/, $name ) )[0] if $name =~ tr{ \t\r\n}{};

    if ( index( $name, '/' ) == 0 ) {
        return ( split( '/', $name ) )[-1];
    }
    else {
        return $name;
    }
}

1;

} # --- END Cpanel/Proc/Basename.pm


{ # --- BEGIN Cpanel/Sys/Info.pm
package Cpanel::Sys::Info;


use strict;

# use Cpanel::Pack ();

my $sysinfo_struct_size = 128;
my $SYS_sysinfo         = 99;

our $LOAD_ADJUST = 65536;    # 1 << SI_LOAD_SHIFT

our @TEMPLATE = (
    uptime => 'l!',          # long uptime

    load1  => 'L!',          # unsigned long loads[3];
    load5  => 'L!',
    load15 => 'L!',

    totalram  => 'L!',       # unsigned long totalram
    freeram   => 'L!',       # unsigned long freeram
    sharedram => 'L!',       # unsigned long sharedram
    bufferram => 'L!',       # unsigned long bufferram
    totalswap => 'L!',       # unsigned long totalswap
    freeswap  => 'L!',       # unsigned long freeswap
    procs     => 'S!',       # unsigned short procs
    pad       => 'S!',       # unsigned short pad   - from /usr/include, missing in man 2 sysinfo
    totalhigh => 'L!',       # unsigned long totalhigh
    freehigh  => 'L!',       # unsigned long freehigh
    mem_unit  => 'I!',       # unsigned int mem_unit
);



sub sysinfo {
    local $!;

    my $sysinfo_buffer = "\0" x $sysinfo_struct_size;

    my $self = syscall( $SYS_sysinfo, $sysinfo_buffer );

    die "Failed to call sysinfo(): $!" if $!;    # This should never happen since the only error is EFAULT pointer to struct sysinfo is invalid

    my $sysinfo_hr = Cpanel::Pack->new( \@TEMPLATE )->unpack_to_hashref($sysinfo_buffer);

    delete $sysinfo_hr->{'pad'};

    $_ /= $LOAD_ADJUST for @{$sysinfo_hr}{qw( load1 load5 load15 )};

    return $sysinfo_hr;
}

1;

} # --- END Cpanel/Sys/Info.pm


{ # --- BEGIN Cpanel/Sys/Uptime.pm
package Cpanel::Sys::Uptime;


use strict;
# use Cpanel::Sys::Info ();

sub get_uptime {
    return Cpanel::Sys::Info::sysinfo()->{'uptime'};
}
1;

} # --- END Cpanel/Sys/Uptime.pm


{ # --- BEGIN Cpanel/SysConf/Constants.pm
package Cpanel::SysConf::Constants;


use strict;

our $_SC_CLK_TCK  = 100;
our $_SC_PAGESIZE = 4096;
1;

} # --- END Cpanel/SysConf/Constants.pm


{ # --- BEGIN Cpanel/PsParser/SysInfo.pm
package Cpanel::PsParser::SysInfo;


use strict;
# use Cpanel::Sys::Uptime           ();
# use Cpanel::Sys::Hardware::Memory ();
# use Cpanel::SysConf::Constants    ();

sub new {
    my ($class) = @_;
    my $self = {
        'clock_ticks'         => $Cpanel::SysConf::Constants::_SC_CLK_TCK,
        'uptime'              => Cpanel::Sys::Uptime::get_uptime(),
        'installed_memory_kb' => ( 1024 * Cpanel::Sys::Hardware::Memory::get_installed() ),
        'page_size'           => $Cpanel::SysConf::Constants::_SC_PAGESIZE,
    };

    return bless $self, $class;
}

sub calculate_percent_memory_from_rsspages {
    my ( $self, $rsspages ) = @_;
    return sprintf( "%.2f", ( ( $rsspages * $self->{'page_size'} / 1024 / $self->{'installed_memory_kb'} ) * 100 ) );    # rss

}

sub calculate_percent_memory_from_rsskb {
    my ( $self, $rsskb ) = @_;
    return sprintf( "%.2f", ( ( $rsskb / $self->{'installed_memory_kb'} ) * 100 ) );    # rss

}


sub calculate_percent_cpu_from_ticks {
    my ( $self, $start_time_in_ticks, $total_running_ticks ) = @_;
    my $seconds_since_start =
      $self->{'uptime'} - ( $start_time_in_ticks / $self->{'clock_ticks'} );    # starttime
    my $seconds_running = $total_running_ticks * 1000 / $self->{'clock_ticks'};
    return sprintf(
        "%.2f",
        (
              ( $seconds_running && $seconds_since_start )
            ? ( $seconds_running / $seconds_since_start / 10 )
            : 0
        )
    );
}


sub calculate_elapsed_from_ticks {
    my ( $self, $start_time_in_ticks ) = @_;
    return sprintf( "%.2f", ( $self->{'uptime'} - ( $start_time_in_ticks / $self->{'clock_ticks'} ) ) );
}

1;

} # --- END Cpanel/PsParser/SysInfo.pm


{ # --- BEGIN Cpanel/PsParser/Fallback.pm
package Cpanel::PsParser::Fallback;


use strict;
use warnings;

# use Cpanel::SafeRun::Object ();
# use Cpanel::Exception       ();
# use Cpanel::Debug           ();
use Try::Tiny;

sub parse_ps {
    my (%OPTS)       = @_;
    my $exclude_self = $OPTS{'exclude_self'};
    my $want_uid     = $OPTS{'want_uid'};
    my ( $ps_run, $err );
    try {
        local $ENV{'TERM'} = 'dumb';
        $ps_run = Cpanel::SafeRun::Object->new(
            'program' => '/bin/ps',
            'args'    => [ '-ewwo', 'pid,uid,user,nice,pmem,pcpu,etime,state,command' ],
        );
    }
    catch {
        $err = Cpanel::Exception::get_string($_);
    };
    if ($err) {
        Cpanel::Debug::log_warn( 'Failed to retrieve process list: ' . $err );
        return;
    }

    my ( @PS, $pid, $uid, $user, $nice, $mem, $cpu, $etime, $state, $command );
    my $current_pid = $$;
    my $child_pid   = $ps_run->child_pid();
    foreach my $line ( split( m{\n}, $ps_run->stdout() ) ) {

        next if ( !length( ( ( $pid, $uid, $user, $nice, $mem, $cpu, $etime, $state, $command ) = parse_ps_line($line) )[0] ) );
        if ( $exclude_self && ( $pid == $child_pid || $pid == $current_pid ) ) { next; }
        $command =~ s/\s+\z//s;    # Strip any trailing whitespace from command and will "chomp" newlines if any

        if ( $etime =~ m{^([0-9]+)-([0-9]+):([0-9]+):([0-9]+)$} ) {
            my ( $days, $hours, $minutes, $seconds ) = ( $1, $2, $3, $4 );
            $etime = ( $days * 86400 ) + ( $hours * 3600 ) + ( $minutes * 60 ) + ($seconds);
        }
        elsif ( $etime =~ m{^([0-9]+):([0-9]+):([0-9]+)$} ) {
            my ( $hours, $minutes, $seconds ) = ( $1, $2, $3 );
            $etime = ( $hours * 3600 ) + ( $minutes * 60 ) + ($seconds);
        }

        next if ( defined $want_uid && $uid != $want_uid );    #

        push @PS,
          {
            'pid'     => $pid,
            'user'    => $user,
            'uid'     => $uid,
            'nice'    => $nice,
            'mem'     => $mem,
            'cpu'     => $cpu,
            'elapsed' => $etime,
            'state'   => $state,
            'command' => $command
          };
    }
    if ( !@PS && !length $ps_run->stdout() ) {
        Cpanel::Debug::log_warn('Failed to retrieve process list using /bin/ps');
        return;
    }
    return \@PS;
}

sub parse_ps_line {
    return ( $_[0] =~ m/^\s*(\d+)\s+(\d+)\s+(\S+)\s+([\d+-]+)\s+([\d\.%]+)\s+([\d\.%]+)\s+([\d:-]+)\s+(.)\s+(.+)$/ );
}

1;

} # --- END Cpanel/PsParser/Fallback.pm


{ # --- BEGIN Cpanel/PsParser.pm
package Cpanel::PsParser;


use strict;
use warnings;

# use Cpanel::LoadFile       ();
# use Cpanel::Proc::Bin      ();
# use Cpanel::Proc::Basename ();

use Try::Tiny;

our $READ_PROC          = 1;
our $PROC_PATH          = '/proc';
our @KNOWN_INTERPRETERS = (qw(bash tcsh zsh dash csh sh perl python ruby php));

my $PROC_STAT_OFFSET    = 3;                        # 0-index + pid + command
my $PROC_STAT_STATE     = 3 - $PROC_STAT_OFFSET;
my $PROC_STAT_PPID      = 4 - $PROC_STAT_OFFSET;
my $PROC_STAT_PGRP      = 5 - $PROC_STAT_OFFSET;
my $PROC_STAT_UTIME     = 14 - $PROC_STAT_OFFSET;
my $PROC_STAT_STIME     = 15 - $PROC_STAT_OFFSET;
my $PROC_STAT_NICE      = 19 - $PROC_STAT_OFFSET;
my $PROC_STAT_STARTTIME = 22 - $PROC_STAT_OFFSET;

my $RESERVED_PIDS = 300;                            # kernel/pid.c

sub fast_parse_ps {    ## no critic qw(Subroutines::ProhibitExcessComplexity)
    if ( $READ_PROC && -r "$PROC_PATH/1/stat" ) {
        my %OPTS = @_;
        my @PS;
        my $resolve_uids   = $OPTS{'resolve_uids'};
        my $memory_stats   = $OPTS{'memory_stats'};
        my $elapsed_stats  = $OPTS{'elapsed_stats'};
        my $cpu_stats      = $OPTS{'cpu_stats'};
        my $exclude_self   = $OPTS{'exclude_self'};
        my $exclude_kernel = $OPTS{'exclude_kernel'};
        my $want_pid       = $OPTS{'want_pid'};
        my $want_uid       = $OPTS{'want_uid'};
        my $skip_cmdline   = $OPTS{'skip_cmdline'};
        my $skip_stat      = $OPTS{'skip_stat'};

        if ($skip_stat) {
            if ($exclude_kernel) {
                die "The parameters ”skip_stat” and “exclude_kernel” are mutually exclusive.";
            }
            elsif ($cpu_stats) {
                die "The parameters ”skip_stat” and “cpu_stats” are mutually exclusive.";
            }
            elsif ($elapsed_stats) {
                die "The parameters ”skip_stat” and “elapsed_stats” are mutually exclusive.";
            }
            elsif ( !$skip_cmdline ) {
                die "The parameters ”skip_stat” requires “skip_cmdline”";

            }
        }

        my $sysinfo_obj;
        if ( $cpu_stats || $memory_stats || $elapsed_stats ) {
            require Cpanel::PsParser::SysInfo;
            $sysinfo_obj = Cpanel::PsParser::SysInfo->new();
        }
        require Cpanel::PwCache if $resolve_uids;
        if ( opendir( my $proc_dh, $PROC_PATH ) ) {
            my ( $stat, $cmd, $cmdline, $user );
            my $current_pid = $$;
            foreach my $pid ( grep { $_ !~ tr/0-9//c } readdir($proc_dh) ) {
                if (
                    ( $exclude_self && $pid == $current_pid ) ||    #
                    ( $want_pid && $pid != $want_pid ) || ( $exclude_kernel && $pid < $RESERVED_PIDS )
                ) {
                    next;
                }
                my $uid = ( stat("$PROC_PATH/$pid") )[4];
                if (
                    !defined $uid ||                                #
                    ( defined $want_uid && $uid != $want_uid )      #
                ) {
                    next;
                }
                $user = $uid == 0 ? 'root' : $resolve_uids ? ( Cpanel::PwCache::getpwuid($uid) )[0] : $uid;

                $cmdline = '';
                if ( !$skip_cmdline ) {
                    if ( $cmdline = Cpanel::LoadFile::loadfile( "$PROC_PATH/$pid/cmdline", { 'skip_exists_check' => 1 } ) ) {
                        $cmdline =~ tr/\0/ /;
                        $cmdline =~ s/\s+\z//s if substr( $cmdline, -1 ) =~ tr{ \t\f\r\n}{};    # Strip any trailing whitespace from command and will "chomp" newlines if any
                    }
                }

                if ( !$skip_stat ) {

                    ( $cmd, $stat ) = split( /\)(?=[^\)]+$) ?/, Cpanel::LoadFile::loadfile( "$PROC_PATH/$pid/stat", { 'skip_exists_check' => 1 } ) || '', 2 );
                    next unless $stat;

                    $stat = [ split( ' ', $stat ) ];

                    if ( !length $cmdline ) {

                        $cmd =~ s/^[0-9]+\s+\(?//g;

                        $cmd = '[' . $cmd . ']';
                    }

                    if ( $exclude_kernel && $stat->[$PROC_STAT_PGRP] == 0 ) { next; }
                }

                $cmdline ||= $cmd;

                my %process_info = (
                    'pid'  => $pid,
                    'user' => $user,
                    'uid'  => $uid,
                    $skip_stat ? () : (
                        'nice'    => $stat->[$PROC_STAT_NICE],
                        'state'   => $stat->[$PROC_STAT_STATE],
                        'ppid'    => $stat->[$PROC_STAT_PPID],
                        'command' => $cmdline,
                    )
                );

                if ($memory_stats) {

                    my $statm = Cpanel::LoadFile::loadfile("$PROC_PATH/$pid/statm");
                    if ( defined $statm && $statm =~ m<\S+\s+(\S+)> ) {
                        $process_info{'mem'} = $sysinfo_obj->calculate_percent_memory_from_rsspages($1);
                    }
                }
                if ($cpu_stats) {
                    $process_info{'cpu'} = $sysinfo_obj->calculate_percent_cpu_from_ticks(
                        $stat->[$PROC_STAT_STARTTIME],
                        $stat->[$PROC_STAT_UTIME] + $stat->[$PROC_STAT_STIME]
                    );
                }
                if ($elapsed_stats) {
                    $process_info{'elapsed'} = $sysinfo_obj->calculate_elapsed_from_ticks( $stat->[$PROC_STAT_STARTTIME] );
                }
                push @PS, \%process_info;
            }
        }
        return \@PS;
    }

    goto \&parse_ps;
}

sub get_pid_info {
    my ($pid) = @_;
    return fast_parse_ps(
        'cpu_stats'     => 1,
        'elapsed_stats' => 1,
        'exclude_self'  => 1,
        'memory_stats'  => 1,
        'resolve_uids'  => 1,
        'want_pid'      => $pid,
    )->[0];
}

sub _get_child_pids {
    my ( $ppid, $ps_ref ) = @_;

    my @out  = grep { $_->{'ppid'} == $ppid } @{$ps_ref};
    my @pids = map  { $_->{'pid'} } @out;
    my @subpids;

    foreach my $pid (@pids) {
        push( @subpids, _get_child_pids( $pid, $ps_ref ) );
    }

    push( @pids, @subpids );

    return @pids;
}

sub get_child_pids {
    my (@ppids) = @_;

    my $ps_ref = Cpanel::PsParser::fast_parse_ps(
        'cpu_stats'     => 1,
        'elapsed_stats' => 1,
        'exclude_self'  => 1,
        'memory_stats'  => 1,
        'resolve_uids'  => 1,
    );

    my @pids;
    my %seen;
    foreach my $pid (@ppids) {
        foreach my $xpid ( _get_child_pids( $pid, $ps_ref ) ) {
            push( @pids, $xpid ) if ( !exists $seen{$xpid} );
            $seen{$xpid} = 1;
        }
    }

    return @pids;
}

sub parse_ps {
    require Cpanel::PsParser::Fallback;
    goto \&Cpanel::PsParser::Fallback::parse_ps;
}

sub get_pids_by_name {
    my ( $deadcmd, $allowed_owners ) = @_;

    return unless defined $deadcmd;

    if ( $> != 0 ) { $allowed_owners = { $> => 1 }; }

    my $deadcmd_regex_text = '^(?:' . ( ref $deadcmd eq 'ARRAY' ? join( '|', map { quotemeta($_) } @{$deadcmd} ) : quotemeta($deadcmd) ) . ')$';
    my $deadcmd_regex      = ref $deadcmd eq 'Regexp' ? $deadcmd : qr/$deadcmd_regex_text/i;

    if ( '' =~ $deadcmd_regex ) {
        return;    #can't match ''
    }
    if ( defined $allowed_owners && ref $allowed_owners eq 'ARRAY' ) {
        $allowed_owners = { map { $_ => 1 } @{$allowed_owners} };
    }
    if ( defined $allowed_owners ) {

        $allowed_owners = { map { ( $_ !~ tr{0-9}{}c ? $_ : ( _lazy_getpwnam($_) )[2] ) => 1 } keys %$allowed_owners };
    }

    my ( $process_name_first_element, @process_name_secondary_elements, $file, $binary_path, $owner );
    if ( $READ_PROC && -r "$PROC_PATH/1/cmdline" && opendir( my $proc_dh, $PROC_PATH ) ) {
        my @pids;
        foreach my $proc ( grep { $_ !~ tr{0-9}{}c } readdir($proc_dh) ) {    # Only has numbers so its a pid
            next if $proc < $RESERVED_PIDS;
            $binary_path = readlink("$PROC_PATH/$proc/exe") or next;


            $owner = ( stat("$PROC_PATH/$proc") )[4];    #getbin will stat the /proc/<pid>
            if ( !defined $owner || ( defined $allowed_owners && !exists $allowed_owners->{$owner} ) ) { next; }

            ( $process_name_first_element, @process_name_secondary_elements ) = map { Cpanel::Proc::Basename::getbasename($_) } ( split( /[\s\0]+/, Cpanel::LoadFile::loadfile( "$PROC_PATH/$proc/cmdline", { 'skip_exists_check' => 1 } ) || '' ) );    # Note: process may go away during lookup

            next if !length $process_name_first_element;
            $file = ( split( m{/}, $binary_path ) )[-1];

            if ( _proc_matches_regex( $deadcmd_regex, $process_name_first_element, \@process_name_secondary_elements, $deadcmd, $file ) ) {
                push @pids, $proc + 0;                                                                                                                                                                                                                   # + 0 for 5.12
            }

        }

        return @pids;
    }

    my @pids;
    my $ps_list = fast_parse_ps( 'exclude_kernel' => 1 );
    return if ( !ref $ps_list );

    foreach my $proc ( @{$ps_list} ) {
        if ( defined $allowed_owners && !exists $allowed_owners->{ $proc->{'uid'} } ) { next; }

        ( $process_name_first_element, @process_name_secondary_elements ) = map { Cpanel::Proc::Basename::getbasename($_) } ( split( /\s+/, $proc->{'command'} ) );
        $file = ( split( /\//, Cpanel::Proc::Bin::getbin( $proc->{'pid'} ) ) )[-1] || '';

        next if !length $process_name_first_element;

        if ( _proc_matches_regex( $deadcmd_regex, $process_name_first_element, \@process_name_secondary_elements, $deadcmd, $file ) ) {
            push @pids, $proc->{'pid'} + 0;    # + 0 for 5.12
        }

    }

    return @pids;
}

sub _lazy_getpwnam {
    eval 'require Cpanel::PwCache' if !$INC{'Cpanel/PwCache.pm'};
    return Cpanel::PwCache::getpwnam(@_);
}

my $_vm_regex;
my $_interpreters_regex;

sub _proc_matches_regex {
    my ( $deadcmd_regex, $process_name_first_element, $process_name_secondary_elements_ref, $deadcmd, $file ) = @_;

    if ( !$_vm_regex ) {
        $_interpreters_regex ||= get_known_interpreters_regex();
        $_vm_regex = qr/(?:^|\/)$_interpreters_regex$/;
    }
    my $is_vm;

    if ( $process_name_first_element =~ tr/-:// ) {
        $process_name_first_element =~ s/^-//;
        $process_name_first_element =~ s/:$//;
    }

    if ( $process_name_first_element =~ m{$_vm_regex}o ) {

        $is_vm = 1;
        while ( @{$process_name_secondary_elements_ref} && index( $process_name_secondary_elements_ref->[0], '-' ) == 0 ) {
            shift( @{$process_name_secondary_elements_ref} );
        }
    }

    return 1 if length($file) && ( $deadcmd eq $file );
    return 1 if $process_name_first_element =~ $deadcmd_regex;
    return 1 if $is_vm && @$process_name_secondary_elements_ref && ( $process_name_secondary_elements_ref->[0] =~ $deadcmd_regex );

    return 0;
}

sub get_known_interpreters_regex {

    my $interpreters = join( '|', @KNOWN_INTERPRETERS );

    return qr/(?:$interpreters)[0-9.]*/;
}

1;

} # --- END Cpanel/PsParser.pm


{ # --- BEGIN Cpanel/Signal/Numbers.pm
package Cpanel::Signal::Numbers;


use strict;

our %SIGNAL_NUMBER = (
    'HUP'  => 1,
    'KILL' => 9,
    'TERM' => 15,
    'USR1' => 10,
    'USR2' => 12,
    'ALRM' => 14,
    'CHLD' => 17,
);

1;

} # --- END Cpanel/Signal/Numbers.pm


{ # --- BEGIN Cpanel/Kill.pm
package Cpanel::Kill;



use strict;
# use Cpanel::PsParser        ();
# use Cpanel::Signal::Numbers ();
# use Cpanel::TimeHiRes       ();
our $VERBOSE = 1;

use constant _ESRCH => 3;

sub _verify_proc_mounted {
    if ( !-e "/proc/1" ) {
        return ( 0, "Critical Error: /proc is not mounted, and we do not have permission to mount it!" ) if $> != 0;
        print "Critical Error: /proc is not mounted)!\n";
        print "Attempting to mount /proc...";
        system( "mount", "-t", "procfs", "/proc", "/proc" );
        print "Done\n";
        if ( !-e "/proc/1" ) {
            return ( 0, "Critical Error: /proc is still not mounted!" );
        }

    }
    return ( 1, "Proc OK" );
}


sub safekill_multipid {
    my ( $pid_ar, $verbose, $wait_time_in_seconds ) = @_;

    return _safekill_multipid( $pid_ar, $verbose, $wait_time_in_seconds );
}

sub safekill {
    my ( $deadcmd, $verbose, $wait_time_in_seconds, $immune_pids_ar, $allowed_owners ) = @_;

    my $txtdeadcmd = ref $deadcmd eq 'ARRAY' ? join( ',', @{$deadcmd} ) : $deadcmd;

    my $immune_pids_hr = _generate_immune_pids_hr_from_ar($immune_pids_ar);

    my @pids = grep { !$immune_pids_hr->{$_} } Cpanel::PsParser::get_pids_by_name( $deadcmd, $allowed_owners );

    if ( !@pids ) {
        print "Waiting for $txtdeadcmd to shutdown ... not running.\n" if $verbose;
        return 0;
    }

    return _safekill_multipid( \@pids, $verbose, $wait_time_in_seconds, $immune_pids_hr, $txtdeadcmd );
}

sub _generate_immune_pids_hr_from_ar {
    my ($immune)    = @_;
    my $mypid       = $$;
    my %immune_pids = map { $_ => 1 } @{ $immune || [] };
    $immune_pids{$mypid} = 1;

    return \%immune_pids;

}

sub _safekill_multipid {
    my ( $pid_ref, $verbose, $wait_time_in_seconds, $immune_hr, $txtdeadcmd ) = @_;

    my @pids = @$pid_ref;

    $wait_time_in_seconds ||= 15;
    $txtdeadcmd           ||= join( ',', @pids );

    print "Waiting for $txtdeadcmd to shutdown ..." if $verbose;

    my $num_killed = _kill_group( 'TERM', @pids );

    if ( !$num_killed ) {
        print " not running.\n" if $verbose;
        return 0;
    }

    my $waited = 0;
    while ( $num_killed && $waited <= $wait_time_in_seconds ) {
        print '.' if $verbose;

        $num_killed = _kill_group( 0, @pids );

        if ( !$num_killed ) {
            print " terminated.\n" if $verbose;
            return 1;
        }

        if ( $waited > 0.5 ) {
            $waited += 0.05;
            Cpanel::TimeHiRes::sleep(0.05);
        }
        elsif ( $waited > 0.01 ) {
            $waited += 0.01;
            Cpanel::TimeHiRes::sleep(0.01);
        }
        else {
            $waited += 0.0025;
            Cpanel::TimeHiRes::sleep(0.0025);
        }

        waitpid( $_, 1 ) for @pids;    # in case its a child of us and in zombie state
    }

    print " terminating $txtdeadcmd ..." if $verbose;

    $num_killed = _kill_group( 'KILL', @pids );

    if ( !$num_killed ) {
        print " terminated.\n" if $verbose;
        return 0;
    }

    while ( $num_killed && ( $waited <= $wait_time_in_seconds * 2 ) ) {
        print '.' if $verbose;
        $num_killed = _kill_group( 0, @pids );
        if ( !$num_killed ) {
            print " terminated.\n" if $verbose;
            return 1;
        }
        Cpanel::TimeHiRes::sleep(0.1);
        $waited += 0.1;
        waitpid( $_, 1 ) for @pids;    # in case its a child of us and in zombie state
    }

    print " failed to kill process.\n" if $verbose;
    return 0;
}

sub _kill_group {
    my ( $signal, @pids ) = @_;

    my $num_killed = 0;

    for my $pid (@pids) {
        if ( kill $signal, $pid ) {
            $num_killed++;
        }
        elsif ($!) {
            warn "kill($signal, $pid): $!" if $! != _ESRCH();
        }
    }

    return $num_killed;
}


sub killall {
    my ( $signal, $deadcmd, $verbose, $immune, $allowed_owners_hr ) = @_;
    my $mypid = $$;
    $signal =~ tr/-//d;

    my ( $proc_status, $proc_statusmsg ) = _verify_proc_mounted();

    $signal = $Cpanel::Signal::Numbers::SIGNAL_NUMBER{$signal} if $signal =~ tr{0-9}{}c;

    if ( $signal =~ tr{0-9}{}c || $deadcmd eq "" ) {
        return ( 0, 0, "Usage: killall(signal, command, [verbose, immunte, allowed_owners_hr])" );
    }
    elsif ( $deadcmd eq "init" ) {
        die "PANIC! Attempted to kill init!\n";
    }

    my %immune_pids = map { $_ => 1 } @{ $immune || [] };
    $immune_pids{$mypid} = 1;
    my @pids = grep { !$immune_pids{$_} } Cpanel::PsParser::get_pids_by_name( $deadcmd, $allowed_owners_hr );

    my @killed_pids;

    for my $pid (@pids) {
        if ( kill $signal, $pid ) {
            push @killed_pids, $pid;
        }
        else {
            warn "kill($signal, $pid): $!";
        }
    }

    my $pretty_proc_names = ref $deadcmd eq 'ARRAY' ? join( ',', @{$deadcmd} ) : $deadcmd;

    my $killed_str   = @killed_pids ? "@killed_pids: " : q<>;
    my $procs_killed = 0 + @killed_pids;

    return ( 1, $procs_killed, "$procs_killed process" . ( $procs_killed > 1 || $procs_killed == 0 ? "es" : '' ) . " ($killed_str" . $pretty_proc_names . ") sent signal $signal" );
}

1;

} # --- END Cpanel/Kill.pm


{ # --- BEGIN Cpanel/Signal.pm
package Cpanel::Signal;


use strict;
use warnings;

# use Cpanel::Debug ();

sub send_hup_cpsrvd {
    return if ( send_hup('cpsrvd') );

    print "Could not send a signal to cpsrvd to restart. Forcing it down with startcpsrvd\n";

    require Cpanel::ServerTasks;
    local $@;
    eval {

        Cpanel::ServerTasks::schedule_task( ['CpServicesTasks'], 1, 'startcpsrvd' );
        1;
    };

    if ($@) {
        Cpanel::Debug::log_warn("Failure to schedule task: $@");
        return 0;
    }

    return 1;

}

sub send_hup_dnsadmin {
    return send_hup('dnsadmin');
}

sub send_hup_cpanellogd {
    return send_hup('cpanellogd');
}

sub send_hup_cphulkd {
    return send_hup( 'cPhulkd', '/var/run/cphulkd_processor.pid' );
}

sub send_hup_proftpd {
    return send_hup( 'proftpd', '/var/proftpd.pid' );
}

sub send_hup_tailwatchd {
    return send_hup( 'tailwatchd', '/var/run/tailwatchd.pid' );
}

sub send_usr1_tailwatchd {
    return send_usr1( 'tailwatchd', '/var/run/tailwatchd.pid' );
}

sub send_hup {
    my ( $proc_name, $pidfile ) = @_;
    return _send_signal( $proc_name, $pidfile, 'HUP' );
}

sub send_usr1 {
    my ( $proc_name, $pidfile ) = @_;
    return _send_signal( $proc_name, $pidfile, 'USR1' );
}

sub _send_signal {
    my ( $proc_name, $pidfile, $signal ) = @_;
    return if !$proc_name;
    $pidfile ||= "/var/run/$proc_name.pid";

    if ( open( my $pid_fh, '<', $pidfile ) ) {
        if ( defined read( $pid_fh, my $pid_file_contents, 4096 ) ) {
            close $pid_fh;

            if ( $pid_file_contents =~ m<\A([0-9]+)\s*\z> ) {
                my $pid = $1;

                if ( $pid < 2 ) {
                    Cpanel::Debug::log_warn("$pidfile contained an invalid PID ($pid)");
                }
                else {
                    return 1 if kill( $signal, $1 );
                }
            }
            else {
                Cpanel::Debug::log_warn("$pidfile contains invalid data: “$pid_file_contents”");
            }
        }
        else {
            Cpanel::Debug::log_warn("Failed to read $pidfile: $!");
        }
    }

    require Cpanel::Kill;
    my ( $ok, $procs_killed, $msg ) = Cpanel::Kill::killall( $signal, $proc_name, undef, undef, { 'root' => 1 } );
    return $procs_killed;

}

1;

} # --- END Cpanel/Signal.pm


{ # --- BEGIN Cpanel/Update/Blocker/Base.pm
package Cpanel::Update::Blocker::Base;


use cPstrict;

use Try::Tiny;

# use Cpanel::iContact         ();
# use Cpanel::FileUtils::Open  ();
# use Cpanel::LoadModule       ();
# use Cpanel::Hostname         ();
# use Cpanel::Update::Config   ();
# use Cpanel::Update::Logger   ();
# use Cpanel::Version::Compare ();


sub update_blocks_fname {
    return '/var/cpanel/update_blocks.config';
}

sub new {
    my ( $class, $self ) = @_;

    die("Unexpected class passed to new for Cpanel::Update::Blocker.") unless $class && $class eq 'Cpanel::Update::Blocker';
    die("Options hash ref not passed to new")                          unless $self  && ref($self) eq 'HASH';

    $self->{'logger'} ||= Cpanel::Update::Logger->new();
    $self->{'starting_version'} or die("Must be passed starting_version to do blocker calculations");
    $self->{'target_version'}   or die("Must be passed target_version to do blocker calculations");
    $self->{'upconf_ref'}       or die("Need upconf_ref to do blocker calculations");

    $self->{'is_fatal_block'} = 0;

    $self = bless $self, $class;

    $self->{'messages'} = [];

    return $self;
}

sub upgrade_deferred_file {
    return '/var/cpanel/upgrade_deferred';
}


sub logger {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    return $self->{'logger'};
}


sub block_version_change {
    my ( $self, $message, $severity, $notify ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    return unless $message;

    $severity //= 'fatal';
    $notify   //= 1;

    if ( $severity !~ m/quiet/i ) {
        push( @{ $self->{'messages'} }, { 'message' => $message, 'severity' => $severity, 'notify' => $notify } );
    }

    $message =~ s/<a.*?>//ig;
    $message =~ s{</a>}{}ig;
    $message =~ s{&reg;}{®}g;    # Convert the HTML directive to a raw UTF-8 char.

    $self->logger->error("Blocker found: $message");

    $self->{'is_fatal_block'}++;

    return $self->{'is_fatal_block'};
}


sub is_fatal_block {
    my ( $self, $new_value ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    if ( defined $new_value ) {
        $self->{'is_fatal_block'} = $new_value;
    }

    return $self->{'is_fatal_block'};
}


sub delay_upgrade {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    if ( $self->is_fatal_block ) {
        return 10;
    }

    return 1 if $self->{'force'};

    return 2 unless $ENV{'CPANEL_IS_CRON'};

    my $current_tier = Cpanel::Update::Config::get_tier( $self->{'upconf_ref'} );

    return 3 unless ( $current_tier =~ m/^(?:release|stable|lts)/i );

    return 5 unless $self->{'tiers'}->is_version_stable_release_or_lts( $self->{'target_version'} );

    my $target_major   = Cpanel::Version::Compare::get_major_release( $self->_Target_version() )    or return 21;    # Pretty sure return 21
    my $starting_major = Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} ) or return 22;    # and return 22 can't happen.
    return 20 if $starting_major eq $target_major;

    my $touchfile = $self->upgrade_deferred_file;

    my $mtime = ( stat($touchfile) )[9];

    return 6 if $mtime && $mtime < time;

    if ( !$mtime ) {
        $mtime = $self->_get_future_upgrade_date();
        return 7 if !$mtime;    # we are not delayed
        $self->_alter_mtime( $touchfile, $mtime );
    }

    $self->block_version_change( "Upgrade to the next $target_major build is blocked in order to gradually distribute upgrades over multiple days. If you wish to upgrade now, you can do so by executing ‘/usr/local/cpanel/scripts/upcp --force’ via SSH or ‘WHM → Home → Server Configuration → Terminal’", 'info', 0 );

    return 8;                   # the only meaningful return code...
}

sub _Target_version ($self) {
    return $self->{'target_version'};
}

sub generate_blocker_file {
    my ( $self, $notify ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    return unless $self->{'messages'} && ref( $self->{'messages'} ) eq 'ARRAY';

    my @messages            = @{ $self->{'messages'} };
    my $update_blocks_fname = $self->update_blocks_fname;

    if ( !@messages ) {
        if ( -e $update_blocks_fname ) {
            unlink($update_blocks_fname) or $self->logger->error("Unable to unlink $update_blocks_fname");
        }
        return;
    }

    open( my $fh, '>', $update_blocks_fname )
      or die("Unable to open $update_blocks_fname");

    my $message = join( "\n", map { "$_->{'severity'},$_->{'message'}" } @messages );
    print {$fh} $message;
    close($fh);

    $notify &&= grep { $_->{'notify'} } @messages;

    if ($notify) {

        if ( try { Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Update::Blocker') } ) {

            my @notifications;
            foreach (@messages) {
                ( my $message_sanitized = $_->{'message'} ) =~ s{<\/?a.*?>}{}ig;
                push @notifications, { 'severity' => $_->{'severity'}, 'message' => $message_sanitized };
            }
            $self->_send_icontact_class_notification(
                'class'            => 'Update::Blocker',
                'application'      => 'Update::Blocker',
                'constructor_args' => [
                    'origin'           => 'upcp',
                    'host'             => Cpanel::Hostname::gethostname(),
                    'messages'         => \@notifications,
                    'starting_version' => $self->{'starting_version'},
                    'target_version'   => $self->{'target_version'},
                ]
            );
        }
        else {

            $message =~ s{<\/?a.*?>}{}ig;
            my $subject = "cPanel version change from “$self->{'starting_version'}” to “$self->{'target_version'}” is blocked";
            $self->_send_icontact_noclass_notification( $subject, $message );

        }

    }

    return 1;
}


sub _roll_100_die {    # random value from 1..100
    my ($self) = @_;

    die('This is a method call.') unless ref $self eq 'Cpanel::Update::Blocker';

    return int( rand(100) ) + 1;
}


sub update_speed {
    my ($self) = @_;

    die('This is a method call.') unless ref $self eq 'Cpanel::Update::Blocker';

    return [
        1,     # day 0 -> +1% of customers can update
        2,     # day 1 -> +2%
        4,     # day 2 -> +4%
        6,     # day 3
        12,    # day 4
        15,    # day 5
        15,    # day 6
        15,    # day 7
        15,    # day 8
        15,    # day 9
    ];
}


sub update_in_n_days {
    my ($self) = @_;

    die('This is a method call.') unless ref $self eq 'Cpanel::Update::Blocker';

    my $die = $self->_roll_100_die();

    my $update_speed = $self->update_speed();

    my $day_pos     = 0;    # which day position we are going to
    my $total_pcent = 0;    # cumulate percentage

    foreach my $pcent (@$update_speed) {
        $total_pcent += $pcent;

        last if $die <= $total_pcent;
        ++$day_pos;
    }

    if ( $day_pos >= scalar @$update_speed ) {
        $day_pos = scalar @$update_speed - 1;
    }

    return $day_pos;
}


sub _get_future_upgrade_date {
    my ( $self, $now ) = @_;

    die('This is a method call.') unless ref $self eq 'Cpanel::Update::Blocker';

    my $update_speed = $self->update_speed();

    my $update_in_n_days = $self->update_in_n_days();

    $now ||= time();
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime($now);

    $now = $now - $sec - $min * 60 - $hour * 60 * 60;

    my $ten_first_days = $self->_get_first_valid_ndays( scalar @$update_speed, $wday );

    if ( $update_in_n_days == 0 && $ten_first_days->[0] == 0 ) {

        return;
    }

    my $one_day = 86400;

    $now += $one_day * $ten_first_days->[$update_in_n_days];

    return $now;
}


sub _get_first_valid_ndays {
    my ( $self, $ndays, $wday ) = @_;

    die('This is a method call.') unless ref $self eq 'Cpanel::Update::Blocker';
    die "NDays need to be > 0"    unless $ndays && $ndays > 0;


    my $FRIDAY   = 5;
    my $SATURDAY = 6;
    my $SUNDAY   = 0;

    die "Invalid wday" unless defined $wday && $SUNDAY <= $wday && $wday <= $SATURDAY;


    my @days;

    my $c = 0;

    while (1) {

        next if ( $wday == $FRIDAY || $wday == $SATURDAY || $wday == $SUNDAY );
        push @days, $c;

        last if scalar @days == $ndays;
    }
    continue {
        ++$c;
        $wday = ( $wday + 1 ) % 7;
    }

    return \@days;
}


sub _alter_mtime {
    my ( $self, $touchfile, $future ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    die 'No touchfile'    if !$touchfile;
    die 'No future mtime' if !$future;

    Cpanel::FileUtils::Open::sysopen_with_real_perms(
        my $t_fh,
        $touchfile,
        'O_WRONLY|O_TRUNC|O_CREAT',
        0640
    ) or die "Cannot create touchfile $touchfile - $!";
    close $t_fh;
    utime( $future, $future, $touchfile ) or $self->logger->warning("Unable to set future mtime on $touchfile");

    return;
}

sub _send_icontact_class_notification {
    my ( $self, %notification_args ) = @_;

    require Cpanel::Notify;
    return Cpanel::Notify::notification_class(%notification_args);
}

sub _send_icontact_noclass_notification {
    my ( $self, $subject, $message ) = @_;

    return Cpanel::iContact::icontact(
        'application' => 'upcp',
        'subject'     => $subject,
        'message'     => $message,
    );
}


1;

} # --- END Cpanel/Update/Blocker/Base.pm


{ # --- BEGIN Cpanel/IP/NonlocalBind/Cache.pm
package Cpanel::IP::NonlocalBind::Cache;


use strict;
use warnings;


use constant {
    DISABLED => '',    # 0-bytes
    ENABLED  => 1,     # 1-byte
    UNKNOWN  => 22,    # 2-bytes

    _ENOENT => 2,
};

our $CACHE_FILE = '/var/cpanel/ipv4_ip_nonlocal_bind';

our $_ipv4_ip_nonlocal_bind_cache_length;


sub ipv4_ip_nonlocal_bind_is_enabled {


    if ( !defined $_ipv4_ip_nonlocal_bind_cache_length ) {
        $_ipv4_ip_nonlocal_bind_cache_length = ( stat($CACHE_FILE) )[7];

        if ( !defined $_ipv4_ip_nonlocal_bind_cache_length ) {
            if ( $! != _ENOENT() ) {
                warn "stat($CACHE_FILE): $!";
            }
        }
    }

    if ( defined $_ipv4_ip_nonlocal_bind_cache_length ) {
        return 1 if $_ipv4_ip_nonlocal_bind_cache_length == length ENABLED();
        return 0 if $_ipv4_ip_nonlocal_bind_cache_length == length DISABLED();

        if ( $_ipv4_ip_nonlocal_bind_cache_length != length UNKNOWN() ) {
            warn "“$CACHE_FILE” has unrecognized length: $_ipv4_ip_nonlocal_bind_cache_length";
        }
    }

    return undef;
}

1;

} # --- END Cpanel/IP/NonlocalBind/Cache.pm


{ # --- BEGIN Cpanel/Validate/IP/Expand.pm
package Cpanel::Validate::IP::Expand;


use strict;
use warnings;

# use Cpanel::Validate::IP     ();
# use Cpanel::Validate::IP::v4 ();

sub normalize_ipv4 {
    return unless Cpanel::Validate::IP::v4::is_valid_ipv4( $_[0] );
    return join '.', map { $_ + 0 } split /\./, $_[0];
}

sub expand_ipv6 {
    my $ip = shift;

    return unless Cpanel::Validate::IP::is_valid_ipv6($ip);

    return $ip if length $ip == 39;    # already expanded

    my @seg = split /:/, $ip, -1;

    $seg[0]  = '0000' if !length $seg[0];
    $seg[-1] = '0000' if !length $seg[-1];

    if ( $seg[-1] =~ tr{.}{} && Cpanel::Validate::IP::v4::is_valid_ipv4( $seg[-1] ) ) {
        my @ipv4 = split /\./, normalize_ipv4( pop @seg );
        push @seg, sprintf( '%04x', ( $ipv4[0] << 8 ) + $ipv4[1] ), sprintf( '%04x', ( $ipv4[2] << 8 ) + $ipv4[3] );
    }
    my @exp;
    for my $seg (@seg) {
        if ( !length $seg ) {
            my $count = scalar(@seg) - scalar(@exp);
            while ( $count + scalar(@exp) <= 8 ) {
                push @exp, '0000';
            }
        }
        else {
            push @exp, sprintf( '%04x', hex $seg );
        }
    }
    return join ':', @exp;
}

sub normalize_ipv6 {
    my $ip = shift;

    return unless $ip = expand_ipv6($ip);

    $ip = lc($ip);

    $ip =~ s/:(0+:){2,}/::/;         # flatten multiple groups of 0's to :: #
    $ip =~ s/(:0+){2,}$/::/;         # flatten multiple groups of 0's to :: #
    $ip =~ s/^0+([1-9a-f])/$1/;      # flatten the first segment's leading 0's to a single 0 #
    $ip =~ s/:0+([1-9a-f])/:$1/g;    # flatten each segment, after the first, leading 0's to a single 0 #
    $ip =~ s/:0+(:)/:0$1/g;          # flatten any segments that are just 0's to a single 0 #
    $ip =~ s/:0+$/:0/g;              # flatten the end segment if it's just 0's to a single 0 #
    $ip =~ s/^0+::/::/;              # remove single 0 at the beginning #
    $ip =~ s/::0+$/::/;              # remote single 0 at the end #

    return $ip;

}

sub normalize_ip {
    return !defined $_[0] ? undef : index( $_[0], ':' ) > -1 ? normalize_ipv6( $_[0] ) : normalize_ipv4( $_[0] );
}

sub expand_ip {
    return !defined $_[0] ? undef : index( $_[0], ':' ) > -1 ? expand_ipv6( $_[0] ) : normalize_ipv4( $_[0] );
}

1;

} # --- END Cpanel/Validate/IP/Expand.pm


{ # --- BEGIN Cpanel/IP/Expand.pm
package Cpanel::IP::Expand;


use strict;
use warnings;

# use Cpanel::Validate::IP::v4     ();
# use Cpanel::Validate::IP::Expand ();

sub expand_ip {
    my ( $ip, $version ) = @_;

    $ip =~ tr{ \r\n\t}{}d if defined $ip;

    if ( defined $version && $version eq 6 && Cpanel::Validate::IP::v4::is_valid_ipv4($ip) ) {
        my @ipv4 = map { $_ + 0 } split /\./, $ip;
        return "0000:0000:0000:0000:0000:ffff:" . sprintf( '%04x', ( $ipv4[0] << 8 ) + $ipv4[1] ) . ':' . sprintf( '%04x', ( $ipv4[2] << 8 ) + $ipv4[3] );
    }

    my $expanded = Cpanel::Validate::IP::Expand::expand_ip($ip);

    return $expanded if $expanded;

    if ( defined $version && $version eq 6 || $ip =~ m/:/ ) {
        return '0000:0000:0000:0000:0000:0000:0000:0000';
    }
    return '0.0.0.0';
}

sub ip2binary_string {
    my $ip = shift || '';

    if ( $ip =~ tr/:// ) {
        $ip = expand_ip( $ip, 6 );
        $ip =~ tr<:><>d;
        return unpack( 'B128', pack( 'H32', $ip ) );
    }

    return unpack( 'B32', pack( 'C4C4C4C4', split( /\./, $ip ) ) );
}

sub first_last_ip_in_range {
    my ($range) = @_;

    my ( $range_firstip, $mask ) = split( m{/}, $range );

    if ( !length $mask ) {
        die "Invalid input ($range) -- must be CIDR!";
    }

    my $mask_offset = 0;

    if ( $range_firstip !~ tr/:// ) {    # match as if it were an embedded ipv4 in ipv6
        $range_firstip = expand_ip( $range_firstip, 6 );
        $mask_offset   = ( 128 - 32 );                     # If we convert the range from ipv4 to ipv6 we need to move the mask
    }

    my $size = 128;

    my $range_firstip_binary_string = ip2binary_string($range_firstip);
    my $range_lastip_binary_string  = substr( $range_firstip_binary_string, 0, $mask + $mask_offset ) . '1' x ( $size - $mask - $mask_offset );

    return ( $range_firstip_binary_string, $range_lastip_binary_string );
}

1;

} # --- END Cpanel/IP/Expand.pm


{ # --- BEGIN Cpanel/Linux/Netlink.pm
package Cpanel::Linux::Netlink;



use strict;
use warnings;

use constant DEBUG => 0;

# use Cpanel::Exception      ();
# use Cpanel::Pack           ();
# use Cpanel::Pack::Template ();

my $NETLINK_READ_SIZE = 262144;    # Maximum size of netlink message

use constant PAGE_SIZE => 0x400;
use constant READ_SIZE => 8 * PAGE_SIZE;

our $PF_NETLINK = 16;
our $AF_INET    = 2;
our $AF_INET6   = 10;

our $NLMSG_NOOP    = 0x1;
our $NLMSG_ERROR   = 0x2;
our $NLMSG_DONE    = 0x3;
our $NLMSG_OVERRUN = 0x4;

our $NETLINK_INET_DIAG_26_KERNEL = 0;

our $NETLINK_INET_DIAG = 4;
our $NLM_F_REQUEST     = 1;
our $NLM_F_MULTI       = 2;        # /* Multipart message, terminated by NLMSG_DONE */
our $NLM_F_ROOT        = 0x100;
our $NLM_F_MATCH       = 0x200;    # in queries, return all matches
our $NLM_F_EXCL        = 0x200;    # in commands, don't alter if it exists
our $NLM_F_CREATE      = 0x400;    # in commands, create if it does not exist

our $NLM_F_ACK          = 4;
our $SOCK_DGRAM         = 2;
our $TCPDIAG_GETSOCK    = 18;
our $INET_DIAG_NOCOOKIE = 0xFFFFFFFF;

use constant {
    PACK_TEMPLATE_U16 => Cpanel::Pack::Template::PACK_TEMPLATE_U16,
    U16_BYTES_LENGTH  => Cpanel::Pack::Template::U16_BYTES_LENGTH,
    PACK_TEMPLATE_U32 => Cpanel::Pack::Template::PACK_TEMPLATE_U32,
    U32_BYTES_LENGTH  => Cpanel::Pack::Template::U32_BYTES_LENGTH,
};

my $NLMSG_HEADER_PACK_OBJ;
my $NLMSG_HEADER_PACK_OBJ_SIZE;

our @NLMSG_HEADER_TEMPLATE;

BEGIN {

    @NLMSG_HEADER_TEMPLATE = (

        'nlmsg_length' => PACK_TEMPLATE_U32(),    #__u32 nlmsg_len;    /* Length of message including header. */
        'nlmsg_type'   => PACK_TEMPLATE_U16(),    #__u16 nlmsg_type;   /* Type of message content. */
        'nlmsg_flags'  => PACK_TEMPLATE_U16(),    #__u16 nlmsg_flags;  /* Additional flags. */
        'nlmsg_seq'    => PACK_TEMPLATE_U32(),    #__u32 nlmsg_seq;    /* Sequence number. */
        'nlmsg_pid'    => PACK_TEMPLATE_U32(),    #__u32 nlmsg_pid;    /* Sender port ID. */

    );
}


my @NETLINK_XACTION_REQUIRED = (
    'message',          #hashref, to be sent via “send_pack_obj”
    'send_pack_obj',    #Cpanel::Pack instance
    'recv_pack_obj',    #Cpanel::Pack instance
    'sock',             #Perl socket
);

my %_u16_cache;
my %_u32_cache;

sub netlink_transaction {
    my (%OPTS) = @_;

    foreach (@NETLINK_XACTION_REQUIRED) {

        die "$_ is required for netlink_transaction" if !$OPTS{$_};
    }
    my ( $message_ref, $send_pack_obj, $recv_pack_obj, $sock, $parser, $payload_parser, $header_parms_ar ) = @OPTS{ @NETLINK_XACTION_REQUIRED, 'parser', 'payload_parser', 'header' };

    my $packed_nlmsg = _pack_nlmsg_with_header( $send_pack_obj, $message_ref, $header_parms_ar );

    if (DEBUG) {
        require Data::Dumper;
        print STDERR "[request]:" . Data::Dumper::Dumper($message_ref);
    }

    printf STDERR "Send %v02x\n", $packed_nlmsg if DEBUG;

    send( $sock, $packed_nlmsg, 0 ) or die "send: $!";

    my $message_hr;
    my $packed_response = '';

    my $header_pack_size = $NLMSG_HEADER_PACK_OBJ->sizeof();
    my $recv_pack_size   = $recv_pack_obj->sizeof();

    my $msgcount = 0;
    my ( $msg, $u32, $u16, $nlmsg_length, $nlmsg_type, $nlmsg_flags );
  READ_LOOP:
    while ( !_nlmsg_type_indicates_finished_reading($message_hr) ) {
        sysread( $sock, $packed_response, $NETLINK_READ_SIZE, length $packed_response ) or die "sysread: $!";

      PARSE_LOOP:
        while (1) {

            $msg          = substr( $packed_response, 0, $header_pack_size, q<> );
            $u32          = substr( $msg,             0, U32_BYTES_LENGTH,  '' );
            $nlmsg_length = $_u32_cache{$u32} //= unpack( PACK_TEMPLATE_U32, $u32 );
            $u16          = substr( $msg, 0, U16_BYTES_LENGTH, '' );
            $nlmsg_type   = $_u16_cache{$u16} //= unpack( PACK_TEMPLATE_U16, $u16 );
            $u16          = substr( $msg, 0, U16_BYTES_LENGTH );
            $nlmsg_flags  = $_u16_cache{$u16} //= unpack( PACK_TEMPLATE_U16, $u16 );

            last PARSE_LOOP if !$nlmsg_length || length $packed_response < $nlmsg_length - $NLMSG_HEADER_PACK_OBJ_SIZE;

            print STDERR "Received message, total size: [$nlmsg_length]\n" if DEBUG;

            if ( $nlmsg_type == $NLMSG_ERROR ) {
                require Data::Dumper;

                my ( $errno, $msg ) = unpack 'i a*', $packed_response;

                die Cpanel::Exception::create( 'Netlink', [ error => do { local $! = -$errno }, message => $msg ] );
            }

            if ( $recv_pack_size <= length $packed_response ) {

                my $main_msg = substr( $packed_response, 0, $recv_pack_size, '' );

                $message_hr = $recv_pack_obj->unpack_to_hashref($main_msg);

                if (DEBUG) {
                    require Data::Dumper;
                    printf STDERR "Received %v02x\n", $main_msg;
                    print STDERR "[response]:" . Data::Dumper::Dumper($message_hr);
                }

                my $payload = substr(
                    $packed_response,
                    0,
                    $nlmsg_length - $NLMSG_HEADER_PACK_OBJ_SIZE - $recv_pack_size,
                    q<>,
                );

                if ( $payload_parser && length $payload ) {
                    printf STDERR "payload: Received [%v02x]\n", $payload if DEBUG;
                    $payload_parser->( $msgcount, $message_hr, $payload );
                }
            }

            last READ_LOOP if _nlmsg_type_flags_indicates_finished_reading( $nlmsg_type, $nlmsg_flags );

            $msgcount++;
        }

    }

    $parser->( $msgcount, $message_hr ) if $parser && $nlmsg_type;

    return 1;
}


our @INET_DIAG_SOCKID_TEMPLATE = (
    'idiag_sport'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE16,    #__be16  idiag_sport;
    'idiag_dport'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE16,    #__be16  idiag_dport;
    'idiag_src_0'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_src[0];
    'idiag_src_1'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_src[1];
    'idiag_src_2'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_src[2];
    'idiag_src_3'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_src[3];
    'idiag_dst_0'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_dst[0];
    'idiag_dst_1'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_dst[1];
    'idiag_dst_2'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_dst[2];
    'idiag_dst_3'    => Cpanel::Pack::Template::PACK_TEMPLATE_BE32,    #__be32  idiag_dst[3];
    'idiag_if'       => Cpanel::Pack::Template::PACK_TEMPLATE_U32,     #__u32  idiag_if;
    'idiag_cookie_0' => Cpanel::Pack::Template::PACK_TEMPLATE_U32,     #__u32  idiag_cookie[0];
    'idiag_cookie_1' => Cpanel::Pack::Template::PACK_TEMPLATE_U32,     #__u32  idiag_cookie[1];
);

my $INET_DIAG_MSG_PACK_OBJ;
our @INET_DIAG_MSG_TEMPLATE = (
    'idiag_family'  => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_family;           /* Family of addresses. */
    'idiag_state'   => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_state;
    'idiag_timer'   => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_timer;
    'idiag_retrans' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_retrans;
    @INET_DIAG_SOCKID_TEMPLATE,                                        # inet_diag_sockid
    'idiag_expires' => Cpanel::Pack::Template::PACK_TEMPLATE_U32,      #__u32   idiag_expires;
    'idiag_rqueue'  => Cpanel::Pack::Template::PACK_TEMPLATE_U32,      #__u32   idiag_rqueue;
    'idiag_wqueue'  => Cpanel::Pack::Template::PACK_TEMPLATE_U32,      #__u32   idiag_wqueue;
    'idiag_uid'     => Cpanel::Pack::Template::PACK_TEMPLATE_U32,      #__u32   idiag_uid;
    'idiag_inode'   => Cpanel::Pack::Template::PACK_TEMPLATE_U32       #__u32   idiag_inode;
);

my $INET_DIAG_REQ_PACK_OBJ;
our @INET_DIAG_REQ_TEMPLATE = (
    'idiag_family'  => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_family;           /* Family of addresses. */
    'idiag_src_len' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_src_len;
    'idiag_dst_len' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_dst_len;
    'idiag_ext'     => Cpanel::Pack::Template::PACK_TEMPLATE_U8,       # __u8    idiag_ext;              /* Query extended information */
    @INET_DIAG_SOCKID_TEMPLATE,                                        #inet_diag_sockid
    'idiag_states' => Cpanel::Pack::Template::PACK_TEMPLATE_U32,       #__u32   idiag_states;           /* States to dump */
    'idiag_dbs'    => Cpanel::Pack::Template::PACK_TEMPLATE_U32        #__u32   idiag_dbs;           /* Tables to dump (NI) */
);

sub connection_lookup {
    my ( $source_address, $source_port, $dest_address, $dest_port ) = @_;

    die "A source port is required."      if !defined $source_port;
    die "A destination port is required." if !defined $dest_port;

    my ( $idiag_dst_0, $idiag_dst_1, $idiag_dst_2, $idiag_dst_3 );
    my ( $idiag_src_0, $idiag_src_1, $idiag_src_2, $idiag_src_3 );
    my ($idiag_family);

    if ( $dest_address =~ tr/:// ) {
        require Cpanel::IP::Expand;    # hide from exim but not perlcc - not eval quoted

        ( $idiag_dst_0, $idiag_dst_1, $idiag_dst_2, $idiag_dst_3 ) = unpack( 'N4', pack( 'n8', split /:/, Cpanel::IP::Expand::expand_ip($dest_address) ) );
        ( $idiag_src_0, $idiag_src_1, $idiag_src_2, $idiag_src_3 ) = unpack( 'N4', pack( 'n8', split /:/, Cpanel::IP::Expand::expand_ip($source_address) ) );
        $idiag_family = $AF_INET6;
    }
    else {
        my $u32_dest_address   = unpack( 'N', pack( 'C4', split( /\D/, $dest_address,   4 ) ) );
        my $u32_source_address = unpack( 'N', pack( 'C4', split( /\D/, $source_address, 4 ) ) );
        $idiag_src_0  = $u32_source_address;
        $idiag_dst_0  = $u32_dest_address;
        $idiag_family = $AF_INET;
    }

    my $sock;
    socket( $sock, $PF_NETLINK, $SOCK_DGRAM, $NETLINK_INET_DIAG ) or die "socket: $!";

    $INET_DIAG_REQ_PACK_OBJ ||= Cpanel::Pack->new( \@INET_DIAG_REQ_TEMPLATE );
    $INET_DIAG_MSG_PACK_OBJ ||= Cpanel::Pack->new( \@INET_DIAG_MSG_TEMPLATE );

    my %RESPONSE;
    netlink_transaction(
        'message' => {
            'idiag_family'   => $idiag_family,
            'idiag_dst_0'    => $idiag_dst_0,
            'idiag_dst_1'    => $idiag_dst_1,
            'idiag_dst_2'    => $idiag_dst_2,
            'idiag_dst_3'    => $idiag_dst_3,
            'idiag_dport'    => $dest_port,
            'idiag_src_0'    => $idiag_src_0,
            'idiag_src_1'    => $idiag_src_1,
            'idiag_src_2'    => $idiag_src_2,
            'idiag_src_3'    => $idiag_src_3,
            'idiag_sport'    => $source_port,
            'idiag_cookie_0' => $INET_DIAG_NOCOOKIE,
            'idiag_cookie_1' => $INET_DIAG_NOCOOKIE,
        },
        'sock'          => $sock,
        'send_pack_obj' => $INET_DIAG_REQ_PACK_OBJ,
        'recv_pack_obj' => $INET_DIAG_MSG_PACK_OBJ,
        'parser'        => sub {
            my ( undef, $response_ref ) = @_;
            %RESPONSE = %$response_ref if ( $response_ref && 'HASH' eq ref $response_ref );
        }
    );

    return \%RESPONSE;
}


my @NETLINK_SEND_HEADER = (
    'nlmsg_length' => undef,              #gets put in place
    'nlmsg_type'   => $TCPDIAG_GETSOCK,
    'nlmsg_flags'  => 0,                  #gets |=’d with $NLM_F_REQUEST
    'nlmsg_pid'    => undef,              #gets put in place
    'nlmsg_seq'    => 2,                  #default
);

sub _pack_nlmsg_with_header {
    my ( $send_pack_obj, $message_ref, $header_parms_ar ) = @_;

    my $nlmsg = $send_pack_obj->pack_from_hashref($message_ref);

    if ( !$NLMSG_HEADER_PACK_OBJ ) {
        $NLMSG_HEADER_PACK_OBJ      = Cpanel::Pack->new( \@NLMSG_HEADER_TEMPLATE );
        $NLMSG_HEADER_PACK_OBJ_SIZE = $NLMSG_HEADER_PACK_OBJ->sizeof();
    }

    my %header_data = (
        @NETLINK_SEND_HEADER,
        ( $header_parms_ar ? @$header_parms_ar : () ),
        nlmsg_length => $NLMSG_HEADER_PACK_OBJ_SIZE + length $nlmsg,
        nlmsg_pid    => $$,
    );

    $header_data{'nlmsg_flags'} |= $NLM_F_REQUEST;

    my $hdr_str = $NLMSG_HEADER_PACK_OBJ->pack_from_hashref( \%header_data );

    return $hdr_str . $nlmsg;
}

sub _nlmsg_type_indicates_finished_reading {
    return _nlmsg_type_flags_indicates_finished_reading( $_[0]->{'nlmsg_type'}, $_[0]->{'nlmsg_flags'} );
}

sub _nlmsg_type_flags_indicates_finished_reading {
    return 0 if !length $_[0];

    return ( $_[0] == $NLMSG_ERROR || ( $_[1] & $NLM_F_MULTI && $_[0] == $NLMSG_DONE ) || !( $_[1] & $NLM_F_MULTI ) ) ? 1 : 0;
}

sub expect_acknowledgment {
    my ( $my_sysread, $socket, $sequence ) = @_;

    my $NETLINK_HEADER = Cpanel::Pack->new( \@NLMSG_HEADER_TEMPLATE );

    my $response_buffer = '';
    my $header_hr;
    my $error_code;

    do {
        while ( length $response_buffer < $NETLINK_HEADER->sizeof() ) {
            $my_sysread->( $socket, \$response_buffer, READ_SIZE(), length $response_buffer ) or return "sysread, message header: $!";
        }
        $header_hr = $NETLINK_HEADER->unpack_to_hashref( substr( $response_buffer, 0, $NETLINK_HEADER->sizeof() ) );
        while ( length $response_buffer < $header_hr->{nlmsg_length} ) {
            $my_sysread->( $socket, \$response_buffer, READ_SIZE(), length $response_buffer ) or return "sysread, message body: $!";
        }

        my $message = substr( $response_buffer, 0, $header_hr->{nlmsg_length}, '' );
        $error_code = 0;
        if ( $header_hr->{nlmsg_type} == $NLMSG_ERROR ) {
            $error_code = unpack( Cpanel::Pack::Template::PACK_TEMPLATE_U32, substr( $message, $NETLINK_HEADER->sizeof(), Cpanel::Pack::Template::U32_BYTES_LENGTH ) );
        }
        if ( $header_hr->{nlmsg_seq} eq $sequence ) {
            if ( $header_hr->{nlmsg_type} == $NLMSG_ERROR && $error_code != 0 ) {
                local $! = -$error_code;
                return "Received error code when expecting acknowledgement: $!\n";
            }
            if ( $header_hr->{nlmsg_type} == $NLMSG_OVERRUN ) {
                return "Data lost due to message overrun";
            }
            if ( $header_hr->{nlmsg_type} == $NLMSG_DONE ) {
                return "Received multipart data when expecting ACK";
            }
        }
    } while ( $header_hr->{nlmsg_seq} ne $sequence || $header_hr->{nlmsg_type} != $NLMSG_ERROR || $error_code != 0 );
    return undef;
}

1;

} # --- END Cpanel/Linux/Netlink.pm


{ # --- BEGIN Cpanel/Linux/NetlinkConstants.pm
package Cpanel::Linux::NetlinkConstants;


use strict;
use warnings;

our $VERSION = '1.00';

# use Cpanel::Pack::Template ();

use constant IFA_ADDRESS   => 1;
use constant IFA_LOCAL     => 2;
use constant IFA_LABEL     => 3;
use constant IFA_CACHEINFO => 6;

use constant RT_SCOPE_UNIVERSE => 0;
use constant RT_SCOPE_SITE     => 200;
use constant RT_SCOPE_LINK     => 253;
use constant RT_SCOPE_HOST     => 254;
use constant RT_SCOPE_NOWHERE  => 255;

use constant RTM_GETLINK  => 18;
use constant RTM_GETADDR  => 22;
use constant RTM_GETROUTE => 26;

use constant RTA_DST     => 1;
use constant RTA_PREFSRC => 7;

our @IFINFOMSG_TEMPLATE = (    #struct ifinfomsg
    'ifi_family' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  unsigned char ifi_family;
    '__ifi_pad'  => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  unsigned char __ifi_pad;
    'ifi_type'   => Cpanel::Pack::Template::PACK_TEMPLATE_U16,    #  unsigned short  ifi_type;   /* ARPHRD_* */
    'ifi_index'  => Cpanel::Pack::Template::PACK_TEMPLATE_U32,    #  int   ifi_index;    /* Link index */
    'ifi_flags'  => Cpanel::Pack::Template::PACK_TEMPLATE_U32,    # unsigned  ifi_flags;    /* IFF_* flags  */
    'ifi_change' => Cpanel::Pack::Template::PACK_TEMPLATE_U32     # unsigned  ifi_change;   /* IFF_* change mask */
);

our @IFA_CACHEINFO_TEMPLATE = (                                   #struct ifa_cacheinfo
    'ifa_prefered' => Cpanel::Pack::Template::PACK_TEMPLATE_U32,    # __u32 ifa_prefered;  # See: https://en,wiktionary,org/wiki/prefered   -- It is mispelled upstream
    'ifa_valid'    => Cpanel::Pack::Template::PACK_TEMPLATE_U32,    # __u32 ifa_valid;
    'cstamp'       => Cpanel::Pack::Template::PACK_TEMPLATE_U32,    # __u32 cstamp; /* created timestamp, hundredths of seconds */
    'tstamp'       => Cpanel::Pack::Template::PACK_TEMPLATE_U32     # __u32 tstamp; /* updated timestamp, hundredths of seconds */
);

our @IFADDRMSG_TEMPLATE = (                                         # struct ifaddrmsg
    'ifa_family'    => Cpanel::Pack::Template::PACK_TEMPLATE_U8,    #  __u8    ifa_family;
    'ifa_prefixlen' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,    #  __u8    ifa_prefixlen;  /* The prefix length    */
    'ifa_flags'     => Cpanel::Pack::Template::PACK_TEMPLATE_U8,    #  __u8    ifa_flags;  /* Flags      */
    'ifa_scope'     => Cpanel::Pack::Template::PACK_TEMPLATE_U8,    #  __u8    ifa_scope;  /* Address scope    */
    'ifa_index'     => Cpanel::Pack::Template::PACK_TEMPLATE_U32    #  __u32   ifa_index;  /* Link index     */
);

our @RTMSG_TEMPLATE = (                                             # struct rtmsg
    'rtm_family'  => Cpanel::Pack::Template::PACK_TEMPLATE_U8,      #  __u8    rtm_family;
    'rtm_dst_len' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,      #  __u8    rtm_dst_len;
    'rtm_src_len' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,      #  __u8    rtm_src_len;
    'rtm_tos'     => Cpanel::Pack::Template::PACK_TEMPLATE_U8,      #  __u8    rtm_tos;

    'rtm_table'    => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  __u8    rtm_table;  /* Routing table id */
    'rtm_protocol' => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  __u8    rtm_protocol;  /* Routing protocol */
    'rtm_scope'    => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  __u8    rtm_scope;  /* Address scope    */
    'rtm_type'     => Cpanel::Pack::Template::PACK_TEMPLATE_U8,     #  __u8    rtm_type;

    'rtm_flags' => Cpanel::Pack::Template::PACK_TEMPLATE_U32        #  __u32   rtm_flags;  /* Flags     */
);

our @RTATTR_HEADER_TEMPLATE = (
    'rta_len'  => Cpanel::Pack::Template::PACK_TEMPLATE_U16,
    'rta_type' => Cpanel::Pack::Template::PACK_TEMPLATE_U16,
);
1;

} # --- END Cpanel/Linux/NetlinkConstants.pm


{ # --- BEGIN Cpanel/Linux/RtNetlink.pm
package Cpanel::Linux::RtNetlink;



use cPstrict;

# use Cpanel::Linux::Netlink          ();
# use Cpanel::Linux::NetlinkConstants ();
# use Cpanel::Pack                    ();
# use Cpanel::Pack::Template          ();
# use Cpanel::Socket::Constants       ();

# use Socket qw(inet_pton inet_ntop);
INIT { Socket->import(qw{inet_pton inet_ntop}); }

use constant {
    IFLA_IFNAME       => 4,
    DEBUG             => 0,
    AF_INET6          => $Cpanel::Linux::Netlink::AF_INET6,
    IFA_LOCAL         => Cpanel::Linux::NetlinkConstants::IFA_LOCAL(),
    IFA_ADDRESS       => Cpanel::Linux::NetlinkConstants::IFA_ADDRESS(),
    IFA_CACHEINFO     => Cpanel::Linux::NetlinkConstants::IFA_CACHEINFO(),
    IFA_LABEL         => Cpanel::Linux::NetlinkConstants::IFA_LABEL(),
    PACK_TEMPLATE_U16 => Cpanel::Pack::Template::PACK_TEMPLATE_U16,
    U16_BYTES_LENGTH  => Cpanel::Pack::Template::U16_BYTES_LENGTH,
    RTA_DST           => Cpanel::Linux::NetlinkConstants::RTA_DST(),
    RTA_PREFSRC       => Cpanel::Linux::NetlinkConstants::RTA_PREFSRC(),
};

my $INFINITY_LIFE_TIME = 4294967295;

my $NETLINK_ROUTE_SOCKET = 0;

my $PF_NETLINK = 16;

my $IFINFOMSG_PACK_OBJ;

my $IFA_CACHEINFO_PACK_OBJ;

my $IFADDRMSG_PACK_OBJ;

my $RTMSG_PACK_OBJ;


sub get_first_interface_and_address {
    my ($address_family) = @_;

    die "List context only!" if !wantarray;

    $address_family = _address_family_string_to_number($address_family);
    my $socket    = _make_netlink_socket();
    my $addresses = _get_interface_addresses( $socket, $address_family );

    my @fallback;
    foreach my $address ( sort { $a->{'scope'} <=> $b->{'scope'} } @{$addresses} ) {    # Prefer the largest global scope
        $address->{'ip'} ||= _unpack_address_to_ip( $address->{'address'} || '' );
        my @candidate = ( $address->{'ifindex'}, $address->{'ip'} );

        if ( defined $address->{label} && index( $address->{label}, ':' ) > 0 ) {    # do nothing if at position 0
            my ( $interface, $virtual ) = split( ':', $address->{label}, 2 );
            $candidate[0] .= ':' . $virtual;
        }

        @fallback = @candidate unless scalar @fallback;
        next if is_reserved_ipv4( $address->{'ip'} );

        return @candidate;
    }

    return @fallback;
}


sub is_reserved_ipv4 ($ip) {

    return unless defined $ip;

    return 1 if index( $ip, '127.' ) == 0    # 127.0.0.0/8
      || index( $ip, '10.' ) == 0            # 10.0.0.0/8
      || index( $ip, '11.' ) == 0            # 11.0.0.0/8
      || index( $ip, '192.168.' ) == 0       # 192.168.0.0/16
      ;

    if ( index( $ip, '172.' ) == 0 || index( $ip, '2' ) == 0 ) {
        if ( $ip =~ qr{^([0-9]+)\.([0-9]+)\.[0-9]+\.[0-9]+$} ) {
            return 1 if $1 == 172 && ( 16 <= $2 && $2 <= 31 );    # 172.16.0.0/12
            return 1 if $1 >= 224;                                # 224.0.0.0/4 & 240.0.0.0/4 & 255.255.255.255/32
        }
    }

    return;
}


sub is_reserved_ipv6 ($ip) {

    return unless defined $ip;

    return 1 if $ip eq '::1';
    $ip = lc $ip;
    return 1 if index( $ip, 'fe80:' ) == 0;

    return;
}


sub get_addresses_by_interface ($address_family) {

    $address_family = _address_family_string_to_number($address_family);
    my $socket     = _make_netlink_socket();
    my $addresses  = _get_interface_addresses( $socket, $address_family, { 'ip' => 1 } );
    my $interfaces = _get_interfaces( $socket, $address_family );

    my %ifcount;
    my %combined;
    foreach my $address ( @{$addresses} ) {
        next if $address->{'scope'} != Cpanel::Linux::NetlinkConstants::RT_SCOPE_UNIVERSE();    # only want global
        my $if = $interfaces->[ $address->{'ifindex'} - 1 ];
        $combined{$if}{ ++$ifcount{$if} } = $address;
    }
    return \%combined;
}


sub get_interfaces {
    my ($address_family) = @_;
    $address_family = _address_family_string_to_number($address_family);
    return _get_interfaces( _make_netlink_socket(), $address_family );
}


sub get_interface_addresses ($address_family) {
    $address_family = _address_family_string_to_number($address_family);
    return _get_interface_addresses( _make_netlink_socket(), $address_family, { 'ip' => 1 } );
}

sub _get_interfaces ( $sock, $address_family ) {

    my @interfaces;
    $IFINFOMSG_PACK_OBJ ||= Cpanel::Pack->new( \@Cpanel::Linux::NetlinkConstants::IFINFOMSG_TEMPLATE );
    Cpanel::Linux::Netlink::netlink_transaction(
        'header' => [
            'nlmsg_flags' => $Cpanel::Linux::Netlink::NLM_F_ROOT | $Cpanel::Linux::Netlink::NLM_F_MATCH,
            'nlmsg_type'  => Cpanel::Linux::NetlinkConstants::RTM_GETLINK(),
        ],
        'message' => {
            'ifi_family' => $address_family,
        },
        'sock'           => $sock,
        'send_pack_obj'  => $IFINFOMSG_PACK_OBJ,
        'recv_pack_obj'  => $IFINFOMSG_PACK_OBJ,
        'payload_parser' => _make_payload_parser(
            sub {
                my ( $nl_msgcount, $nl_response_hr, $rta_type, $value ) = @_;

                print STDERR "toto-[$nl_msgcount]\ntype:[$rta_type]==value:[$value]\n" if DEBUG;

                if ( $rta_type == Cpanel::Linux::NetlinkConstants::IFA_LABEL() ) {
                    $interfaces[ $nl_response_hr->{'ifi_index'} - 1 ] = $value =~ tr{\0}{}dr;
                }
                elsif (DEBUG) {
                    warn "Unknown rta_type: [$rta_type]";
                }
            },
        ),
    );

    return \@interfaces;
}


sub get_route_to ( $address_family, $dst_ip ) {
    $address_family = _address_family_string_to_number($address_family);
    $dst_ip         = Socket::inet_pton $address_family, $dst_ip;
    return _get_route_to( _make_netlink_socket(), $address_family, $dst_ip );
}

my @RTATTR_DATA = (
    undef,
    {
        'name'    => 'rta_dst',
        'handler' => \&_rtattr_address_handler,
    },
    undef,
    undef,
    undef,
    undef,
    undef,
    {
        'name'    => 'rta_prefsrc',
        'handler' => \&_rtattr_address_handler,
    },
);

sub _rtattr_address_handler ( $value, $address_family ) {

    return Socket::inet_ntop( $address_family, $value );
}

sub _get_route_to ( $sock, $address_family, $dst_ip_packed ) {    ## no critic qw(ProhibitManyArgs)

    my ( $address_length, @attributes );

    $address_length = ( $address_family == AF_INET6 ) ? 16 : 4;

    $RTMSG_PACK_OBJ ||= Cpanel::Pack->new( \@Cpanel::Linux::NetlinkConstants::RTMSG_TEMPLATE );

    my $RTMSG_WITH_DST_PACK_OBJ = Cpanel::Pack->new(
        [
            @Cpanel::Linux::NetlinkConstants::RTMSG_TEMPLATE,
            @Cpanel::Linux::NetlinkConstants::RTATTR_HEADER_TEMPLATE,
            'rta_dst' => 'a' . $address_length,
        ]
    );
    Cpanel::Linux::Netlink::netlink_transaction(
        'header' => [
            'nlmsg_type' => Cpanel::Linux::NetlinkConstants::RTM_GETROUTE(),
            'nlmsg_seq'  => 1,                                                 #seems unnecessary??
        ],
        'message' => {
            'rtm_family'  => $address_family,
            'rtm_dst_len' => $address_length * 8,                              # /32 for v4, /128 for v6
            'rta_len'     => 4 + $address_length,                              # includes rtattr header size (4 bytes)
            'rta_type'    => RTA_DST,
            'rta_dst'     => $dst_ip_packed,
        },
        'sock'           => $sock,
        'send_pack_obj'  => $RTMSG_WITH_DST_PACK_OBJ,
        'recv_pack_obj'  => $RTMSG_PACK_OBJ,
        'payload_parser' => _make_payload_parser(
            sub {
                my ( $msgcount, $response_ref, $rta_type, $value ) = @_;

                $attributes[$msgcount] = {} unless defined $attributes[$msgcount];

                if ( defined $RTATTR_DATA[$rta_type] ) {
                    my $rtattr_hr = $RTATTR_DATA[$rta_type];
                    $attributes[$msgcount]->{ $rtattr_hr->{'name'} } = $rtattr_hr->{'handler'}->( $value, $address_family );
                }
                else {
                    $attributes[$msgcount]->{$rta_type} = $value;
                }
            },
        ),
    );

    return \@attributes;
}

my %_u16_cache;

sub _make_payload_parser ($for_each_rtmsg_cr) {

    return sub {
        my ( $nl_msgcount, $nlresponse_hr, $payload_sr ) = ( $_[0], $_[1], \$_[2] );
        my ( $u16, $rta_length, $rta_type, $value );
      RTATTR_LOOP:
        while ( length $$payload_sr ) {

            $u16        = substr( $$payload_sr, 0, U16_BYTES_LENGTH, '' );
            $rta_length = ( $_u16_cache{$u16} //= unpack( PACK_TEMPLATE_U16, $u16 ) ) or last RTATTR_LOOP;    # unsigned short  rta_len;
            $u16        = substr( $$payload_sr, 0, U16_BYTES_LENGTH, '' );
            $rta_type   = ( $_u16_cache{$u16} //= unpack( PACK_TEMPLATE_U16, $u16 ) );
            $value      = substr( $$payload_sr, 0, $rta_length - ( U16_BYTES_LENGTH * 2 ), '' );

            $for_each_rtmsg_cr->(
                $nl_msgcount,
                $nlresponse_hr,
                $rta_type,
                $value
            );
        }
    };
}

sub _get_interface_addresses ( $sock, $address_family, $want = undef ) {
    $want //= {};

    my $want_ip = $want->{'ip'};

    my @addresses;
    $IFADDRMSG_PACK_OBJ     ||= Cpanel::Pack->new( \@Cpanel::Linux::NetlinkConstants::IFADDRMSG_TEMPLATE );
    $IFA_CACHEINFO_PACK_OBJ ||= Cpanel::Pack->new( \@Cpanel::Linux::NetlinkConstants::IFA_CACHEINFO_TEMPLATE );
    Cpanel::Linux::Netlink::netlink_transaction(
        'header' => [
            'nlmsg_type'  => Cpanel::Linux::NetlinkConstants::RTM_GETADDR(),
            'nlmsg_flags' => $Cpanel::Linux::Netlink::NLM_F_ROOT,
            'nlmsg_seq'   => 1,                                                #seems unnecessary??
        ],
        'message' => {
            'ifa_family' => $address_family,
        },
        'sock'           => $sock,
        'send_pack_obj'  => $IFADDRMSG_PACK_OBJ,
        'recv_pack_obj'  => $IFADDRMSG_PACK_OBJ,
        'payload_parser' => _make_payload_parser(
            sub {
                my ( $msgcount, $response_ref, $rta_type, $value ) = @_;

                print STDERR "haha-[$msgcount]\n[$rta_type]==[$value]\n" if DEBUG;
                if ( $rta_type == IFA_LOCAL || ( $rta_type == IFA_ADDRESS && !$addresses[$msgcount]->{'ip'} ) ) {
                    @{ $addresses[$msgcount] }{ 'scope', 'ifindex', 'prefix' } = @{$response_ref}{ 'ifa_scope', 'ifa_index', 'ifa_prefixlen' };
                    if ($want_ip) {
                        $addresses[$msgcount]->{'ip'} = ( $address_family == AF_INET6 ) ? join( ":", unpack( "H4H4H4H4H4H4H4H4", $value ) ) : join( '.', unpack( 'C4', $value ) );
                    }
                    else {
                        $addresses[$msgcount]->{'address'} = $value;
                    }
                    print STDERR "[address][$addresses[$msgcount]->{'ip'}]\n" if DEBUG;
                }
                elsif ( $rta_type == IFA_CACHEINFO ) {
                    $addresses[$msgcount]->{'cacheinfo'} = $IFA_CACHEINFO_PACK_OBJ->unpack_to_hashref($value);
                    if ( $addresses[$msgcount]->{'cacheinfo'}{'ifa_valid'} == $INFINITY_LIFE_TIME ) {
                        $addresses[$msgcount]->{'type'} = 0;
                    }
                    else {
                        $addresses[$msgcount]->{'temporary'} = 1;
                    }
                }
                elsif ( $rta_type == IFA_LABEL ) {
                    $addresses[$msgcount]->{'label'} = $value =~ tr{\0}{}dr;
                }
                elsif (DEBUG) {
                    warn "Unknown rta_type: [$rta_type]";
                }
            },
        ),
    );

    return \@addresses;
}

sub _make_netlink_socket() {
    my $sock;
    socket( $sock, $Cpanel::Linux::Netlink::PF_NETLINK, $Cpanel::Linux::Netlink::SOCK_DGRAM, $NETLINK_ROUTE_SOCKET ) or die "socket: $!";
    return $sock;
}

my @ALLOWED_FAMILIES = qw(
  AF_INET
  AF_INET6
);

sub _address_family_string_to_number ($addr_fam) {

    if ( !grep { $_ eq $addr_fam } @ALLOWED_FAMILIES ) {
        die "“$addr_fam” is not a recognized address family; must be one of: @ALLOWED_FAMILIES";
    }

    return ${ *{ $Cpanel::Socket::Constants::{$addr_fam} }{'SCALAR'} };
}

sub _unpack_address_to_ip ($ip) {
    return length $ip > 10 ? join( ":", unpack( "H4H4H4H4H4H4H4H4", $ip ) ) : join( '.', unpack( 'C4', $ip ) );
}
1;

} # --- END Cpanel/Linux/RtNetlink.pm


{ # --- BEGIN Cpanel/IP/Configured.pm
package Cpanel::IP::Configured;


use strict;
use warnings;

# use Cpanel::Exception                    ();
# use Cpanel::CachedCommand::Utils         ();
# use Cpanel::FileUtils::TouchFile         ();
# use Cpanel::JSON::FailOK                 ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::PwCache                      ();
use Try::Tiny;

our $VERSION = '1.7';

my $PRODUCT_CONF_DIR = '/var/cpanel';
my $SYSTEM_CONF_DIR  = '/etc';
my $SYSTEM_SBIN_DIR  = '/sbin';
my $DB_FILE          = 'all_iplist.db';

my $configuredips;

sub clear_configured_ips_cache {
    Cpanel::FileUtils::TouchFile::touchfile("$SYSTEM_CONF_DIR/ips");    # Reset mtime
    Cpanel::CachedCommand::Utils::destroy( 'name' => $DB_FILE );
    $configuredips = undef;
    return 1;
}

sub getconfiguredips {
    if ($configuredips) {
        return wantarray ? @$configuredips : $configuredips;
    }

    my $iplist_cachefile = Cpanel::CachedCommand::Utils::get_datastore_filename($DB_FILE);
    my $now              = time();
    my $iplist_cache_age = $now - ( ( stat $iplist_cachefile )[9] || 0 );

    my $use_cache = 1;
    if ( $iplist_cache_age < 0 || $iplist_cache_age > 300 ) {
        $use_cache = 0;
    }
    else {
        my $ips_age         = $now - ( ( stat "$SYSTEM_CONF_DIR/ips" )[9]          || 0 );
        my $wwwacctconf_age = $now - ( ( stat "$SYSTEM_CONF_DIR/wwwacct.conf" )[9] || 0 );

        if ( $iplist_cache_age > $ips_age || $iplist_cache_age > $wwwacctconf_age ) {
            $use_cache = 0;
        }
    }

    if ($use_cache) {
        $configuredips = Cpanel::JSON::FailOK::LoadFile($iplist_cachefile);
    }

    if ( !$configuredips || !@$configuredips ) {
        require Cpanel::Linux::RtNetlink;
        require Cpanel::IP::Loopback;
        my $ips = Cpanel::Linux::RtNetlink::get_interface_addresses('AF_INET');
        @$configuredips = map { $_->{'ip'} } grep { !Cpanel::IP::Loopback::is_loopback( $_->{'ip'} ) } @$ips;

        if ( Cpanel::PwCache::getusername() ne 'nobody' ) {
            try {
                Cpanel::FileUtils::Write::JSON::Lazy::write_file( $iplist_cachefile, $configuredips, 0644 );
            }
            catch {
                _logger()->warn( Cpanel::Exception::get_string($_) );
            };

        }
    }

    $configuredips = [] unless ( defined $configuredips );

    return wantarray ? @$configuredips : $configuredips;
}

sub clearcache {
    $configuredips = undef;
    return 1;
}

sub default_product_dir {
    $PRODUCT_CONF_DIR = shift if @_;
    return $PRODUCT_CONF_DIR;
}

sub default_conf_dir {
    $SYSTEM_CONF_DIR = shift if @_;
    return $SYSTEM_CONF_DIR;
}

sub default_sbin_dir {
    $SYSTEM_SBIN_DIR = shift if @_;
    return $SYSTEM_SBIN_DIR;
}

my $logger;

sub _logger {
    return $logger if $logger;
    require Cpanel::Logger;
    return ( $logger = Cpanel::Logger->new() );
}

1;

} # --- END Cpanel/IP/Configured.pm


{ # --- BEGIN Cpanel/IP/Bound.pm
package Cpanel::IP::Bound;


use strict;
use warnings;

# use Cpanel::Socket::Constants       ();
# use Cpanel::Validate::IP::v4        ();
# use Cpanel::IP::NonlocalBind::Cache ();
# use Cpanel::SV                      ();


use constant {
    _EADDRNOTAVAIL => 99,
    _EADDRINUSE    => 98
};

sub ipv4_is_bound {
    my ($addr) = @_;
    my $fd;

    return 0 unless Cpanel::Validate::IP::v4::is_valid_ipv4($addr);

    if ( index( $addr, '.' ) == 3 ) {
        if ( ( substr( $addr, 0, 3 ) >= 224 ) && ( substr( $addr, 0, 3 ) < 240 ) ) {
            die "Multicast address ($addr) cannot be tested via this interface!";
        }
    }

    my $ipv4_ip_nonlocal_bind_is_enabled = Cpanel::IP::NonlocalBind::Cache::ipv4_ip_nonlocal_bind_is_enabled();
    if ( !defined $ipv4_ip_nonlocal_bind_is_enabled || $ipv4_ip_nonlocal_bind_is_enabled ) {
        return _slow_ipv4_is_bound_via_configured_ips($addr);
    }

    local $!;
    socket( $fd, $Cpanel::Socket::Constants::PF_INET, $Cpanel::Socket::Constants::SOCK_STREAM, $Cpanel::Socket::Constants::IPPROTO_TCP ) or die "socket(PF_INET, SOCK_STREAM, IPPROTO_TCP): $!";

    Cpanel::SV::untaint($addr);

    bind( $fd, pack( 'SnC4x8', $Cpanel::Socket::Constants::AF_INET, 0, split( m{\.}, $addr ) ) ) or do {

        return 1 if $! == _EADDRINUSE();

        die "bind($addr): $!" if $! != _EADDRNOTAVAIL();

        return 0;
    };

    return 1;
}

sub _slow_ipv4_is_bound_via_configured_ips {
    my ($addr) = @_;
    require Cpanel::IP::Configured;
    my $configured_ips_ar = Cpanel::IP::Configured::getconfiguredips();
    foreach my $check_ip (@$configured_ips_ar) {
        return 1 if $check_ip eq $addr;
    }
    return 0;

}

1;

} # --- END Cpanel/IP/Bound.pm


{ # --- BEGIN Cpanel/NAT/Object.pm
package Cpanel::NAT::Object;


use strict;
use warnings;

# use Cpanel::Debug            ();
# use Cpanel::Validate::IP::v4 ();

our $NAT_FILE = '/var/cpanel/cpnat';

sub new {
    my ( $class, $file ) = @_;

    my $self = {
        'cpnat_file'    => $file || $NAT_FILE,
        'cpnat_data'    => {},
        'file_read'     => 0,
        'only_local_ip' => [],
        'dups'          => {},
    };

    bless $self, $class;
    $self->load_file();

    return $self;
}

sub load_file {
    my ($self) = @_;

    $self->{'file_read'}  = 0;
    $self->{'cpnat_data'} = {};

    if ( !-e $self->{'cpnat_file'} || !-r _ || -z _ ) {
        return;
    }

    my $nat_data;
    {
        local $/;
        open my $fh, '<', $self->{'cpnat_file'} or die "Failed to open “$self->{'cpnat_file'}”: $!";

        $nat_data = <$fh>;
        close $fh;
    }

    $self->{'nat_data'}   = $nat_data;
    $self->{'cpnat_data'} = $self->_parse_nat_file($nat_data);
    $self->{'file_read'}  = 1;
    return 1 if %{ $self->{'cpnat_data'} };

    return;
}

sub enabled {
    my ($self) = @_;
    return $self->{'file_read'} ? 1 : 0;
}

sub ordered_list {
    my ($self) = @_;
    return ( $self->{'cpnat_ordered'} ||= $self->_create_ordered_list( $self->{'nat_data'} ) );
}

sub get_public_ip {
    return $_[1] if !$_[1] || !$_[0]->{'file_read'} || !$_[0]->{'cpnat_data'}->{ $_[1] };
    return $_[0]->_get_public_ip( $_[1] );
}

sub get_all_public_ips {
    my ($self) = @_;
    return [ sort values %{ $self->{cpnat_data} } ];
}

sub get_public_ip_raw {
    my ( $self, $local_ip ) = @_;

    return 'FILE NOT READ'    if !$self->{'file_read'};
    return 'INVALID LOCAL IP' if !$self->{'cpnat_data'}->{$local_ip} && !$self->_find_ip($local_ip) && !exists $self->{'dups'}->{$local_ip};

    return $self->_get_public_ip($local_ip) || $self->{'dups'}->{$local_ip} || '';
}

sub _find_ip {
    my ( $self, $ip ) = @_;

    my $found = grep { $_ eq $ip } @{ $self->{'only_local_ip'} };
    return $ip if $found;
    return;
}

sub _get_public_ip {
    my ( $self, $local_ip ) = @_;
    my $public_ip = $self->{'cpnat_data'}->{$local_ip};
    return $public_ip;
}

sub get_local_ip {
    my ( $self, $public_ip ) = @_;

    return $public_ip unless $public_ip;
    return $public_ip if !$self->{'file_read'};

    $self->{'_public_to_local'} ||= { reverse %{ $self->{'cpnat_data'} } };

    return $self->{'_public_to_local'}{$public_ip} || $public_ip;
}

sub _parse_nat_file {
    my ( $self, $nat_data ) = @_;

    return if !$nat_data;

    my $cpnat_hash    = {};
    my @file          = split /\n/, $nat_data;
    my $only_local_ip = $self->{'only_local_ip'};
    foreach my $line (@file) {
        my ( $local, $public ) = split /\s+/, $line;
        if ( !$public ) {
            push @$only_local_ip, $local;
            next;
        }
        if (   !Cpanel::Validate::IP::v4::is_valid_ipv4($local)
            && !Cpanel::Validate::IP::v4::is_valid_ipv4($public) ) {

            Cpanel::Debug::log_warn( 'Invalid line in cpnat file: ' . $line );
            next;
        }
        if ( !grep { $public && $public eq $_ } values %{$cpnat_hash} ) {
            $cpnat_hash->{$local} = $public;
        }
        else {
            $self->{'dups'}->{$local} = $public;
        }
    }

    return $cpnat_hash;
}

sub _create_ordered_list {
    my ( $self, $nat_data ) = @_;

    return if !$nat_data;

    my $cpnat_array = [];
    my $group_hash  = {};
    my $order       = [];
    my @file        = split /\n/, $nat_data;
    foreach my $line (@file) {
        my ( $local, $public ) = split /\s+/, $line;
        my $key = $public || $local;

        $public ||= '';

        push @$order,                  $key if !$group_hash->{$key};
        push @{ $group_hash->{$key} }, [ $local, $public ];
    }

    foreach my $key (@$order) {
        if ( scalar @{ $group_hash->{$key} } == 1 ) {
            push @$cpnat_array, pop @{ $group_hash->{$key} };
        }
        else {
            push @$cpnat_array, $group_hash->{$key};
        }
    }

    return $cpnat_array;
}

1;

} # --- END Cpanel/NAT/Object.pm


{ # --- BEGIN Cpanel/NAT.pm
package Cpanel::NAT;


use strict;

# use Cpanel::NAT::Object ();

my $nat;

sub set_cpnat {
    $nat = shift;
    return;
}

sub cpnat {
    return $nat ||= Cpanel::NAT::Object->new();
}

sub reload {
    return cpnat()->load_file();
}

sub get_public_ip {
    return ( $nat ||= cpnat() )->get_public_ip( $_[0] );
}

sub get_local_ip {
    return ( $nat ||= cpnat() )->get_local_ip( $_[0] );
}

sub get_public_ip_raw {
    return ( $nat ||= cpnat() )->get_public_ip_raw( $_[0] );
}

sub ordered_list {
    return cpnat()->ordered_list();
}

sub get_all_public_ips {
    return cpnat()->get_all_public_ips();
}

sub is_nat {
    return cpnat()->enabled();
}

1;

} # --- END Cpanel/NAT.pm


{ # --- BEGIN Cpanel/DIp/MainIP.pm
package Cpanel::DIp::MainIP;


use strict;
use warnings;

# use Cpanel::Config::LoadWwwAcctConf ();
# use Cpanel::GlobalCache             ();
# use Cpanel::IP::Bound               ();
# use Cpanel::LoadFile                ();
# use Cpanel::NAT                     ();
# use Cpanel::Debug                   ();
# use Cpanel::Validate::IP::v4        ();

our $VERSION = '1.5';

my $PRODUCT_CONF_DIR = '/var/cpanel';
my $SYSTEM_CONF_DIR  = '/etc';
my $SYSTEM_SBIN_DIR  = '/sbin';

my $cachedmainip   = q{};
my $cachedserverip = q{};

*getmainip = *getmainsharedip;

sub getmainsharedip {
    return $cachedmainip if ( $cachedmainip ne '' );

    my $wwwaccthash_ref = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
    my $addr            = q{};

    if ( exists $wwwaccthash_ref->{'ADDR'} ) {
        if ( !length $wwwaccthash_ref->{'ADDR'} ) {
            return ( $cachedmainip = getmainserverip() );
        }
        elsif ( !Cpanel::Validate::IP::v4::is_valid_ipv4( $wwwaccthash_ref->{'ADDR'} ) && -x "$SYSTEM_SBIN_DIR/ip" ) {
            return ( $cachedmainip = getmainserverip() );
        }
        elsif ( !-x "$SYSTEM_SBIN_DIR/ip" ) {
            return ( $cachedmainip = $wwwaccthash_ref->{'ADDR'} );
        }
        $addr = $wwwaccthash_ref->{'ADDR'};
    }

    if ( !-x "$SYSTEM_SBIN_DIR/ip" ) {
        Cpanel::Debug::log_warn("Working ip binary required to determine IP address. Please check the permissions of $SYSTEM_SBIN_DIR/ip");
        return;
    }

    return ( $cachedmainip = $addr ) if Cpanel::IP::Bound::ipv4_is_bound($addr);

    my $mainserverip = getmainserverip();

    $cachedmainip = $mainserverip;

    return $mainserverip;
}

sub getmainserverip {
    return $cachedserverip if length $cachedserverip;

    my $oldmainip = Cpanel::LoadFile::loadfile("$PRODUCT_CONF_DIR/mainip");
    $oldmainip =~ tr{ \t\r\n}{}d if length $oldmainip;

    if ( Cpanel::Validate::IP::v4::is_valid_ipv4($oldmainip) ) {
        $cachedserverip = $oldmainip;
        return $oldmainip;
    }

    my $wwwaccthash_ref = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();

    my $addr   = $wwwaccthash_ref->{'ADDR'}   // q{};
    my $ethdev = $wwwaccthash_ref->{'ETHDEV'} // q{};

    if ( !-x "$SYSTEM_SBIN_DIR/ip" ) {
        return $addr if length $addr;
        Cpanel::Debug::log_die("Fatal error: $SYSTEM_SBIN_DIR/ip is not executable, determining main server IP impossible");
    }

    my $wwwacct_conf_mtime = ( stat($Cpanel::Config::LoadWwwAcctConf::wwwacctconf) )[9];
    my $ipconfig_mtime     = 43200;                                                        #12 hours
    if ( !$wwwacct_conf_mtime ) {

        $ipconfig_mtime = 1;
    }
    else {
        my $sec_since_wwwacct_conf_modified = ( time() - $wwwacct_conf_mtime );
        if ( $sec_since_wwwacct_conf_modified < $ipconfig_mtime ) {

            $ipconfig_mtime = $sec_since_wwwacct_conf_modified - 60;
        }
    }
    my $thisip = _get_first_valid_ip( [ split( /\n/, Cpanel::GlobalCache::cachedmcommand( 'cpanel', $ipconfig_mtime, "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show', $ethdev eq '' ? () : $ethdev ) ) ] );

    return ( $cachedserverip = $thisip ) if $thisip;

    my $ips;
    my $retry_ok = 0;
    if ( !length $ethdev ) {
        require Cpanel::CachedCommand;
        $ips = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show' );
    }
    else {
        $retry_ok = 1;
        require Cpanel::CachedCommand;
        $ips = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show', $ethdev );
    }
    $thisip = _get_first_valid_ip( [ split( /\n/, $ips ) ] );
    return ( $cachedserverip = $thisip ) if $thisip;

    if ($retry_ok) {
        require Cpanel::CachedCommand;
        $ips    = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show' );
        $thisip = _get_first_valid_ip( [ split( /\n/, $ips ) ] );
        return ( $cachedserverip = $thisip ) if $thisip;
    }

    if ( $ethdev ne '' ) {
        Cpanel::Debug::log_warn("No IP address found on $ethdev, make sure device is correctly configured, returning 0.0.0.0");
    }
    else {
        Cpanel::Debug::log_warn("No IP address found, returning 0.0.0.0");
    }
    return '0.0.0.0';
}

sub getpublicmainserverip {
    return Cpanel::NAT::get_public_ip( getmainserverip() );
}

sub clearcache {
    $cachedmainip   = '';
    $cachedserverip = '';

    if ( $INC{'Cpanel/DIp.pm'} ) {
        Cpanel::DIp::clearcache();
    }
    return;
}

sub default_product_dir {
    $PRODUCT_CONF_DIR = shift if @_;
    return $PRODUCT_CONF_DIR;
}

sub default_conf_dir {
    $SYSTEM_CONF_DIR = shift if @_;
    return $SYSTEM_CONF_DIR;
}

sub default_sbin_dir {
    $SYSTEM_SBIN_DIR = shift if @_;
    return $SYSTEM_SBIN_DIR;
}

sub _get_first_valid_ip {

    my ($ips_ref) = @_;

    require Cpanel::Regex;
    require Cpanel::IP::Loopback;

    foreach my $ip (@$ips_ref) {
        if ( $ip =~ m{ [\s\:] ($Cpanel::Regex::regex{'ipv4'}) }xoms ) {
            my $thisip = $1;
            if ( !Cpanel::IP::Loopback::is_loopback($thisip) ) {
                return $thisip;
            }
        }
    }
    return undef;
}

1;

} # --- END Cpanel/DIp/MainIP.pm


{ # --- BEGIN Cpanel/Update/Blocker/CpanelConfig.pm
package Cpanel::Update::Blocker::CpanelConfig;


use strict;
use warnings;

# use Cpanel::Update::Logger      ();
# use Cpanel::Config::CpConfGuard ();

sub new {
    my ( $class, $args ) = @_;

    my $self = $class->init($args);
    return bless $self, $class;
}

sub init {
    my ( $class, $args ) = @_;

    my $logger = $args->{'logger'} || Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );

    return {
        'invalid' => 0,
        'logger'  => $logger,
        'guard'   => Cpanel::Config::CpConfGuard->new(),
    };
}

sub cpconfig {
    my $self = shift;
    return $self->{'guard'}->{'data'};
}

sub get_local_nameserver_type {
    my $self = shift;
    return $self->cpconfig()->{'local_nameserver_type'} || '';
}

sub is_local_nameserver_type_valid {
    my $self            = shift;
    my $nameserver_type = $self->get_local_nameserver_type();

    return 1 if ( $nameserver_type eq '' && $ENV{'CPANEL_BASE_INSTALL'} );

    return 1 if !$nameserver_type;
    return 1 if ( $nameserver_type =~ /^(?:powerdns|mydns|nsd|bind|disabled)$/ );

    $self->{'invalid'}++;
    return 0;
}

sub is_mailserver_valid {
    my $self       = shift;
    my $mailserver = $self->cpconfig()->{'mailserver'} || '';

    return 1 if ( $mailserver eq '' && $ENV{'CPANEL_BASE_INSTALL'} );

    return 1 if ( $mailserver =~ /^(?:dovecot|disabled)$/ );

    $self->{'invalid'}++;
    return 0;
}

sub is_ftpserver_valid {
    my $self      = shift;
    my $ftpserver = $self->cpconfig()->{'ftpserver'} || '';

    return 1 if ( $ftpserver eq '' && $ENV{'CPANEL_BASE_INSTALL'} );

    return 1 if ( $ftpserver =~ /^(?:pure-ftpd|proftpd|disabled)$/ );

    $self->{'invalid'}++;
    return 0;
}

sub cleanse_cpanel_config_entries {
    my $self = shift;
    my $conf = $self->cpconfig();

    my $needs_save;

    for my $key (qw/ftpserver local_nameserver_type mailserver mysql-version/) {
        my $value = $conf->{$key} || '';

        my $changed = $value =~ s/^\s+//;
        $changed += $value =~ s/\s+$//;
        next unless $changed;

        $self->{'logger'}->warning("Correcting white space found in cpanel.config setting: $key");
        $needs_save++;
        $conf->{$key} = $value;
    }
    if ( not $needs_save ) {
        $self->{'guard'}->release_lock();    # save() releases the lock automatically (cause keep_lock isn't in effect),
        return;
    }

    $self->{'logger'}->warning("Saving cpanel.config with removed white space");
    $self->{'guard'}->save();

    return 1;
}

sub is_legacy_cpconfig_invalid {
    my $self = shift;

    return $self->{'invalid'};
}

1;

} # --- END Cpanel/Update/Blocker/CpanelConfig.pm


{ # --- BEGIN Cpanel/Update/Blocker/Constants/MySQL.pm
package Cpanel::Update::Blocker::Constants::MySQL;


use strict;
use warnings;


use constant BLOCKED_MYSQL_RELEASES => ( '3.23', '4.0', '4.1', '5.0', '5.1' );

use constant SUPPORTED_MYSQL_RELEASES => ( '5.5', '5.6', '5.7', '8.0' );
use constant SUPPORTED_MARIADB_RELEASES => ( '10.0', '10.1', '10.2', '10.3', '10.5', '10.6' );

use constant {
    MYSQL_MIN_DBI_SERVERVERSION   => 50500,
    MYSQL_MAX_DBI_SERVERVERSION   => 90000,
    MARIADB_MIN_DBI_SERVERVERSION => 100000,
    MARIADB_MAX_DBI_SERVERVERSION => 100700
};

use constant MYSQL_RELEASE_APPROACHING_EOL   => '5.6';
use constant MARIADB_RELEASE_APPROACHING_EOL => '10.1';


sub MINIMUM_RECOMMENDED_MYSQL_RELEASE {
    return (SUPPORTED_MYSQL_RELEASES)[0];
}

1;

} # --- END Cpanel/Update/Blocker/Constants/MySQL.pm


{ # --- BEGIN Cpanel/MysqlUtils/Version.pm
package Cpanel::MysqlUtils::Version;


use cPstrict;

use Try::Tiny;


# use Cpanel::Exception                ();
# use Cpanel::LoadFile                 ();
# use Cpanel::LoadModule               ();
# use Cpanel::MysqlUtils::MyCnf::Basic ();
# use Cpanel::MariaDB                  ();

our $cached_mysql_version;

our $MINIMUM_RECOMMENDED_MYSQL_RELEASE            = 5.7;
our $MINIMUM_RECOMMENDED_MARIADB_RELEASE          = 10.2;
our $DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED = $MINIMUM_RECOMMENDED_MYSQL_RELEASE;    # assume MySQL 5.7 is the default value
our $USE_LOCAL_MYSQL                              = 0;

our $_VERSION_CACHE_PATH = '/var/cpanel/mysql_server_version_cache';

my $VERSION_CACHE_TTL = 4 * 60 * 60;                                                       #4 hours


sub cmp_versions ( $a, $b ) {
    for my $orig ( $a, $b ) {
        my $copy = $orig;
        for ($copy) {
            s<-.*><>;    #strip suffixes
            if ( !length || tr<0-9.><>c || m<\.\.> || m<\A\.> || m<\.\z> ) {
                die "Invalid MySQL version: “$orig”";
            }
        }

        $orig = $copy;
    }

    my ( $a_ar, $b_ar ) = map { [ split m<[.-]> ] } ( $a, $b );
    die "Uneven version numbers: $a, $b" if @$a_ar != @$b_ar;

    push @$_, (0) x 4 for ( $a_ar, $b_ar );

    ( $a, $b ) = map { join( '.', @{$_}[ 0 .. 3 ] ) } $a_ar, $b_ar;    ## no critic qw(Variables::RequireLocalizedPunctuationVar)

    Cpanel::LoadModule::load_perl_module('Cpanel::Version::Compare');
    return Cpanel::Version::Compare::cmp_versions( $a, $b );
}

sub is_at_least ( $testee, $minimum ) {
    for ( $testee, $minimum ) {
        $_ = _expand_mysql_version($_);
    }

    return ( cmp_versions( $testee, $minimum ) >= 0 ) ? 1 : 0;
}

sub mysqlversion {
    return $cached_mysql_version ||= current_mysql_version()->{'short'};
}

sub uncached_mysqlversion {
    undef $cached_mysql_version;

    unlink $_VERSION_CACHE_PATH;

    return mysqlversion();
}

sub current_mysql_version {
    my ($host) = @_;

    $host = 'localhost'                   if $USE_LOCAL_MYSQL;
    $host = _getmydbhost() || 'localhost' if !$host;

    if ($>) {
        Cpanel::LoadModule::load_perl_module('Cpanel::Carp');
        die Cpanel::Carp::safe_longmess("Only run as root!") if $>;
    }

    my $is_remote = Cpanel::MysqlUtils::MyCnf::Basic::is_remote_mysql($host);

    my ( $version_string, $maj, $min, $pt );

    if ( ( -s $_VERSION_CACHE_PATH ) && ( ( stat _ )[9] > ( time - $VERSION_CACHE_TTL ) ) ) {
        try {
            ( my $cache_host, $version_string ) = _load_cache_file();

            if ( $version_string && $cache_host eq $host ) {
                try {
                    ( $maj, $min, $pt ) = _split_mysql_version($version_string);
                }
                catch {
                    warn "Invalid MySQL version cache: “$version_string”";
                };
            }
        }
        catch {
            warn "Failed to read “$_VERSION_CACHE_PATH”: " . $_->to_string();
        };
    }

    if ( !$maj ) {
        undef $version_string;
        Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::Unprivileged');

        try {
            $version_string = Cpanel::MysqlUtils::Unprivileged::get_version_from_host($host);
        }

        catch {
            my $exc = $_;
            local $@ = $exc;

            die if $is_remote;
        };

        if ( !$version_string && $is_remote ) {
            die Cpanel::Exception->create( 'The system failed to determine the “[_1]” version on remote host “[_2]”.', [ 'mysqld', $host ] );
        }

        if ( !$version_string ) {



            Cpanel::LoadModule::load_perl_module('Cpanel::DbUtils');
            if ( my $mysqld_bin = Cpanel::DbUtils::find_mysqld() ) {

                Cpanel::LoadModule::load_perl_module('Cpanel::SafeRun::Object');
                my $run = Cpanel::SafeRun::Object->new_or_die(
                    program => $mysqld_bin,
                    args    => ['--version'],
                );

                if ( $run->stdout() =~ m<\A\S+mysqld[^0-9]+([0-9]+\.[0-9]+\.[0-9]+(?:-\S+)?)> ) {
                    $version_string = $1;
                }
            }
        }

        $version_string ||= get_version_from_frm_files();
        $version_string ||= get_version_from_mysql_upgrade_info();

        if ( !$version_string ) {
            die Cpanel::Exception->create( 'The system failed to determine the “[_1]” version.', ['mysqld'] );
        }

        ( $maj, $min, $pt ) = _split_mysql_version($version_string);

        try {
            require Cpanel::FileUtils::Write;
            Cpanel::FileUtils::Write::overwrite( $_VERSION_CACHE_PATH, "$host\n$version_string" );
        }
        catch {
            warn $_;
        };
    }

    return {
        host      => $host,
        is_remote => $is_remote ? 1 : 0,
        full      => $version_string,
        long      => "$maj.$min.$pt",
        short     => "$maj.$min",
    };
}

sub get_short_mysql_version_from_data_files {
    my $version = get_version_from_frm_files() || get_version_from_mysql_upgrade_info();
    if ( length $version ) {
        my ( $maj, $min, $pt ) = _split_mysql_version($version);
        return "$maj.$min";
    }
    return undef;
}

sub get_version_from_mysql_upgrade_info {
    my $mysql_dir = _mysql_data_dir() or return undef;

    my $contents = Cpanel::LoadFile::loadfile("$mysql_dir/mysql_upgrade_info");

    $contents =~ tr{\0}{}d if length $contents;

    return $contents;
}

sub get_version_from_frm_files {
    my $mysql_dir = _mysql_data_dir() or return undef;
    my $newest_mysql_version_id;
    foreach my $potential_file (qw(user table_stats slow_log column_stats db)) {
        my $contents = Cpanel::LoadFile::loadfile("$mysql_dir/mysql/${potential_file}.frm")
          or next;

        if ( $contents =~ qr{^mariadb-version=(\d{4,})}mai ) {
            return mysql_version_id_to_version("$1");
        }

        my $MYSQL_VERSION_ID = unpack( 'L', substr( $contents, 0x0033, 4 ) );    # see https://dev.mysql.com/doc/internals/en/frm-file-format.html
        if ( !$newest_mysql_version_id || $MYSQL_VERSION_ID gt $newest_mysql_version_id ) {
            $newest_mysql_version_id = $MYSQL_VERSION_ID;
        }
    }

    return undef if !$newest_mysql_version_id;
    return mysql_version_id_to_version($newest_mysql_version_id);
}

sub mysql_version_id_to_version ( $newest_mysql_version_id, $limit = 3 ) {
    my @VERSION;

    while ( length $newest_mysql_version_id ) {
        unshift @VERSION, int substr( $newest_mysql_version_id, -2, 2, '' );
    }

    if ( $limit > 0 && scalar @VERSION > $limit ) {
        splice( @VERSION, $limit );
    }

    return join( '.', @VERSION );
}

sub string_to_number ($version) {
    my ( $maj, $min, $pt ) = _split_mysql_version($version);

    return 0 + sprintf( "%d%02d%02d", $maj, $min || 0, $pt || 0 );
}

sub is_at_least_version_and_of_vendor ( $testee, $minimum, $vendor ) {
    $vendor = lc($vendor);
    die "Unknown vendor: $vendor" if !grep { $_ eq $vendor } qw{mysql mariadb};

    require Cpanel::MysqlUtils::Version;
    require Cpanel::MariaDB;

    my $installed_vendor = Cpanel::MariaDB::version_is_mariadb($testee) ? 'mariadb' : 'mysql';
    return Cpanel::MysqlUtils::Version::is_at_least( $testee, $minimum ) && $vendor eq $installed_vendor;
}

sub version_is_mysql {

    my $version;
    try { $version = mysqlversion() };
    return !Cpanel::MariaDB::version_is_mariadb($version) if $version;
    return 'mysql';
}


sub version_dispatch (%table) {
    my $version  = current_mysql_version()->{'short'};
    my $dispatch = $table{$version};

    return unless $dispatch;

    if ( ref($dispatch) eq 'CODE' ) {
        return $dispatch->();
    }
    else {
        return $table{$dispatch}->();
    }
}


sub get_mysql_version_with_fallback_to_default {
    local $@;
    return (
        eval { mysqlversion() }                               #
          || get_short_mysql_version_from_data_files()        #
          || $DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED    #
    );
}


sub get_local_mysql_version_with_fallback_to_default {
    local $@;
    my $localhost = eval { current_mysql_version("localhost"); };    # This can die if it fails to connect
    return $localhost ? $localhost->{short} : get_short_mysql_version_from_data_files() || $DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED;
}


*_getmydbhost = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbhost;

sub _load_cache_file {
    my $cache = Cpanel::LoadFile::loadfile($_VERSION_CACHE_PATH);
    return split m<\n>, $cache, 2;                                   #host => version_string
}

sub _split_mysql_version ($version) {

    $version //= '';

    if ( $version =~ m{mariadb}i ) {
        $version =~ s{\A[0-9]+\.[0-9]+(?:\.[0-9]+)?-}{} if $version =~ m{\A[0-9]+\.[0-9]+(?:\.[0-9]+)?-[0-9]+\.};
    }

    my $version_splitter_re = qr<
        \A
        \s*
        ([0-9]+)
        (?:
            \.
            ([0-9]+)
            (?:
                \.
                ([0-9]+)
                (?:
                    -
                    ([0-9a-z\.\-~+]+)
                )?
            )?
        )?
        \s*
        \z
    >xi;

    my ( $major, $minor, $point, $build ) = ( $version =~ m<$version_splitter_re> ) or do {
        Cpanel::LoadModule::load_perl_module('Cpanel::Carp');
        die Cpanel::Carp::safe_longmess("Invalid version: $version");
    };

    return ( $major, $minor, $point, $build );
}

sub _expand_mysql_version ($version) {
    my ( $major, $minor, $point, $build ) = _split_mysql_version($version);

    $_     ||= 0 for ( $major, $minor, $point );
    $build ||= 'a';

    return "$major.$minor.$point-$build";
}

sub _mysql_data_dir {
    Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::Dir');
    return 'Cpanel::MysqlUtils::Dir'->can('getmysqldir')->();
}

1;

} # --- END Cpanel/MysqlUtils/Version.pm


{ # --- BEGIN Cpanel/Update/Blocker/MySQL.pm
package Cpanel::Update::Blocker::MySQL;


use strict;
use warnings;


use Try::Tiny;

# use Cpanel::Pkgr                              ();
# use Cpanel::LoadFile                          ();
# use Cpanel::Exception                         ();
# use Cpanel::LoadModule                        ();
# use Cpanel::Update::Logger                    ();
# use Cpanel::Config::CpConfGuard               ();
# use Cpanel::MysqlUtils::Versions              ();
# use Cpanel::RPM::Versions::Directory          ();
# use Cpanel::MysqlUtils::MyCnf::Basic          ();
# use Cpanel::Update::Blocker::Constants::MySQL ();

use constant UPGRADE_TOUCHFILE => '/var/cpanel/mysql55_autoupgrade_time';

my @SUPPORTED_MYSQL_RELEASES          = Cpanel::Update::Blocker::Constants::MySQL::SUPPORTED_MYSQL_RELEASES();
my @SUPPORTED_MARIADB_RELEASES        = Cpanel::Update::Blocker::Constants::MySQL::SUPPORTED_MARIADB_RELEASES();
my $MINIMUM_RECOMMENDED_MYSQL_RELEASE = Cpanel::Update::Blocker::Constants::MySQL::MINIMUM_RECOMMENDED_MYSQL_RELEASE();


sub new {
    my ( $class, $args ) = @_;

    my $self = $class->_init($args);
    return bless $self, $class;
}

sub _init {
    my ( $class, $args ) = @_;

    my $logger   = $args->{'logger'}   || Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );
    my $cpconfig = $args->{'cpconfig'} || Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 )->config_copy();

    my $rpmv          = Cpanel::RPM::Versions::Directory->new( { 'mysql_targets' => [ Cpanel::MysqlUtils::Versions::get_rpm_target_names( Cpanel::MysqlUtils::Versions::get_installable_versions() ) ] } );
    my $mysql_version = $cpconfig->{'mysql-version'} || '';

    return {
        'logger'          => $logger,
        'rpmv'            => $rpmv,
        'mysql_version'   => $mysql_version,
        'upgrade_started' => 0,
    };
}


sub mysql_version_in_cpconfig { return $_[0]->{'mysql_version'}; }


sub is_mysql_version_valid {
    my $self = shift;

    return $self->base_install_check() if $ENV{'CPANEL_BASE_INSTALL'};
    return 1                           if Cpanel::MysqlUtils::MyCnf::Basic::is_remote_mysql();

    if ( $self->meets_conditions_for_autoupgrade_to_mysql57() ) {
        my ( $time_passed, $time_left ) = _is_time_to_autoupgrade();

        return $self->perform_autoupgrade_and_notify()
          if $time_passed;

        $self->notify_about_pending_autoupgrade($time_left);
        return 1;
    }
    elsif ( !$self->is_mysql_supported_by_cpanel() ) {    # block if we detect a legacy MySQL version
        return 0;
    }

    return 1;
}


sub base_install_check {
    my $self = shift;

    my $mysql_version = $self->mysql_version_in_cpconfig();

    return 1 if $mysql_version eq '';

    return 1 if grep { $mysql_version eq $_ } (
        @SUPPORTED_MYSQL_RELEASES,
        @SUPPORTED_MARIADB_RELEASES,
    );

    return 0;
}


sub meets_conditions_for_autoupgrade_to_mysql57 {
    my $self = shift;

    return 0 if not _is_runing_mysql_55();

    $self->{'logger'}->info('[*] Evaluating if system can autoupgrade MySQL 5.5 to MySQL 5.7...');

    return 0 if not $self->_is_mysql_version_in_cpconfig_set_to_55();

    return 0 if $self->_is_mysql55_target_set_in_local_rpm_versions();

    return 0 if not $self->_is_mysql55_cpanel_rpm();

    return 0 if $self->_has_user_created_databases();

    return 0 if not $self->_can_migrate_my_cnf();

    $self->{'logger'}->info('[+] System can autoupgrade MySQL 5.5 to MySQL 5.7.');

    return 1;
}


sub perform_autoupgrade_and_notify {
    my $self = shift;

    if ( try { Cpanel::LoadModule::load_perl_module('Whostmgr::Mysql::Upgrade') } ) {
        my ( $failed_step, $err );
        try {
            Cpanel::LoadModule::load_perl_module('Whostmgr::Mysql::Upgrade::Warnings');
            my ( $fatal, $warnings_ar ) = Whostmgr::Mysql::Upgrade::Warnings::get_upgrade_warnings( 5.7, 5.5 );
            if ($fatal) {
                Cpanel::LoadModule::load_perl_module('Cpanel::StringFunc::HTML');
                my $warnings_str = "\n" . join(
                    '   ',
                    map {
                        my $msg = $_->{'message'};
                        chomp($msg);
                        $msg .= "\n";
                        Cpanel::StringFunc::HTML::trim_html( \$msg );
                        $msg
                    } grep { $_->{'severity'} eq 'Fatal' } @$warnings_ar
                );

                die "MySQL could not be updated due to the following: $warnings_str\n";
            }

            $self->{'upgrade_started'} = 1;
            $self->{'logger'}->info("[*] Attempting to autoupgrade MySQL 5.5 to MySQL 5.7...");
            $failed_step = Whostmgr::Mysql::Upgrade::unattended_upgrade(
                {
                    upgrade_type     => 'unattended_automatic',
                    selected_version => '5.7',
                }
            );
        }
        catch {
            $err = $_;
        };
        if ($err) {
            $self->{'logger'}->error("[!] MySQL autoupgrade to 5.7 failed. Error: $err");
            return $self->notify_autoupgrade_failure($err);
        }

        if ( !$failed_step ) {
            $self->{'logger'}->info("[+] MySQL was autoupgraded to 5.7 successfully.");
            unlink UPGRADE_TOUCHFILE();
            return $self->notify_autoupgrade_success();
        }

        my $last_upgrade_logpath = $self->get_last_mysqlupgrade_logpath();
        $self->{'logger'}->error( "[!] MySQL autoupgrade to 5.7 failed. " . ( $last_upgrade_logpath ? "Review the mysql upgrade log for more details: $last_upgrade_logpath" : "" ) );
        return $self->notify_autoupgrade_failure();
    }

    return $self->notify_autoupgrade_failure('Failed to load Whostmgr::Mysql::Upgrade to perform upgrade.');
}


sub get_last_mysqlupgrade_logpath {
    my $self = shift;

    return '' if not $self->{'upgrade_started'};
    if ( opendir my $dh, $Whostmgr::Mysql::Upgrade::LOG_BASE_DIR ) {
        my ( $latest_path, $_time ) = ( undef, 2**31 - 1 );

        while ( defined( my $f = readdir($dh) ) ) {
            next if $f !~ m/^mysql_upgrade\./;

            my $path = $Whostmgr::Mysql::Upgrade::LOG_BASE_DIR . '/' . $f;
            next if !-d $path;

            ( $latest_path, $_time ) = ( $path, -M _ ) if ( -M $path < $_time );
        }

        return "$latest_path/unattended_upgrade.log"
          if $latest_path && -e "$latest_path/unattended_upgrade.log";
    }

    return '';
}

my $notification_args = {
    'origin'            => 'upcp',
    'service_name'      => 'MySQL 5.5',
    'replacement'       => 'MySQL 5.7',
    'last_version'      => '11.78',
    'days_left'         => undef,
    'hrs_left'          => undef,
    'failed_to_convert' => 0,
    'script_output'     => '',
};


sub notify_about_pending_autoupgrade {
    my ( $self, $time_left ) = @_;

    my $days_left = $notification_args->{'days_left'} = int( $time_left / ( 24 * 60 * 60 ) );
    my $hrs_left  = $notification_args->{'hrs_left'}  = ( $time_left / ( 60 * 60 ) ) % 24;

    $self->{'mysql-reason'} =
      qq{Future releases of cPanel & WHM may not be compatible with your local MySQL version. You can upgrade your local MySQL server to a version greater than $MINIMUM_RECOMMENDED_MYSQL_RELEASE using the <a href="../scripts/mysqlupgrade">MySQL/MariaDB Upgrade</a> interface. If you take no action, the system will automatically upgrade to MySQL 5.7 in $days_left day(s) and $hrs_left hour(s).};

    _notify($notification_args);
    return;
}


sub notify_autoupgrade_failure {
    my ( $self, $reason ) = @_;

    undef $notification_args->{'days_left'};
    undef $notification_args->{'hrs_left'};
    $notification_args->{'failed_to_convert'} = 1;
    $notification_args->{'script_output'}     = $reason // 'Unknown Error. Review the upgrade log for details.';

    my $last_upgrade_logpath = $self->get_last_mysqlupgrade_logpath();
    $notification_args->{'script_output'} .= "Review the mysql upgrade log for more details: $last_upgrade_logpath"
      if $last_upgrade_logpath;

    _notify($notification_args);
    return 0;
}


sub notify_autoupgrade_success {
    my ($self) = @_;

    undef $notification_args->{'days_left'};
    undef $notification_args->{'hrs_left'};
    $notification_args->{'failed_to_convert'} = 0;

    my $last_upgrade_logpath = $self->get_last_mysqlupgrade_logpath();
    $notification_args->{'script_output'} .= "Review the mysql upgrade log for more details: $last_upgrade_logpath"
      if $last_upgrade_logpath;

    _notify($notification_args);
    return 1;
}

sub _is_runing_mysql_55 {
    my $version;

    try {
        require Cpanel::MysqlUtils::Version;
        $version = Cpanel::MysqlUtils::Version::uncached_mysqlversion();
    };

    return 1 if $version <= 5.5;
    return 0;
}

sub _is_mysql_version_in_cpconfig_set_to_55 {
    my $self = shift;

    if ( $self->mysql_version_in_cpconfig() != 5.5 ) {
        $self->{'logger'}->info('[!] Unable to autoupgrade: "mysql-version" is not configured properly in /var/cpanel/cpanel.config');
        return 0;
    }

    return 1;
}

sub _is_mysql55_target_set_in_local_rpm_versions {
    my $self = shift;

    my $rpmv           = $self->{rpmv}                                                                               || return 0;
    my $target_setting = $rpmv->{'local_file_data'}->fetch( { 'section' => 'target_settings', 'key' => 'MySQL55' } ) || '';
    if ( $target_setting eq 'installed' or $target_setting eq 'unmanaged' ) {
        $self->{'logger'}->info("[!] Unable to autoupgrade: the MySQL55 target is set to '$target_setting' in the rpm.versions system");
        return 1;
    }

    return 0;
}

sub _is_mysql55_cpanel_rpm {
    my $self = shift;
    return 1 if $self->_target_setting('MySQL55-server');
    $self->{'logger'}->info('[!] Unable to autoupgrade: the MySQL55 packages installed are not provided cPanel');
    return 0;
}

sub _has_user_created_databases {
    my $self = shift;

    my %databases;
    my $fetched_dblist = 0;
    try {
        Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::Connect');
        my $dbh = Cpanel::MysqlUtils::Connect::get_dbi_handle();

        my $sth = $dbh->prepare('show databases;') or die $dbh->errstr;
        $sth->execute()                            or die $dbh->errstr;

        while ( my $db = $sth->fetchrow_array() ) {
            $databases{$db} = 1;
        }

        $sth->finish;
        $fetched_dblist++;
    }
    catch {
        $self->{'logger'}->warning("[!] Unable to autoupgrade: Errors encounterd when fetching list of MySQL databases.");
        $self->{'logger'}->warning( "[!] Errors: " . Cpanel::Exception::to_string_no_id($_) );
    };

    return 1 if !$fetched_dblist;

    my %mysql55_system_dbs = map { $_ => 1 } qw(information_schema performance_schema mysql);
    foreach my $db ( keys %databases ) {

        if ( not exists $mysql55_system_dbs{$db} ) {
            $self->{'logger'}->info("[!] Unable to autoupgrade: there are user created databases present (ex: '$db')");
            return 1;
        }
    }

    return 0;
}

sub _can_migrate_my_cnf {
    my $self = shift;

    my ( $possible_to_migrate, $err );
    try {
        Cpanel::LoadModule::load_perl_module('Cpanel::ConfigFiles');
        Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::MyCnf::Migrate');
        $possible_to_migrate = Cpanel::MysqlUtils::MyCnf::Migrate::possible_to_migrate_my_cnf_file( $Cpanel::ConfigFiles::MYSQL_CNF, 5.5, 5.7 );
    }
    catch {
        $err = $_;
    };
    if ( $err || !$possible_to_migrate ) {
        $self->{'logger'}->info( "[!] Unable to autoupgrade: The system detected issues with the current “/etc/my.cnf” file. These issues may interfere with the upgrade process" . ( $err ? ":\n" . join( "\n", map { "\t$_" } split( "\n", $err ) ) : '.' ) );
        return 0;
    }

    return 1;
}

sub _is_time_to_autoupgrade {
    _set_autoupgrade_file();
    return _check_autoupgrade_time();
}

sub _check_autoupgrade_time {
    my $time_to_check = Cpanel::LoadFile::loadfile( UPGRADE_TOUCHFILE() );
    chomp $time_to_check;

    my $curtime = time();
    if ( $time_to_check <= $curtime ) {
        return ( 1, 0 );
    }

    return ( 0, $time_to_check - $curtime );
}

sub _set_autoupgrade_file {
    return if -e UPGRADE_TOUCHFILE();

    if ( open my $fh, '>', UPGRADE_TOUCHFILE() ) {
        print $fh time() + ( 30 * 86400 );    # 30 days from now.
        close $fh;
    }

    return;
}


sub is_mysql_supported_by_cpanel {
    my $self = shift or die;



    my $rpmv = $self->{rpmv} || return 0;

    foreach my $version ( Cpanel::Update::Blocker::Constants::MySQL::BLOCKED_MYSQL_RELEASES() ) {
        my $target_number = $version;
        $target_number =~ s/\.//;
        my $target         = 'MySQL' . $target_number;
        my $target_setting = $rpmv->fetch( { 'section' => 'target_settings', 'key' => $target } ) || '';
        $target_setting = $self->_double_check_mysqltarget_setting( $target, $target_setting );

        if ( $target_setting eq 'installed' ) {
            $self->{'mysql-reason'} = 'Newer releases of cPanel & WHM are not compatible with your local MySQL version: ' . $version . '.' . ' You must upgrade your local MySQL server to a version greater or equal to ' . $MINIMUM_RECOMMENDED_MYSQL_RELEASE . ' using the <a href="../scripts/mysqlupgrade">MySQL/MariaDB Upgrade</a> interface.';
            return 0;
        }
    }

    foreach my $version (@SUPPORTED_MYSQL_RELEASES) {
        my $target_number = $version;
        $target_number =~ s/\.//;
        my $target_setting = $rpmv->fetch( { 'section' => 'target_settings', 'key' => 'MySQL' . $target_number } ) || '';
        return 1 if $target_setting eq 'installed';
    }

    return 1;
}

sub _double_check_mysqltarget_setting {
    my ( $self, $target, $target_setting ) = @_;

    return $target_setting unless $target && $target_setting && $target_setting eq 'uninstalled';
    return $self->_target_setting("${target}-server") || $target_setting;
}

sub _target_setting {
    my ( $self, $target ) = @_;

    my $v = Cpanel::Pkgr::get_package_version($target);
    return 'installed' if $v && $v =~ m/\.cp\d+$/;

    return;
}

sub _notify {
    my $notification_args = shift;

    if ( try { Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Update::ServiceDeprecated') } ) {
        _send_icontact_class_notification(
            'class'            => 'Update::ServiceDeprecated',
            'application'      => 'Update::ServiceDeprecated',
            'constructor_args' => [%$notification_args],
        );
    }
    else {
        my ( $subject, $message ) = _fetch_legacy_autoupgrade_notification($notification_args);
        _send_icontact_noclass_notification( $subject, $message );
    }

    return 1;
}

sub _send_icontact_class_notification {
    my %notification_args = @_;

    require Cpanel::Notify;
    return Cpanel::Notify::notification_class(%notification_args);
}

sub _send_icontact_noclass_notification {
    my ( $subject, $message ) = @_;

    require Cpanel::iContact;
    return Cpanel::iContact::icontact(
        'application' => 'upcp',
        'subject'     => $subject,
        'message'     => $message,
    );
}

sub _fetch_legacy_autoupgrade_notification {
    my $notification_args = shift;

    my ( $subject, $message );
    if ( defined $notification_args->{'days_left'} || defined $notification_args->{'hrs_left'} ) {
        my $days_left = ( defined $notification_args->{'days_left'} ? $notification_args->{'days_left'} : 0 );
        my $hrs_left  = ( defined $notification_args->{'hrs_left'}  ? $notification_args->{'hrs_left'}  : 0 );

        $subject = "The system will automatically upgrade $notification_args->{'service_name'} to $notification_args->{'replacement'} in $days_left day(s) and $hrs_left hour(s) in order to continue receiving updates.";
        $message = <<END_OF_MESSAGE;
The system is running a deprecated and soon-to-be unsupported service: $notification_args->{'service_name'}

The last version of cPanel & WHM to support this service is $notification_args->{'last_version'}. To ensure that your system can upgrade to a newer version of cPanel & WHM, upgrade $notification_args->{'service_name'} to $notification_args->{'replacement'} with using the MySQL/MariaDB Upgrade interface in WHM.

If you take no action, cPanel & WHM will automatically upgrade $notification_args->{'service_name'} to $notification_args->{'replacement'} in $days_left day(s) and $hrs_left hour(s).

END_OF_MESSAGE
    }
    else {
        if ( $notification_args->{'failed_to_convert'} ) {
            $subject = $message = "The system failed to upgrade $notification_args->{'service_name'} to $notification_args->{'replacement'}";
        }
        else {
            $subject = $message = "The deprecated service, $notification_args->{'service_name'}, has been upgraded to $notification_args->{'replacement'}.";
        }

        $message .= "\n\nReview the log for further details:\n\n$notification_args->{'script_output'}\n\n"
          if ( $notification_args->{'script_output'} );
    }

    return ( $subject, $message );
}

1;

} # --- END Cpanel/Update/Blocker/MySQL.pm


{ # --- BEGIN Cpanel/Update/Blocker/RemoteMySQL.pm
package Cpanel::Update::Blocker::RemoteMySQL;


use strict;
use warnings;


# use Cpanel::Update::Logger                    ();
# use Cpanel::MysqlUtils::Version               ();
# use Cpanel::Update::Blocker::Constants::MySQL ();


sub new {
    my ( $class, $args ) = @_;

    my $self = $class->init($args);
    return bless $self, $class;
}


sub init {
    my ( $class, $args ) = @_;

    my $logger = $args->{'logger'} || Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );
    return {
        'logger' => $logger,
    };
}


sub is_mysql_supported_by_cpanel {
    my $self = shift or die;

    my $current_version = Cpanel::MysqlUtils::Version::mysqlversion();

    foreach my $version ( Cpanel::Update::Blocker::Constants::MySQL::BLOCKED_MYSQL_RELEASES() ) {
        my $supported = Cpanel::MysqlUtils::Version::cmp_versions( $version, $current_version );
        if ( !$supported ) {
            die "Newer releases of cPanel & WHM are not compatible with your remote MySQL version: $version. You must upgrade your remote MySQL server to a version greater or equal to " . Cpanel::Update::Blocker::Constants::MySQL::MINIMUM_RECOMMENDED_MYSQL_RELEASE() . ".\n";
        }
    }

    foreach my $version ( Cpanel::Update::Blocker::Constants::MySQL::SUPPORTED_MYSQL_RELEASES(), Cpanel::Update::Blocker::Constants::MySQL::SUPPORTED_MARIADB_RELEASES() ) {
        my $supported = Cpanel::MysqlUtils::Version::cmp_versions( $version, $current_version );
        return 1 if $supported;
    }

    die "cPanel & WHM does not support your remote MySQL/MariaDB version: $current_version.\n";
}


sub is_remote_mysql {
    my $current_version = Cpanel::MysqlUtils::Version::current_mysql_version();
    return $current_version->{'is_remote'};
}

1;

} # --- END Cpanel/Update/Blocker/RemoteMySQL.pm


{ # --- BEGIN Cpanel/LinkedNode/Privileged/Configuration.pm
package Cpanel::LinkedNode::Privileged::Configuration;


use cPstrict;

my @_GETTERS;

BEGIN {
    @_GETTERS = (
        'alias',
        'hostname',
        'username',
        'api_token',
        'enabled_services',
        'worker_capabilities',
        'last_check',
        'version',
        'tls_verified',
        'system_settings',
    );
}



# use Cpanel::Context    ();
# use Cpanel::LoadModule ();



use Class::XSAccessor (
    constructor => 'new',
    getters     => \@_GETTERS,
);


sub allow_bad_tls ($self) {
    return !$self->tls_verified();
}



sub get_async_remote_api ($self) {
    return $self->_get_remote_api('Cpanel::Async::RemoteAPI::WHM::ToChild');
}

sub _get_remote_api ( $self, $class ) {
    Cpanel::LoadModule::load_perl_module($class);

    return $self->{"_remote_api_$class"} ||= do {
        my $obj = $class->new_from_token( $self->hostname(), $self->username(), $self->api_token() );

        $obj->disable_tls_verify() if $self->allow_bad_tls();

        $obj;
    };
}



sub get_remote_api ($self) {
    return $self->_get_remote_api('Cpanel::RemoteAPI::WHM::ToChild');
}



sub get_commandstream ($self) {
    return $self->{'_commandstream'} ||= do {

        Cpanel::LoadModule::load_perl_module('Cpanel::CommandStream::Client::WebSocket::APIToken');

        Cpanel::CommandStream::Client::WebSocket::APIToken->new(
            hostname         => $self->hostname(),
            username         => $self->username(),
            api_token        => $self->api_token(),
            tls_verification => $self->allow_bad_tls() ? 'off' : 'on',
        );
    };
}



sub get_api_token_header ($self) {
    Cpanel::Context::must_be_list();

    return (
        'Authorization',
        sprintf(
            "whm %s:%s",
            $self->username(),
            $self->api_token(),
        ),
    );
}


sub TO_JSON ($self) {
    my %vals = %{$self}{@_GETTERS};
    return \%vals;
}

1;

} # --- END Cpanel/LinkedNode/Privileged/Configuration.pm


{ # --- BEGIN Cpanel/LinkedNode/Index.pm
package Cpanel::LinkedNode::Index;


use cPstrict;



# use Cpanel::LinkedNode::Privileged::Configuration ();

our $_DIR = '/var/cpanel/linked_nodes';



sub dir {
    return $_DIR;
}


sub file {
    return "$_DIR/master.json";
}


sub objectify_contents ($raw_hr) {
    for my $alias ( keys %$raw_hr ) {
        $raw_hr->{$alias} = Cpanel::LinkedNode::Privileged::Configuration->new( alias => $alias, %{ $raw_hr->{$alias} } );
    }

    return;
}

1;

} # --- END Cpanel/LinkedNode/Index.pm


{ # --- BEGIN Cpanel/LinkedNode/Index/Read.pm
package Cpanel::LinkedNode::Index::Read;


use cPstrict;



# use Cpanel::LoadFile          ();
# use Cpanel::LinkedNode::Index ();
# use Cpanel::JSON              ();



sub get() {
    my $path = Cpanel::LinkedNode::Index::file();

    my $resp_hr = Cpanel::LoadFile::load_if_exists($path);

    if ($resp_hr) {
        $resp_hr = Cpanel::JSON::Load($resp_hr);

        Cpanel::LinkedNode::Index::objectify_contents($resp_hr);
    }

    return $resp_hr || {};
}

1;

} # --- END Cpanel/LinkedNode/Index/Read.pm


{ # --- BEGIN Cpanel/Data/Result.pm
package Cpanel::Data::Result;


use cPstrict;



use constant {
    _SUCCESS_PKG => __PACKAGE__ . '::Success',
    _FAILURE_PKG => __PACKAGE__ . '::Failure',
};



sub create_success ($value) {
    return bless \$value, _SUCCESS_PKG();
}


sub create_failure ($error) {

    if ( !ref($error) && !$error ) {
        _carp('Falsy failure is nonsensical!');
    }

    return bless \$error, _FAILURE_PKG();
}


sub try ($coderef) {
    local ($@);

    my $result;

    eval { $result = $coderef->(); 1 } or do {
        my $error = $@;
        return bless \$error, _FAILURE_PKG();
    };

    return bless \$result, _SUCCESS_PKG();
}

sub _carp ($msg) {
    local ( $@, $! );
    require Carp;
    return Carp::croak($msg);
}



package Cpanel::Data::Result::Success;

# use Cpanel::Data::Result();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Data::Result); }

use constant error => undef;

sub get ($self) {
    return $$self;
}


package Cpanel::Data::Result::Failure;

# use Cpanel::Data::Result();
BEGIN { push @ISA, qw(Cpanel::Data::Result); }

BEGIN {

    no warnings 'once';

    *error = *Cpanel::Data::Result::Success::get;
}

sub get ($self) {
    return Cpanel::Data::Result::_carp( $$self // '' );
}

1;

} # --- END Cpanel/Data/Result.pm


{ # --- BEGIN Cpanel/PromiseUtils.pm
package Cpanel::PromiseUtils;


use cPstrict;



use AnyEvent    ();
use Promise::XS ();

# use Cpanel::Data::Result ();

AnyEvent->now_update();



sub wait_anyevent (@promises) {
    if ( !@promises ) {
        local ( $@, $! );
        require Carp;
        Carp::croak('Need >= 1 promise.');
    }

    if ( !wantarray && defined wantarray && @promises > 1 ) {
        my $how_many = @promises;

        local ( $@, $! );
        require Carp;
        Carp::croak("call in scalar context must receive only 1 promise! (received $how_many)");
    }

    my $cv = AnyEvent->condvar();

    @promises = map { $_->then( \&_create_success, \&_create_failure ); } @promises;

    my @results;

    Promise::XS::all(@promises)->then(
        sub (@results_ars) {
            @results = map { $_->[0] } @results_ars;
            $cv->();
        }
    )->catch(
        sub ($err) {

            $cv->croak($err);
        }
    );

    $cv->recv();

    if ( !defined wantarray ) {
        local $Carp::Internal{ +__PACKAGE__ } = 1;

        $_->get() for @results;
    }

    return splice @results;
}

sub _create_success ( $result = undef, @extra ) {
    die sprintf( "Promise resolved with %d results ($result @extra); only 1 allowed.", 1 + @extra ) if @extra;

    return Cpanel::Data::Result::create_success($result);
}

sub _create_failure ( $error = undef, @extra ) {
    die sprintf( "Promise rejected with %d results ($error @extra); only 1 allowed.", 1 + @extra ) if @extra;

    return Cpanel::Data::Result::create_failure($error);
}


sub ordered_all ( $on_each_cr, @promises ) {
    my $d = Promise::XS::deferred();

    sub {
        my $do_next = __SUB__;

        if ( my $this_p = shift @promises ) {
            $this_p->then(
                sub (@res) {
                    my @got = $on_each_cr->( $d, @res );

                    $do_next->() if $d->is_pending();

                    return @got;
                },
            )->catch(
                sub (@err) {
                    $d->reject(@err);
                },
            );
        }
        else {
            $d->resolve();
        }
      }
      ->();

    return $d->promise()->finally(
        sub {
            @promises = ();
        }
    );
}



sub delay ($after) {
    my $deferred = Promise::XS::deferred();

    my $t;
    $t = AnyEvent->timer(
        after => $after,
        cb    => sub {
            undef $t;
            $deferred->resolve();
        },
    );

    return $deferred->promise();
}



sub retry ( $promise_cr, $max_retries, $should_retry_cr = undef ) {    ## no critic qw(ManyArgs) - mis-parse
    my $retries = 0;

    return $promise_cr->($retries)->catch(
        sub ($why) {
            my $currentsub = __SUB__;

            if ( $retries < $max_retries ) {
                my $should_retry;

                if ($should_retry_cr) {
                    local $@;
                    eval { $should_retry = $should_retry_cr->($why); 1 } or do {
                        warn "Failed to determine if I should retry (assuming no): $@";
                    };
                }
                else {
                    $should_retry = 1;
                }

                if ($should_retry) {
                    $retries++;
                    return $promise_cr->($retries)->catch($currentsub);
                }
            }

            return Promise::XS::rejected($why);
        }
    );
}

1;

} # --- END Cpanel/PromiseUtils.pm


{ # --- BEGIN Cpanel/Update/Blocker/WorkerNodes.pm
package Cpanel::Update::Blocker::WorkerNodes;


use cPstrict;



use Cpanel::Imports;

# use Cpanel::Exception               ();
# use Cpanel::LinkedNode::Index::Read ();
# use Cpanel::PromiseUtils            ();
# use Cpanel::Version::Compare        ();

use cPanel::APIClient                             ();
use cPanel::APIClient::Service::whm               ();
use cPanel::APIClient::Request::WHM1              ();
use cPanel::APIClient::Transport::NetCurlPromiser ();
use Net::Curl::Promiser::AnyEvent                 ();



sub get_workers_problem (%opts) {

    my $logger = $opts{'logger'} or die "need logger";

    my $target_version = $opts{'target_version'} or die "need target_version";

    if ( $target_version !~ tr<.><> ) {
        die "invalid “target_version” ($target_version)!";
    }

    my $target_major_version = Cpanel::Version::Compare::get_major_release($target_version);

    my $nodes_hr = Cpanel::LinkedNode::Index::Read::get();

    my @promises;

    my %update_working;

    my @check_failed;

    my $log_err = sub ($phrase) {
        $logger->error($phrase);
    };

    foreach my $node_obj ( values %$nodes_hr ) {
        my $api      = $node_obj->get_async_remote_api();
        my $hostname = $node_obj->hostname();

        push @promises, $api->request_whmapi1('version')->then(
            sub ($res) {
                my $remote_version = $res->get_data()->{'version'} or do {
                    die "No version in $hostname’s `version` API response!\n";
                };

                my $remote_major_version = Cpanel::Version::Compare::get_major_release($remote_version);

                if ( Cpanel::Version::Compare::compare( $remote_major_version, '<', $target_major_version ) ) {
                    $log_err->("“$hostname” runs cPanel & WHM version $remote_version.  This update’s target version is $target_version. All child nodes must be up to date before this server can update. The system will now attempt to start an update on “$hostname”.");

                    my $update_sr = \$update_working{$hostname};

                    return _update_promise( $logger, $hostname, $api, $update_sr );
                }
            },
        )->catch(
            sub ($why) {
                push @check_failed, $hostname;

                $why = Cpanel::Exception::get_string($why);

                $log_err->("The system failed to determine “$hostname”’s cPanel & WHM version because of an error: $why");
            },
        );
    }

    Cpanel::PromiseUtils::wait_anyevent(@promises) if @promises;

    return _get_report( \@check_failed, \%update_working, $target_major_version );
}

sub _get_report ( $check_failed_ar, $update_working_hr, $target_major_version ) {    ## no critic qw(ProhibitManyArgs) - mis-parse
    my $automatic_updates = grep { $update_working_hr->{$_} } keys %$update_working_hr;

    my $needs_manual_work = keys(%$update_working_hr) - $automatic_updates;
    $needs_manual_work += @$check_failed_ar;

    my @phrases;

    if ($needs_manual_work) {
        $needs_manual_work == 1
          ? push @phrases, "child node requires manual attention.\n"
          : push @phrases, "child nodes require manual attention.\n";
    }

    if ($automatic_updates) {
        $automatic_updates == 1
          ? push @phrases, "child node is automatically updating.\n"
          : push @phrases, "child nodes are automatically updating.\n";
    }

    if (@phrases) {
        my $total_nodes = $needs_manual_work + $automatic_updates;
        $total_nodes == 1
          ? push @phrases, "Try again once this child node runs version $target_major_version or later.\n"
          : push @phrases, "Try again once all child nodes run version $target_major_version or later.\n";
    }

    return "@phrases";
}

sub _update_promise ( $logger, $hostname, $api, $update_sr ) {
    return $api->request_whmapi1('start_cpanel_update')->then(
        sub ($resp) {
            $$update_sr = 1;

            my ( $new_yn, $pid, $log_path ) = @{ $resp->get_data() }{ 'is_new', 'pid', 'log_path' };

            my @phrases;

            if ($new_yn) {
                push @phrases, "An update on “$hostname” (process ID: $pid) is now in progress.\n";
            }
            else {
                push @phrases, "There is already a version update in progress on “$hostname” (process ID: $pid )\n";
            }

            push @phrases, "The update’s log file on that system is “$log_path”.\n";

            $logger->info("@phrases");
        },
        sub ($why) {
            $$update_sr = 0;

            my $why_string = Cpanel::Exception::get_string($why);
            $logger->warn("The system failed to start a cPanel & WHM update on “$hostname” because of an error: $why_string");
        },
    );
}

1;

} # --- END Cpanel/Update/Blocker/WorkerNodes.pm


{ # --- BEGIN Cpanel/Version/Compare/Package.pm
package Cpanel::Version::Compare::Package;


use cPstrict;


sub version_string_cmp ( $ver1, $ver2 ) {

    my ( $e1, $v1, $r1 ) = $ver1 =~ m/(?:(\d+):)?([^:-]+)(?:-([^:-]+))?/a;
    my ( $e2, $v2, $r2 ) = $ver2 =~ m/(?:(\d+):)?([^:-]+)(?:-([^:-]+))?/a;

    my $cmp = ( $e1 || 0 ) <=> ( $e2 || 0 );
    return $cmp if $cmp;

    return version_cmp( $v1, $v2 ) || version_cmp( $r1 || '', $r2 || '' );
}


sub version_cmp ( $ver1, $ver2 ) {

    my @v1 = ( $ver1 =~ m/([a-zA-Z]+|[0-9]+)/g );
    my @v2 = ( $ver2 =~ m/([a-zA-Z]+|[0-9]+)/g );

    while ( @v1 && @v2 ) {
        my $s1 = shift @v1;
        my $s2 = shift @v2;

        if ( $s1 =~ m/\d/a ) {
            return 1 if $s2 =~ m/\D/a;    # Handle numeric/alphabetic mismatch.
            my $cmp = $s1 <=> $s2;
            return $cmp if $cmp;
        }
        else {
            return -1 if $s2 =~ m/\d/a;    # Handle numeric/alphabetic mismatch.
            my $cmp = $s1 cmp $s2;
            return $cmp if $cmp;
        }
    }

    return @v1 <=> @v2;
}

1;

} # --- END Cpanel/Version/Compare/Package.pm


{ # --- BEGIN Cpanel/ConfigFiles/Apache.pm
package Cpanel::ConfigFiles::Apache;



use cPstrict;

# use Cpanel::Config::LoadConfig ();

my $multiton = {};


sub apache_paths_facade {
    state $lazyfacade = Cpanel::ConfigFiles::Apache->new();
    return $lazyfacade;
}


sub is_installed ($self) {

    $self = apache_paths_facade() unless ref $self;
    return -e $self->bin_httpd;
}

sub import ( $class, @args ) {

    if ( scalar @args ) {
        if ( grep { $_ eq 'apache_paths_facade' } @args ) {
            my $caller = caller;
            no strict 'refs';
            *{ $caller . "::apache_paths_facade" } = \&apache_paths_facade;
        }
        else {
            die "$class does not import @args\n";
        }
    }

    return 1;
}

use constant EA4_PATHS_PATH => '/etc/cpanel/ea4/paths.conf';

sub new ( $class, $path = undef ) {

    $path //= EA4_PATHS_PATH;

    my $mtime = ( stat($path) )[9] // 0;
    return $multiton->{$path} if defined $multiton->{$path} && $multiton->{$path}{'_meta'}{'mtime'} == $mtime;

    my $self = exists $multiton->{$path} ? $multiton->{$path} : {};
    $self->{_meta}{path}  = $path;
    $self->{_meta}{mtime} = $mtime;

    $self->{'dir_base'}             = '/usr/local/apache';
    $self->{'dir_logs'}             = $self->{'dir_base'} . '/logs';
    $self->{'dir_domlogs'}          = $self->{'dir_base'} . '/domlogs';
    $self->{'dir_modules'}          = $self->{'dir_base'} . '/modules';
    $self->{'dir_run'}              = $self->{'dir_logs'};
    $self->{'dir_conf'}             = $self->{'dir_base'} . '/conf';
    $self->{'dir_conf_includes'}    = $self->{'dir_conf'} . '/includes';
    $self->{'dir_conf_userdata'}    = $self->{'dir_conf'} . '/userdata';
    $self->{'dir_docroot'}          = $self->{'dir_base'} . '/htdocs';
    $self->{'file_access_log'}      = $self->{'dir_logs'} . '/access_log';
    $self->{'file_error_log'}       = $self->{'dir_logs'} . '/error_log';
    $self->{'file_conf'}            = $self->{'dir_conf'} . '/httpd.conf';
    $self->{'file_conf_mime_types'} = $self->{'dir_conf'} . '/mime.types';
    $self->{'file_conf_srm_conf'}   = $self->{'dir_conf'} . '/srm.conf';
    $self->{'file_conf_php_conf'}   = $self->{'dir_conf'} . '/php.conf';
    $self->{'bin_httpd'}            = $self->{'dir_base'} . '/bin/httpd';
    $self->{'bin_apachectl'}        = $self->{'dir_base'} . '/bin/apachectl';
    $self->{'bin_suexec'}           = $self->{'dir_base'} . '/bin/suexec';

    my $conf;
    if ($mtime) {
        $conf = Cpanel::Config::LoadConfig::loadConfig( $path, undef, '\s*=\s*', undef, '^\s*', undef, { 'empty_is_invalid' => 1 } );
    }
    $conf ||= {};
    foreach my $key ( keys %$conf ) {
        my $value = $conf->{$key};

        if ( defined $value && length($value) && exists $self->{$key} ) {
            $self->{$key} = $value;
        }
    }

    if ( !exists $multiton->{$path} ) {
        $multiton->{$path} = bless $self, $class;
    }

    return $multiton->{$path};
}


sub get_template_hashref ($self) {
    my %newhash = %$self;
    delete $newhash{_meta};
    return \%newhash;
}


sub dir_base ($self) {
    return $self->{'dir_base'};
}


sub dir_logs ($self) {
    return $self->{'dir_logs'};
}


sub dir_domlogs ($self) {
    return $self->{'dir_domlogs'};
}


sub dir_modules ($self) {
    return $self->{'dir_modules'};
}


sub dir_run ($self) {
    return $self->{'dir_run'};
}


sub dir_conf ($self) {
    return $self->{'dir_conf'};
}


sub dir_conf_includes ($self) {
    return $self->{'dir_conf_includes'};
}


sub dir_conf_userdata ($self) {
    return $self->{'dir_conf_userdata'};
}


sub dir_docroot ($self) {
    return $self->{'dir_docroot'};
}


sub file_access_log ($self) {
    return $self->{'file_access_log'};
}


sub file_error_log ($self) {
    return $self->{'file_error_log'};
}


sub file_conf ($self) {
    return $self->{'file_conf'};
}


sub file_conf_mime_types ($self) {
    return $self->{'file_conf_mime_types'};
}


sub file_conf_srm_conf ($self) {
    return $self->{'file_conf_srm_conf'};
}


sub file_conf_php_conf ($self) {
    return $self->{'file_conf_php_conf'};
}


sub bin_httpd ($self) {
    return $self->{'bin_httpd'};
}


sub bin_apachectl ($self) {
    return $self->{'bin_apachectl'};
}


sub bin_suexec ($self) {
    return $self->{'bin_suexec'};
}


sub _clear_cache {
    $multiton = {};
    return;
}

1;

} # --- END Cpanel/ConfigFiles/Apache.pm


{ # --- BEGIN Cpanel/Config/Httpd/Vendor.pm
package Cpanel::Config::Httpd::Vendor;


use strict;
use warnings;

# use Cpanel::Config::Httpd::EA4 ();
# use Cpanel::LoadFile           ();

our $LITESPEED_PATH               = '/usr/local/lsws/bin/lshttpd';
our $LITESPEED_BUILD_VERSION_FILE = '/usr/local/lsws/autoupdate/build';


sub httpd_vendor_info {
    if ( -x $LITESPEED_PATH ) {
        require Cpanel::CachedCommand;
        my $lshttpd_v = Cpanel::CachedCommand::cachedcommand( $LITESPEED_PATH, '-v' );
        if ( $lshttpd_v =~ m{LiteSpeed/(\S+)\s+(\S+)} ) {
            my $version = $1;
            my $is_open = $2;
            $is_open =~ tr{A-Z}{a-z};
            if ( $is_open eq 'open' ) {
                return ( 'openlitespeed', $version );
            }
            my $patch_version = Cpanel::LoadFile::loadfile($LITESPEED_BUILD_VERSION_FILE) || "";
            chomp($patch_version);
            if ( length $patch_version && $patch_version !~ tr{0-9}{}c ) {
                $version .= '.' . $patch_version;
            }
            return ( 'litespeed', $version );
        }
    }

    if ( -r '/usr/local/lsws/VERSION' ) {
        my $version       = Cpanel::LoadFile::loadfile('/usr/local/lsws/VERSION');
        my $patch_version = Cpanel::LoadFile::loadfile($LITESPEED_BUILD_VERSION_FILE);
        if ( length $patch_version && $patch_version !~ tr{0-9}{}c ) {
            $version .= '.' . $patch_version;
        }
        return ( 'litespeed', $version );
    }

    if ( Cpanel::Config::Httpd::EA4::is_ea4() ) {
        require Cpanel::ConfigFiles::Apache;    # because httpd_vendor_info() is called at BEGIN time so scripts/updatenow.static-cpanelsync INIT import is too late and the call the facade fails (CPANEL-28458 should address this)
        my $httpd = Cpanel::ConfigFiles::Apache->new->bin_httpd();
        if ( -x $httpd ) {
            require Cpanel::CachedCommand;
            my $httpd_v = Cpanel::CachedCommand::cachedcommand( $httpd, '-v' );
            if ( $httpd_v =~ m{Server\s+version:\s+Apache/([0-9]+\.[0-9]+\.[0-9]+)\s+\(cPanel\)} ) {
                my $apv = $1;
                return ( 'easyapache4', $apv );
            }
        }
    }

    return ( 'unknown', 'unknown' );
}

1;

} # --- END Cpanel/Config/Httpd/Vendor.pm


{ # --- BEGIN Cpanel/Update/Blocker/Always.pm
package Cpanel::Update::Blocker::Always;


use cPstrict;

# use Cpanel::iContact                      ();
# use Cpanel::DIp::MainIP                   ();
# use Cpanel::JSON                          ();
# use Cpanel::LoadFile                      ();
# use Cpanel::LoadModule                    ();
# use Cpanel::NAT                           ();
# use Cpanel::Pack                          ();
# use Cpanel::SafeDir::MK                   ();
# use Cpanel::SafeRun::Object               ();
# use Cpanel::Sys::Uname                    ();
# use Cpanel::Server::Type                  ();
# use Cpanel::TempFile                      ();
# use Cpanel::TimeHiRes                     ();
# use Cpanel::Update::Blocker::Base         ();    # PPI USE OK - Used for inheritance of common blocker logic.
# use Cpanel::Update::Blocker::CpanelConfig ();    # cpanel.config integrity checks.
# use Cpanel::Update::Blocker::MySQL        ();
# use Cpanel::Update::Blocker::RemoteMySQL  ();
# use Cpanel::Update::Blocker::WorkerNodes  ();
# use Cpanel::Update::Config                ();
# use Cpanel::Version::Compare::Package     ();
# use Cpanel::Version::Tiny                 ();    # PPI USE OK - used an heredoc later - cplint issue CPANEL-37939
# use Cpanel::OS                            ();
# use Cpanel::OS::All                       ();
# use Cpanel::Pkgr                          ();

# use Cpanel::Update::Blocker::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Update::Blocker::Base); }

use Try::Tiny;


sub new {
    die("Try Cpanel::Update::Blocker->new");
}


sub perform_global_checks {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    $self->is_supported_distro() or return;    # No further checks need to be done if we fail here.

    $self->is_license_expired();               # See sub is_license_expired for the dangers of removing this line.

    $self->is_disk_full_staging();

    $self->is_disk_full_ulc();

    $self->is_directory_ro();

    unless ( $ENV{'CPANEL_BASE_INSTALL'} ) {    # we will not get here if rpm is broken
        $self->is_package_manager_sane();
    }

    $self->is_cpanel_config_broken();

    unless ( $ENV{'CPANEL_BASE_INSTALL'} ) {    # yum will be running in the background
        if ( Cpanel::OS::is_yum_based() ) {
            $self->is_yum_locked();
        }
    }

    $self->active_transfer_exists();

    $self->is_remote_mysql_supported();

    $self->is_litespeed_version_insufficient();

    $self->is_supported_openssl();

    $self->are_worker_nodes_ready();

    return 1;
}

sub are_worker_nodes_ready ($self) {
    my $prob = Cpanel::Update::Blocker::WorkerNodes::get_workers_problem(
        logger         => $self->logger(),
        target_version => $self->_Target_version(),
    );

    $self->block_version_change($prob) if length $prob;

    return;
}


sub is_license_expired {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    $self->logger->info("Checking license\n");

    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        $self->logger->info('Installation in progress. Skipping license check.');
        return;
    }

    if ( !-e '/usr/local/cpanel/version' && !-e '/usr/local/cpanel/cpanel' && !-e '/usr/local/cpanel/cpkeyclt' && !-e '/usr/local/cpanel/cpanel.lisc' ) {
        $self->logger->warning('Your system appears unstable. Bypassing license check.');
        return;
    }

    system '/usr/local/cpanel/scripts/rdate';
    my $now = time();

    if ( !-e '/usr/local/cpanel/cpanel.lisc' ) {
        system '/usr/local/cpanel/cpkeyclt' if -x '/usr/local/cpanel/cpkeyclt';    # Attempt to create the license file once before failing
        if ( !-e '/usr/local/cpanel/cpanel.lisc' ) {

            $self->block_version_change( 'No license file found. Your cPanel software will not function properly. Updates will be blocked until you fix this.', 'quiet_error' );
            return;
        }
    }

    my $updates_expire_time = 0;

    my $cplisc_fh;
    if ( !open( $cplisc_fh, '<', '/usr/local/cpanel/cpanel.lisc' ) ) {
        $self->block_version_change("Unable to read license file: $!\nYou may need to execute /usr/local/cpanel/cpkeyclt via the command line to rectify this issue.");
        return;
    }

    while ( my $line = readline($cplisc_fh) ) {
        if ( $line =~ m/^updates_expire_time:\s+(\d+)/ ) {
            $updates_expire_time = $1;
            last;
        }
    }
    close($cplisc_fh);

    if ( $updates_expire_time && $now > $updates_expire_time ) {

        my $msg = <<'EOS';



!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

cPanel software update unable to continue. This server's license is
no longer eligible for software updates. In order to update this
server's cPanel software, you will need to purchase an update
extension for this server. Please contact customer service for more
information on software updates and update extensions.

https://tickets.cpanel.net/submit/?reqtype=cs

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



EOS

        foreach my $line ( split( /\n/, $msg ) ) {
            $self->logger->warning($line);    # this could also be done as a single warning call
        }

        $self->block_version_change("Server's license is no longer eligible for updates.");
    }

    $self->logger->info("License file check complete\n");
    return;
}


sub is_supported_distro ($self) {

    return 1 if Cpanel::OS::is_supported();

    my $eol_advice = Cpanel::OS::eol_advice();

    my $distro_list = Cpanel::OS::All::advertise_supported_distros();

    my $upgrade_your_os = q[Upgrade your OS];

    my $minor = Cpanel::OS::support_needs_minor_at_least_at();
    if ( defined $minor ) {
        $upgrade_your_os .= sprintf( " to %d.%d or later", Cpanel::OS::major(), $minor );    ## no critic(Cpanel::CpanelOS)
    }

    my $legacy_message = <<"EOS";
Newer releases of cPanel & WHM are not compatible with your operating system.
$upgrade_your_os, or use the <a href="../scripts2/updateconf">Update Preferences screen</a>
to select a Long-Term Support release for use with your OS. cPanel & WHM $Cpanel::Version::Tiny::VERSION_BUILD
supports $distro_list only.
Please see our <a href="https://go.cpanel.net/eol" target="_blank">OS End of Life policy</a> for more information.
EOS
    $legacy_message .= "$eol_advice\n" if length $eol_advice;

    $legacy_message =~ s{\n}{ }g;

    $self->block_version_change($legacy_message);

    return 0;
}

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

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

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

    my @ret;

    my $count = _max( scalar @{$a}, scalar @{$b} );

    for ( my $i = 0; $i < $count; $i++ ) {
        push @ret, defined $a->[$i] ? $a->[$i] : undef;
        push @ret, defined $b->[$i] ? $b->[$i] : undef;
    }

    return \@ret;
}

sub _statfs {
    my ( $self, $path ) = @_;

    my @MEMBERS = qw(
      f_type f_bsize f_blocks f_bfree f_bavail f_files
      f_ffree f_fsid f_namelen f_frsize f_flags f_spare
    );

    my %TEMPLATES = (
        'i386'   => [qw(L L L L L L L L L L L LLLL)],
        'x86_64' => [qw(Q Q Q Q Q Q Q Q Q Q Q QQQQ)]
    );

    my %SYSCALL_IDS = (
        'i386'   => 99,
        'x86_64' => 137
    );

    my @uname = Cpanel::Sys::Uname::get_uname_cached();

    unless ( defined $SYSCALL_IDS{ $uname[4] } ) {
        die "Unsupported platform '$uname[4]'";
    }

    my $struct = Cpanel::Pack->new( _zip( \@MEMBERS, $TEMPLATES{ $uname[4] } ) );
    my $buf    = $struct->malloc();

    return syscall( $SYSCALL_IDS{ $uname[4] }, $path, $buf ) < 0
      ? ()
      : $struct->unpack_to_hashref($buf);
}


sub is_disk_full_ulc {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my $path =
        -e '/usr/local/cpanel' ? '/usr/local/cpanel'
      : -e '/usr/local'        ? '/usr/local'
      :                          '/usr';

    my $statfs = $self->_statfs($path);
    my $space  = $statfs->{'f_bsize'} * $statfs->{'f_bfree'};
    my $inodes = $statfs->{'f_ffree'};

    my @ignore_free_inode_types = (
        0x9123683E,    # BTRFS_SUPER_MAGIC from include/linux/magic.h -- UNSUPPORTED, always reports 0 free, OK to ignore because inodes are effectively unlimited
    );
    my $ignore_free_inodes = ( grep { $statfs->{'f_type'} == $_ } @ignore_free_inode_types ) ? 1 : 0;

    if ( $space < 1073741824 ) {
        $space = sprintf( "%1.02f", $space / 1024 / 1024 );
        $self->block_version_change("cPanel & WHM cannot update due to insufficient disk space. The system detected $space MB free, but requires at least 1 GB free at '$path' in order to successfully update.");
        return;
    }

    if ( !$ignore_free_inodes && $inodes < 360000 ) {
        $self->block_version_change("cPanel & WHM cannot update due to insufficient available inodes. The system detected $inodes free inodes, but requires at least 360,000 free inodes at '$path' in order to successfully update.");
        return;
    }

    return 1;
}


sub is_disk_full_staging {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my $path;

    if ( $self->{'upconf_ref'}->{'STAGING_DIR'} and $self->{'upconf_ref'}->{'STAGING_DIR'} ne '/usr/local/cpanel' ) {
        $path = $self->{'upconf_ref'}->{'STAGING_DIR'};
    }
    else {
        $path =
            -e '/usr/local/cpanel' ? '/usr/local/cpanel'
          : -e '/usr/local'        ? '/usr/local'
          :                          '/usr';
    }

    Cpanel::SafeDir::MK::safemkdir($path) if !-d $path;
    my $statfs = $self->_statfs($path) or return;
    my $space  = $statfs->{'f_bsize'} * $statfs->{'f_bfree'};

    if ( $space < 3221225472 ) {
        $space = sprintf( "%1.02f", $space / 1024 / 1024 / 1024 );
        my ( $public_ip, $subject, $message );
        eval { $public_ip = Cpanel::NAT::get_public_ip( Cpanel::DIp::MainIP::getmainip() ); };

        my $update_preferences_url = 'https://' . ( $public_ip ? $public_ip : 'SERVER_IP' ) . ':2087/scripts2/updateconf';
        my $new_staging_dir        = $self->_find_better_staging_location();
        if ($new_staging_dir) {
            $self->{'upconf_ref'}->{'STAGING_DIR'} = $new_staging_dir;
            Cpanel::Update::Config::save( $self->{'upconf_ref'} );

            $subject = "Upgrade blocked: Not enough disk space: '$path'. Automatically determined a new staging directory for the next upcp run.";
            $message = <<END_OF_MESSAGE;
cPanel & WHM cannot update due to insufficient disk space in the staging directory, "$path". The system requires 3 GB to update; this directory only has $space GB available.

The system automatically selected "$new_staging_dir" as a staging directory. All update data will be stored here. If you take no action, the system will continue to use this directory for future updates. To change the location of the staging directory, use $update_preferences_url .

END_OF_MESSAGE

            $self->block_version_change(
                "cPanel & WHM cannot update due to insufficient disk space in the staging directory, '$path'. The system requires 3 GB to update; this directory only has ${space} GB available. The system automatically selected '$new_staging_dir' as a staging directory. All update data will be stored here. If you take no action, the system will continue to use this directory for future updates. To change the location of the staging directory, use WHM's <a href=\"../scripts2/updateconf\">Update Preferences interface</a>."
            );
        }
        else {
            $subject = "Upgrade blocked: Not enough disk space: '$path'.";
            $message = <<END_OF_MESSAGE;
cPanel & WHM cannot update due to insufficient disk space in the staging directory, "$path". The system requires 3 GB to update; this directory only has $space GB available

The system failed to find a new staging directory with enough space to update. You can either clear enough disk space or select a new staging directory with enough disk space at $update_preferences_url .

END_OF_MESSAGE

            $self->block_version_change(
                "cPanel & WHM cannot update due to insufficient disk space in the staging directory, '$path'. The system requires 3 GB to update; this directory only has $space GB available. The system failed to find a new staging directory with enough space to update. You can either clear enough disk space or select a new staging directory with enough disk space at <a href=\"../scripts2/updateconf\">Update Preferences interface</a>."
            );
        }

        Cpanel::iContact::icontact(
            'application'              => 'upcp',
            'subject'                  => "[$public_ip] $subject",
            'message'                  => $message,
            'prepend_hostname_subject' => 1,
        );
        return;
    }

    return 1;
}

sub _find_better_staging_location {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my @home_mounts;
    eval {
        Cpanel::LoadModule::load_perl_module('Cpanel::Filesys::Home');
        @home_mounts = Cpanel::Filesys::Home::get_all_homedirs();
    };
    return if ( !scalar @home_mounts || $@ );

    foreach my $largest_mountpoint (@home_mounts) {
        if ( Cpanel::Update::Config::validate_staging_dir($largest_mountpoint) ) {
            my $statfs   = $self->_statfs($largest_mountpoint) or return;
            my $avail_gb = ( $statfs->{'f_bsize'} * $statfs->{'f_bfree'} ) / 1048576 / 1024;

            return $largest_mountpoint if $avail_gb > 3;
        }
    }
    return;
}


our @system_directories = qw{ /etc /var /usr/local /usr/bin /tmp /var/tmp };

our @optional_directories = qw{ /var/cpanel /usr/local/cpanel /usr/local/bin /var/lib/rpm };

sub is_directory_ro {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my $ok = 1;

    my @all_directories = @system_directories;
    push @all_directories, grep { -d $_ } @optional_directories;

    foreach my $dir (@all_directories) {
        unless ( $self->_test_path_is_rw($dir) ) {
            $self->block_version_change("Can not upgrade because $dir is not writable");
            $ok = 0;
        }
    }

    return $ok;
}

our $rw_testfile = '/CPANEL_TEST_FS_IS_RW';

sub _create_temporary_directory {
    my ( $self, $path ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    $path or return;

    my $temp = Cpanel::TempFile->new;
    $path = $temp->dir( { path => $path } ) . $rw_testfile;

    return ( $temp, $path );
}

sub _test_path_is_rw {
    my ( $self, $dir ) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    $dir or return;
    $dir =~ s/\/$//;    # Strip trailing slash.
    $dir = "/" if !$dir;

    return unless -d $dir;

    my ( $temp, $path );

    eval {
        ( $temp, $path ) = $self->_create_temporary_directory($dir);
        open( my $fh, '>', $path ) or die "failed to open $path: $!";
        print {$fh} 'abc'          or die "failed to print to $path: $!";
        close($fh)                 or die "failed to close $path: $!";
    };
    my $error = $@;

    my $file_size = -s $path // 0;
    unlink $path;
    return unless $file_size == 3;
    return if $error;
    return 1;
}

sub is_package_manager_sane ($self) {
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my ( $db_works, $msg ) = Cpanel::Pkgr::verify_package_manager_can_install_packages( $self->{'logger'} );
    return 1 if $db_works;

    $msg //= '';
    $self->block_version_change("Your Packaging System does not seem in a sane state at the moment: $msg");

    return;
}

sub is_cpanel_config_broken {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my $cpconfig = Cpanel::Update::Blocker::CpanelConfig->new( { 'logger' => $self->logger() } );

    $cpconfig->cleanse_cpanel_config_entries();

    my $mysql    = Cpanel::Update::Blocker::MySQL->new( { 'logger' => $self->logger(), 'cpconfig' => $cpconfig->cpconfig() } );
    my $mysql_ok = $mysql->is_mysql_version_valid();
    if ( !$mysql_ok ) {
        my $reason = $mysql->{'mysql-reason'} || 'The mysql-version value in /var/cpanel/cpanel.config either is invalid or references an unsupported MySQL/MariaDB version. Upgrade to a newer MySQL/MariaDB version, then attempt to update again. You can upgrade your system’s MySQL/MariaDB here: <a href="../scripts/mysqlupgrade">MySQL/MariaDB Upgrade</a>';
        $self->block_version_change($reason);
        $cpconfig->{'invalid'}++;
    }

    my $nameserver_ok = $cpconfig->is_local_nameserver_type_valid();
    if ( !$nameserver_ok ) {
        $self->block_version_change('The local_nameserver_type value in /var/cpanel/cpanel.config is invalid. Valid values are powerdns, mydns, nsd, bind or you can leave it blank. You can change the value here: <a href="../scripts/nameserverconfig">Nameserver Selection</a>');
    }

    my $dnstype = $cpconfig->get_local_nameserver_type();
    if ( defined $dnstype && $dnstype eq 'powerdns' && Cpanel::OS::major() == 6 ) {    ## no critic(Cpanel::CpanelOS)
        $self->block_version_change( "Systems that run " . Cpanel::OS::display_name() . " no longer support $dnstype" );
    }

    my $mailserver_ok = $cpconfig->is_mailserver_valid();
    if ( !$mailserver_ok ) {
        $self->block_version_change('The mailserver value in /var/cpanel/cpanel.config is invalid. Valid values are dovecot or disabled. You can change the value here: <a href="../scripts/mailserverconfig">Mailserver Configuration</a>');
    }

    my $ftpserver_ok = $cpconfig->is_ftpserver_valid();
    if ( !$ftpserver_ok ) {
        $self->block_version_change('The ftpserver value in /var/cpanel/cpanel.config is invalid. Valid values are pure-ftpd or proftpd. You can change the value here: <a href="../scripts2/tweakftp">FTP Server Selection</a>');
    }

    return $cpconfig->is_legacy_cpconfig_invalid();
}


our $YUM_WAIT_SLEEP_INTERVAL = 5;    # for testing

sub is_yum_locked {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    my $timeout      = $self->_yum_lock_timeout;
    my $counter      = 0;
    my $yum_pid_file = '/var/run/yum.pid';
    while ( -e $yum_pid_file ) {
        my $pid_in_file = Cpanel::LoadFile::loadfile($yum_pid_file);
        if ( $pid_in_file && !kill( 0, $pid_in_file ) ) {
            unlink($yum_pid_file) && return 1;
        }
        elsif ( $counter > $timeout ) {
            $self->block_version_change("Cannot upgrade because yum is locked (/var/run/yum.pid has existed for 10+ minutes).");
            return;
        }
        Cpanel::TimeHiRes::sleep($YUM_WAIT_SLEEP_INTERVAL);
        $counter += $YUM_WAIT_SLEEP_INTERVAL;
    }
    return 1;
}


sub _yum_lock_timeout {
    my ( $self, $timeout ) = @_;
    $self->{'_yum_lock_timeout'} = $timeout if defined $timeout;
    return $self->{'_yum_lock_timeout'} || 600;
}


sub active_transfer_exists {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    if ( Cpanel::Server::Type::is_dnsonly() ) {
        $self->logger->info('DNSONLY detected.');
        return;
    }

    return if $ENV{CPANEL_BASE_INSTALL};

    my $script_path = '/usr/local/cpanel/scripts/transfer_in_progress';

    return if !-e $script_path;

    my $saferun_obj = Cpanel::SafeRun::Object->new(
        program      => $script_path,
        timeout      => 86400,
        read_timeout => 86400,
        args         => ['--serialize_output'],
    );

    if ( $saferun_obj->CHILD_ERROR() ) {
        $self->logger->warn( "The script '$script_path' failed to check for active transfers due to an error: " . $saferun_obj->stderr() );
        return;
    }

    my $output = $saferun_obj->stdout();

    if ( !length $output ) {
        $self->logger->warn("The script '$script_path' failed to return any output.");
        return;
    }

    my $err;
    my $response;
    try {
        $response = Cpanel::JSON::Load($output);
    }
    catch {
        $err = $_;
    };

    if ($err) {
        $self->logger->warn("The script '$script_path' failed to return valid output: $err");
        return;
    }

    return if !$response->{transfer_exists};

    $self->block_version_change('There are active transfers to this server. The system will block updates until those transfers end or a user aborts them. Please read our <a href="https://go.cpanel.net/whmdocsTransferTool" target="_blank">Transfer Tool documentation</a> for more information.');

    return;
}

sub is_remote_mysql_supported {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call.');

    return if $ENV{'CPANEL_BASE_INSTALL'};

    my $remote_mysql_obj = Cpanel::Update::Blocker::RemoteMySQL->new( { 'logger' => $self->logger } );

    return unless $remote_mysql_obj->is_remote_mysql();

    $self->logger->info('Checking if remote mysql server is supported');

    my $err;
    try {
        $remote_mysql_obj->is_mysql_supported_by_cpanel();
    }
    catch {
        $err = $_ || 'cPanel & WHM does not support your remote MySQL/MariaDB version.';
    };

    if ($err) {
        $self->block_version_change($err);
        return;
    }

    $self->logger->info('Remote mysql server check is complete');
    return 1;
}

sub is_litespeed_version_insufficient {
    my ($self) = @_;

    require Cpanel::Config::Httpd::Vendor;
    my ( $is_lsws, $version ) = Cpanel::Config::Httpd::Vendor::httpd_vendor_info();

    return 0 unless grep { $_ eq $is_lsws } qw{litespeed};

    my ( $maj, $min, $build ) = split( /\./, $version );
    if ( $maj <= 5 && $min <= 3 && $build < 6 ) {
        $self->block_version_change("LiteSpeed WebServer version must be greater than 5.3.5");
        return 1;
    }
    $self->logger->info('LiteSpeed version check is complete');
    return 0;
}


sub is_supported_openssl ($self) {

    return if $ENV{'CPANEL_BASE_INSTALL'};

    my $minimum_required_version = Cpanel::OS::openssl_minimum_supported_version() or return;

    my $openssl_version = Cpanel::Pkgr::get_package_version('openssl');

    if ( Cpanel::Version::Compare::Package::version_cmp( $openssl_version, $minimum_required_version ) == -1 ) {
        $self->block_version_change(qq{This system is running an outdated version of OpenSSL ($openssl_version), which will need to be updated to at least $minimum_required_version to continue.});
        return;
    }

    return;
}

1;

} # --- END Cpanel/Update/Blocker/Always.pm


{ # --- BEGIN Cpanel/Update/Blocker/LTS.pm
package Cpanel::Update::Blocker::LTS;


use strict;
use warnings;

# use Cpanel::Update::Blocker::Base ();    # PPI USE OK - Used for inheritance of common blocker logic.

# use Cpanel::Update::Blocker::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Update::Blocker::Base); }

use Try::Tiny;


sub new {
    die("Try Cpanel::Update::Blocker->new");
}



sub perform_lts_specific_checks {
    my ($self) = @_;
    ref $self eq 'Cpanel::Update::Blocker' or die('This is a method call for Cpanel::Update::Blocker');


    return;
}

1;

} # --- END Cpanel/Update/Blocker/LTS.pm


{ # --- BEGIN Cpanel/Update/Blocker.pm
package Cpanel::Update::Blocker;


use strict;
use warnings;

# use Cpanel::Update::Blocker::Base   ();    # PPI USE OK - Used for inheritance of common blocker logic.
# use Cpanel::Update::Blocker::Always ();    # PPI USE OK - Used for inheritance of blocker checks that always happen.
# use Cpanel::Update::Blocker::LTS    ();    # PPI USE OK - Used for inheritance of common blocker logic.

# use Cpanel::Update::Blocker::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Update::Blocker::Base); }
# use Cpanel::Update::Blocker::Always();
BEGIN { push @ISA, qw(Cpanel::Update::Blocker::Always); }
# use Cpanel::Update::Blocker::LTS();
BEGIN { push @ISA, qw(Cpanel::Update::Blocker::LTS); }



sub is_upgrade_blocked {
    my ($self) = @_;
    ref $self eq __PACKAGE__ or die('This is a method call.');

    my $keep_checking = $self->perform_global_checks();

    if ($keep_checking) {

        $self->perform_lts_specific_checks() unless $ENV{CPANEL_BASE_INSTALL};

        if ( $self->delay_upgrade() == 8 ) {
            $self->generate_blocker_file(0);
            return $self->is_fatal_block() + 1;
        }
    }

    $self->generate_blocker_file(1);

    return $self->is_fatal_block();
}

1;

} # --- END Cpanel/Update/Blocker.pm


{ # --- BEGIN Cpanel/Update/Tiers.pm
package Cpanel::Update::Tiers;


use strict;
use warnings;

# use Cpanel::JSON                         ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::Update::Config               ();
# use Cpanel::Version::Full                ();
# use Cpanel::Version::Compare             ();

use Scalar::Util ();

sub new {
    my ( $class, %args ) = @_;

    my $self = {};
    $self->{'tiers_url'}  = $args{'tiers_url'}  || '/cpanelsync/TIERS.json';
    $self->{'tiers_path'} = $args{'tiers_path'} || '/etc/cpanel/TIERS.json';

    $self->{'cache_expiration_time'} = $args{'cache_expiration_time'} || $ENV{'CPANEL_BASE_INSTALL'} ? 6 * 3600 : 300;

    $self->{'logger'} = $args{'logger'} if $args{'logger'};

    return bless $self, $class;
}


sub logger {
    my $self = shift || die("logger is a method call");

    require Cpanel::Logger;
    $self->{'logger'} ||= Cpanel::Logger->new();
    return $self->{'logger'};
}


sub sync_tiers_file {
    my $self = shift || die("sync_tiers_file is a method call");

    require Cpanel::Config::Sources;
    my $remote_tiers_host = Cpanel::Config::Sources::loadcpsources()->{'HTTPUPDATE'};

    my $tiers_json;
    {
        require Cpanel::Alarm;
        require Cpanel::HttpRequest;
        my $alarm = Cpanel::Alarm->new( 45, sub { die 'Timeout while fetching version information.' } );
        $tiers_json = Cpanel::HttpRequest->new(
            'logger'     => ( Scalar::Util::blessed( $self->logger() ) ? $self->logger() : undef ),    # undef restores the legacy behavior
            'hideOutput' => 1,
            'die_on_404' => 1,
            'retry_dns'  => 0,
        )->request(
            'host'   => $remote_tiers_host,
            'url'    => $self->{'tiers_url'},
            'signed' => 1,
        );
    }

    if ( !$tiers_json ) {
        die("Error downloading ${remote_tiers_host}/cpanelsync/TIERS.json");
    }

    my $json_hr = Cpanel::JSON::Load($tiers_json) or die("Could not load ${remote_tiers_host}/cpanelsync/TIERS.json: $@");

    if ( !-e $self->{'tiers_path'} ) {
        require File::Basename;
        my ( $basename, $dirname, $suffix ) = File::Basename::fileparse( $self->{'tiers_path'} );

        if ( !-e $dirname ) {
            require Cpanel::SafeDir::MK;
            Cpanel::SafeDir::MK::safemkdir( $dirname, 0755 );
        }
    }
    return 0 unless Cpanel::FileUtils::Write::JSON::Lazy::write_file( $self->{'tiers_path'}, $json_hr, 0644 );

    return 1;
}


sub tiers_hash {
    my $self = shift || die("tiers_hash is a method call");

    return $self->{'tiers_hash'} if exists $self->{'tiers_hash'};

    eval {
        if ( $self->tiers_cache_expired() ) {
            $self->sync_tiers_file();
        }
    };
    if ($@) {
        my $error = 'Tried to sync version ' . $self->{'tiers_path'} . ' file but failed: ' . $@;
        if ( $self->logger->can('error') ) {
            $self->logger->error($error);
        }
        else {
            $self->logger->warn($error);
        }
        return;
    }

    $self->{'tiers_hash'} = Cpanel::JSON::SafeLoadFile( $self->{'tiers_path'} );
    return $self->{'tiers_hash'};
}


sub tiers_cache_expired {
    my $self = shift || die("tiers_cache_expired is a method call");

    if ( !-e $self->{'tiers_path'} || -z _ || ( ( stat(_) )[9] + $self->{'cache_expiration_time'} ) < time ) {
        return 1;
    }
    else {
        return 0;
    }
}


sub get_current_lts_expiration_status {
    my $self = shift || die("get_current_lts_expiration_status is a method call");
    my %results;

    $results{'full_version'} = Cpanel::Version::Full::getversion();
    $results{'expiration'}   = $self->get_expires_for_version( $results{'full_version'} );

    return unless defined $results{'expiration'};

    $results{'expires_in_next_three_months'} = 0;
    my $time = time;

    my $time_three_months_from_now = $time + 3600 * 24 * 90;

    if ( $results{'expiration'} && ($time_three_months_from_now) > $results{'expiration'} ) {
        $results{'expires_in_next_three_months'} = 1;
    }

    return \%results;
}

sub get_build_info {
    my ( $self, $version ) = @_;

    return $self->_visit_major_builds_from_version(
        $version,
        sub {
            my ($build) = @_;

            return $build if $build && defined $build->{'build'} && $build->{'build'} eq $version;
            return;
        }
    );
}

sub _visit_major_builds_from_version {
    my ( $self, $version, $visit ) = @_;

    my ($major) = $version =~ m/^11\.([0-9]+)\.[0-9]+\.[0-9]+$/;
    $major or return;        # Not a valid version. Obviously not stable :)
    $major += $major % 2;    #Make it even.
    $major = "11.$major";

    my $tiers_hr    = $self->tiers_hash()            or return;
    my $major_array = $tiers_hr->{'tiers'}->{$major} or return;

    return unless ref $major_array eq 'ARRAY';

    foreach my $build (@$major_array) {
        my $got = $visit->($build);
        return $got if $got;
    }

    return;
}

sub get_expires_for_version {
    my ( $self, $version ) = @_;

    die("get_expires_for_version is a method call") unless ref $self;
    return                                          unless defined $version;

    my $build_info = $self->get_build_info($version) or return;
    return $build_info->{'expires'} if defined $build_info->{'expires'};


    return $self->_visit_major_builds_from_version(
        $version,
        sub {
            my ($build) = @_;
            return unless $build;
            if ( $build->{is_lts} && defined $build->{expires} ) {
                return $build->{expires};
            }
            return;
        }
    );
}

sub get_current_tier {
    my $self = shift || die("get_current_tier is a method call");

    return $self->{'current_update_tier'} if $self->{'current_update_tier'};

    my $tier = Cpanel::Update::Config::load()->{'CPANEL'};

    if ( $tier =~ m{^[0-9]+$} ) {
        $tier = '11.' . $tier;
    }

    return $self->{'current_update_tier'} = $tier;
}

sub is_explicit_version {
    my ( $self, $tier ) = @_;
    $self || die("is_explicit_version is a method call");

    return unless defined $tier && length $tier;

    return ( $tier =~ m/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ ) ? 1 : 0;
}


sub get_remote_version_for_tier {
    my ( $self, $tier ) = @_;
    $self || die("get_remote_version_for_tier is a method call");

    return unless defined $tier && length $tier;

    return $tier if $self->is_explicit_version($tier);

    my $tiers_hash = $self->tiers_hash;

    if ( $tier =~ m/^([0-9]+\.[0-9]+)$/ ) {
        my $LTS = "$1";    # Be sure to stringify it.

        ref $tiers_hash->{'tiers'} eq 'HASH' or return;
        my $major_versions = $tiers_hash->{'tiers'}->{$LTS};

        ref $major_versions eq 'ARRAY' or return;
        foreach my $build (@$major_versions) {
            next unless $build->{'is_main'};

            return $build->{'build'};
        }

        return;            # Couldn't find an is_main inside $LTS
    }


    if ( $tier =~ m/^([0-9]+\.[0-9]+\.[0-9]+)$/ ) {
        my $dev_branch = "$1";    # Be sure to stringify it.
        if ( ref $tiers_hash->{'branch'} eq 'HASH' ) {
            my $build = $tiers_hash->{'branch'}->{$dev_branch};
            if ( $build && ref $build eq 'ARRAY' ) {
                if ( $build->[0] && ref $build->[0] eq 'HASH' ) {
                    return $build->[0]->{'build'};
                }
            }
        }
    }

    ref $tiers_hash->{'tiers'} eq 'HASH' or return;
    foreach my $versions_in_major ( values %{ $tiers_hash->{'tiers'} } ) {
        ref $versions_in_major eq 'ARRAY' or next;
        foreach my $release (@$versions_in_major) {
            ref $release eq 'HASH' or next;

            $release->{'named'} or next;

            ref $release->{'named'} eq 'ARRAY' or next;
            foreach my $name ( @{ $release->{'named'} } ) {

                return $release->{'build'} if $name eq $tier;
            }
        }
    }

    return;
}

sub get_main_for_version {
    my ( $self, $current_version ) = @_;
    $self || die("get_main_for_version is a method call");

    $current_version                                      or return;
    $current_version =~ m{^11\.([0-9]+)\.[0-9]+\.[0-9]+$} or return;

    my $major_version = $1;
    $major_version++ if ( $major_version % 2 );    # Make it even if it's odd.

    my $tiers_hash = $self->tiers_hash;
    ref $tiers_hash->{'tiers'} eq 'HASH' or return;

    my $build_list = $tiers_hash->{'tiers'}->{"11.$major_version"} or return;
    ref $build_list eq 'ARRAY'                                     or return;

    foreach my $build (@$build_list) {
        next unless $build->{'is_main'};
        return $build->{'build'};    # We found the is_main for 11.76.0.4 (or whatver)
    }

    return;                          #If there's no LTS forwad of #
}

sub get_lts_for {
    my ( $self, $current_version, $next ) = @_;
    $self || die("get_lts_for is a method call");

    $current_version                             or return;
    $current_version =~ m{^11\.(\d+)\.\d+\.\d+$} or return;

    my $major_version = $1;
    $major_version++ if ( $major_version % 2 );    # Make it even if it's odd.

    $major_version += 2 if ($next);                # Find the next LTS , not the current one

    my $tiers_hash = $self->tiers_hash;
    ref $tiers_hash->{'tiers'} eq 'HASH' or return;

    foreach my $step ( 0 .. 50 ) {
        my $forward_major = sprintf( "11.%02d", $major_version + $step * 2 );

        my $major_versions = $tiers_hash->{'tiers'}->{$forward_major} or next;

        ref $major_versions eq 'ARRAY' or next;
        foreach my $build (@$major_versions) {
            next unless $build->{'is_lts'};
            return $build->{'build'};
        }
    }

    return;    #If there's no LTS forwad of #
}

sub get_update_availability {
    my $self = shift || die("get_update_availability is a method call");

    my $current_tier    = $self->get_current_tier();
    my $current_version = Cpanel::Version::Full::getversion();

    my $newest_version = $self->get_remote_version_for_tier($current_tier);

    $current_version =~ s{^11\.}{};
    $newest_version  =~ s{^11\.}{} if defined $newest_version;

    return {
        'tier'             => $current_tier,
        'current_version'  => $current_version,
        'newest_version'   => $newest_version,
        'update_available' => Cpanel::Version::Compare::compare( $newest_version, '>', $current_version ) ? 1 : 0,
    };
}

sub is_version_stable_release_or_lts {
    my ( $self, $version ) = @_;

    $version or return;

    my $tiers_hr = $self->tiers_hash;
    ref $tiers_hr->{'tiers'} eq 'HASH' or return;

    my $build = $self->get_build_info($version) or return;

    return unless $build->{'named'};
    return if ref $build->{'named'} ne 'ARRAY';

    foreach my $tier ( @{ $build->{'named'} } ) {
        next unless $tier;
        return 1 if lc($tier) =~ m/^(?:stable|release|lts)$/;
    }

    return;
}

sub get_flattened_hash {
    my $self = shift || die("get_flattened_hash is a method call");

    my $remote_tiers_info;
    my %tiers;

    my $tiers_hr = $self->tiers_hash;
    ref $tiers_hr->{'tiers'} eq 'HASH' or return;
    foreach my $major ( keys %{ $tiers_hr->{'tiers'} } ) {
        my $versions_in_major = $tiers_hr->{'tiers'}->{$major};
        ref $versions_in_major eq 'ARRAY' or next;
        foreach my $release (@$versions_in_major) {
            ref $release eq 'HASH' or next;

            if ( $release->{'is_main'} ) {
                $tiers{"$major"} = $release->{'build'};
            }

            $release->{'named'} or next;

            ref $release->{'named'} eq 'ARRAY' or next;
            foreach my $name ( @{ $release->{'named'} } ) {
                $tiers{$name} = $release->{'build'};
            }
        }
    }

    return \%tiers;
}

1;

} # --- END Cpanel/Update/Tiers.pm


{ # --- BEGIN Cpanel/Usage.pm
package Cpanel::Usage;






my $g_prefs;    # Ref to hash containing up to three boolean preferences, as follows:


$Cpanel::Usage::VERSION = '1.08';

sub version {    # Reports our current revision number.
    $Cpanel::Usage::VERSION;
}


sub wrap_options {
    my $arg1 = $_[0];
    $g_prefs = {};
    if ( defined $arg1 && ( ref $arg1 ) =~ /\bHASH\b/ ) {    # hash of preferences
        $g_prefs = $arg1;
        shift;
    }
    my ( $ar_argv, $cr_usage, $hr_opts ) = @_;
    getoptions( usage( $ar_argv, $cr_usage ), $hr_opts );
}


sub usage {
    my ( $ar_argv, $cr_usage ) = @_;
    foreach my $arg (@$ar_argv) {
        if ( $arg =~ /^-+(h|help|usage)$/ ) {
            if ( defined($cr_usage) ) {
                &$cr_usage();
            }
            return 1;
        }
    }

    $ar_argv;
}

sub getoptions {
    my ( $ar_cmdline, $hr ) = @_;

    my $non_opt_arg_seen = "";


    return $ar_cmdline if ( ref $ar_cmdline || "" ) !~ /\bARRAY\b/;


    if ( !$#$ar_cmdline && $ar_cmdline->[0] eq "1" ) {
        return 1;
    }


    unless ( defined $hr && ( ref $hr ) =~ /\bHASH\b/ ) {
        print "Error: opts must be a hash reference\n";
        return 2;
    }

    my $predefined = keys %{$hr};

    my @cmdline_out = @$ar_cmdline;    # save a copy of the arg array


    if ( !$predefined ) {
        if ( no_switches($ar_cmdline) ) {
            my $i = 0;
            foreach my $arg (@$ar_cmdline) {
                $hr->{ $i++ } = $arg;
            }
            return "";
        }
    }
    if ($predefined) {
        my $default_value = exists $g_prefs->{'default_value'} ? $g_prefs->{'default_value'} : 0;

        foreach my $k ( keys %$hr ) {


            if ( ref( $hr->{$k} ) =~ /^HASH/ ) {
                foreach my $kk ( keys %{ $hr->{$k} } ) {
                    ${ $hr->{$k}->{$kk} } = $default_value unless ( defined ${ $hr->{$k}->{$kk} } );
                }
            }
            else {
                ${ $hr->{$k} } = $default_value unless ( defined ${ $hr->{$k} } );
            }
        }
    }

    my $seen_dash_dash = 0;

    for ( my $i = 0; $i <= $#$ar_cmdline; $i++ ) {
        if ( $ar_cmdline->[$i] eq '--' ) {
            $seen_dash_dash = 1;

        }
        elsif ( !$seen_dash_dash && $ar_cmdline->[$i] =~ /^-+(.+)$/ ) {
            my $o = $1;

            if ( "" ne $non_opt_arg_seen and $g_prefs->{'require_left'} ) {
                print qq{Error: Preference require_left was specified, all opt args must therefore appear first on the command line; option "-$o" found after "$non_opt_arg_seen" violates this rule\n};
                return 3;
            }
            my $eq_value = '';


            if ( $o =~ /(.+?)=(.+)/ ) {
                $o        = $1;
                $eq_value = $2;
                $eq_value =~ s@^\s+@@;
                $eq_value =~ s@\s+$@@;
            }

            if ( $g_prefs->{'strict'} && $predefined && !exists $hr->{$o} ) {
                print qq{Error: While "strict" is in effect, we have encountered option --$o on the command line, an option that was not specified in the opts hash.\n};
                return 4;
            }

            if (    # It is a "lone switch", that is, an
                $eq_value eq '' && ( $i == $#$ar_cmdline
                    || $ar_cmdline->[ $i + 1 ] =~ /^-+.+$/ )
            ) {

                if ( ref( $hr->{$o} ) =~ /^HASH/ ) {

                    foreach my $kk ( keys %{ $hr->{$o} } ) {
                        if ($predefined) {
                            ${ $hr->{$o}->{$kk} }++ if ( exists( $hr->{$o} ) );
                        }
                    }
                }
                else {
                    if ($predefined) {
                        ${ $hr->{$o} }++ if ( exists( $hr->{$o} ) );
                    }
                    else {
                        $hr->{ _multihelp($o) }++;
                    }
                }
            }

            else {    # not a "lone switch"; the next arg might be the value
                if ( ref( $hr->{$o} ) =~ /^HASH/ ) {
                    print "Error: A multi-level option can only be used when implicitly boolean (true), but you have attempted to use a multi-level option with an explicitly specified option argument.\n";

                    return 5;
                }
                if ( $eq_value ne '' ) {    # Sorry, we already have a value for the switch
                    if ($predefined) {
                        ${ $hr->{$o} } = $eq_value if ( exists( $hr->{$o} ) );
                    }
                    else {
                        $hr->{$o} = $eq_value;
                    }
                }
                else {                      # We have no value yet for the switch, so use next arg as the value
                    $cmdline_out[$i] = undef if $g_prefs->{'remove'};
                    ++$i;
                    if ($predefined) {
                        ${ $hr->{$o} } = $ar_cmdline->[$i]
                          if ( exists( $hr->{$o} ) );
                    }
                    else {
                        $hr->{$o} = $ar_cmdline->[$i];
                    }
                }
            }
            $cmdline_out[$i] = undef if $g_prefs->{'remove'};
        }
        else {    # It's a regular (non-hyphen-prefixed) arg, not an option arg
            if ( "" eq $non_opt_arg_seen ) {
                $non_opt_arg_seen = $ar_cmdline->[$i];
            }
        }
    }

    if ( $g_prefs->{'remove'} ) {


        @cmdline_out = grep { defined } @cmdline_out;
        @{$ar_cmdline} = @cmdline_out;
    }

    return "";    # aka 0, successful completion
}


sub _multihelp {    # For internal use only
    my $name = shift;
    return $name =~ /^(h|help|usage)$/ ? 'help' : $name;
}

sub no_switches {
    my $ar = shift;
    return !grep { /^-+.+/ } @{$ar};
}


sub dump_args {
    my $hr_opts = shift;
    require Data::Dumper;
    print Data::Dumper::Dumper($hr_opts);
}

1;


} # --- END Cpanel/Usage.pm


{ # --- BEGIN Cpanel/Update/Now.pm
package Cpanel::Update::Now;


use cPstrict;

use utf8;

use Try::Tiny;

# use Cpanel::Carp                   ();
# use Cpanel::LoadModule             ();
# use Cpanel::Locale::Context        ();
# use Cpanel::SafeDir::RM            ();
# use Cpanel::Hostname               ();
# use Cpanel::Config::Merge          ();
# use Cpanel::Config::Sources        ();
# use Cpanel::Crypt::GPG::VendorKeys ();
# use Cpanel::FileUtils::Copy        ();
# use Cpanel::Binaries               ();
# use Cpanel::ForkAsync              ();
# use Cpanel::Exception              ();
# use Cpanel::FileUtils::TouchFile   ();

# use Cpanel::OS                  ();
# use Cpanel::RPM::Versions::File ();
# use Cpanel::SafeDir::MK         ();
# use Cpanel::SafeFile            ();
# use Cpanel::SafeRun::Object     ();
# use Cpanel::Server::Type        ();
# use Cpanel::Sync::v2            ();
# use Cpanel::Sysup               ();
# use Cpanel::LoadFile            ();
# use Cpanel::Signal              ();
# use Cpanel::TempFile            ();
# use Cpanel::Themes::Get         ();
# use Cpanel::Update::Blocker     ();
# use Cpanel::Update::Config      ();
# use Cpanel::Update::Logger      ();
# use Cpanel::Update::Tiers       ();
# use Cpanel::Usage               ();
# use Cpanel::Version::Compare    ();
# use Cpanel::Version::Tiny       ();
# use Cpanel::iContact            ();
use File::Basename              ();
use IO::Handle                  ();
# use Cpanel::Sys::Hostname       ();

# use Cpanel::PwCache::Build ();    # PPI NO PARSE - needed for install

# use Cpanel::ConfigFiles::RpmVersions ();

our $FASTEST_MIRROR_CNF_FILE = '/etc/yum/pluginconf.d/fastestmirror.conf';

our $FASTEST_MIRROR_MAX_THREADS = 65;

our $FASTEST_MIRROR_SOCKET_TIMEOUT = 2;


sub new {
    my $class = shift;

    my $self = shift || {};
    ref($self) eq 'HASH' or die("Options hash ref not passed to new");

    $self = bless $self, $class;

    my $default_ulc = '/usr/local/cpanel';
    $self->{'ulc'} ||= $default_ulc;

    if ( !$self->{'staging_dir'} ) {
        $self->{'staging_dir'} = $self->determine_staging_dir();
        $self->{'staging_dir'} = $self->{'ulc'} if $self->{'ulc'} ne $default_ulc;
    }

    $self->{'dnsonly'} //= Cpanel::Server::Type::is_dnsonly();
    $self->{'update_is_available_exit_code'} = 42;
    $self->{'cpanel_config_file'} ||= '/var/cpanel/cpanel.config';
    $self->{'firstinstall'} = ( $ENV{'CPANEL_BASE_INSTALL'} && !-e '/usr/local/cpanel/cpanel' ) ? 1 : 0;

    if ( $self->{'log_file_path'} && -e $self->{'log_file_path'} ) {
        $self->{'log_tell'} = ( stat( $self->{'log_file_path'} ) )[7];
    }

    $self->{'logger'} ||= Cpanel::Update::Logger->new( { $self->{'log_file_path'} ? ( 'logfile' => $self->{'log_file_path'} ) : ( 'to_memory' => 1 ), 'stdout' => 1, 'log_level' => ( $self->{'verbose'} ? 'debug' : 'info' ) } );

    return $self;
}

sub determine_staging_dir {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $staging_dir = $self->upconf->{'STAGING_DIR'};

    if ( $staging_dir !~ m{^/usr/local/cpanel/?$} ) {
        $self->{using_custom_staging_dir} = 1;
        my $hostname = Cpanel::Sys::Hostname::gethostname();
        $hostname =~ s/\./_/g;
        $staging_dir .= ( substr( $staging_dir, -1 ) eq '/' ? ".cpanel__${hostname}__upcp_staging" : "/.cpanel__${hostname}__upcp_staging" );
        return $staging_dir;
    }
    return $staging_dir;
}

sub validate_staging_dir {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    if ( $self->{'staging_dir'} !~ m{^/usr/local/cpanel/?$} ) {

        eval { Cpanel::Update::Config::validate_staging_dir( $self->{'staging_dir'}, 'die_on_failure' ); } or do {
            my $error_as_string = Cpanel::Exception::get_string($@);
            $self->logger->fatal("Failed to validate staging directory: “$error_as_string”.");
            die( { 'exit' => 1, 'remove_blocker_file' => 0 } );
        };
    }
    return 1;
}

sub advertise_startup {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->logger->info("Running version '$Cpanel::Version::Tiny::VERSION_BUILD' of updatenow.");

    return;
}


sub logger {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return $self->{'logger'};
}


sub dry_run {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return $self->{'dry_run'} ? 1 : 0;
}


sub upconf {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'upconf'} ||= Cpanel::Update::Config::load();
    return $self->{'upconf'};
}


sub tiers {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'tiers'} ||= Cpanel::Update::Tiers->new( logger => $self->{'logger'} );
    return $self->{'tiers'};
}


sub cpsrc {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'CPSRC'} ||= Cpanel::Config::Sources::loadcpsources();
    return $self->{'CPSRC'};
}


sub parse_argv {
    my %options = (
        'sync'               => 0,
        'force'              => 0,
        'upcp'               => 0,
        'log_file_path'      => undef,
        'man'                => 0,
        'verbose'            => 0,
        'checkremoteversion' => 0,
        'skipreposetup'      => 0,
        'dry_run'            => 0,
        'upgrade_to_main'    => 0,
    );

    Cpanel::Usage::wrap_options(
        \@_,
        \&_usage,
        {
            'sync'               => \$options{'sync'},
            'force'              => \$options{'force'},
            'upcp'               => \$options{'upcp'},
            'verbose'            => \$options{'verbose'},
            'checkremoteversion' => \$options{'checkremoteversion'},
            'log'                => \$options{'log_file_path'},
            'man'                => \$options{'man'},
            'dry_run'            => \$options{'dry_run'},
            'skipreposetup'      => \$options{'skipreposetup'},
            'upgrade_to_main'    => \$options{'upgrade_to_main'},
        }
    );

    return \%options;
}


sub rebuild_argv {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my @argv = (
        $self->{'sync'}               ? ('--sync')                                            : (),
        $self->{'force'}              ? ('--force')                                           : (),
        $self->{'upcp'}               ? ('--upcp')                                            : (),
        $self->{'verbose'}            ? ('--verbose')                                         : (),
        $self->{'checkremoteversion'} ? ('--checkremoteversion')                              : (),
        $self->{'dry_run'}            ? ('--dry_run')                                         : (),
        $self->{'skipreposetup'}      ? ('--skipreposetup')                                   : (),
        $self->{'log_file_path'}      ? ( '--log=' . $self->{'log_file_path'} )               : (),
        $self->{'upgrade_to_main'}    ? ( '--upgrade_to_main=' . $self->{'upgrade_to_main'} ) : (),
    );
    return @argv;
}


sub setup_rpms_targets {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return unless $self->{'dnsonly'};

    foreach my $target (qw{mailman munin analog awstats roundcube clamav composer proftpd pure-ftpd webalizer horde ng-cpanel-jupiter-apps}) {
        $self->logger->info(qq[Mark target '$target' as 'uninstalled'.]);

        $self->_uninstall_rpm_target($target);
    }

    $self->rpms()->save();

    return;
}

sub _uninstall_rpm_target {
    my ( $self, $target ) = @_;
    $self->rpms()->set_target_settings( { 'key' => [$target], 'value' => 'uninstalled' } );
    return;
}


sub run {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    local $Cpanel::Locale::Context::DEFAULT_OUTPUT_CONTEXT = 'ansi';
    local $Cpanel::Carp::OUTPUT_FORMAT                     = q<>;

    $self->advertise_startup();

    Cpanel::Crypt::GPG::VendorKeys::download_public_keys( 'logger' => $self->{'logger'} );

    $self->set_initial_starting_version();

    $self->validate_staging_dir();

    $self->validate_config();

    $self->_ensure_yum_fastest_mirror_optimized();

    $self->set_tier_or_sync_version();

    $self->block_if_downgrade();

    my $final_target = 0;
    $self->current_lts_first() or $self->next_lts_before_target() or $final_target = 1;

    if ( $self->_current_updatenow_version ne $self->target_version ) {
        $self->logger->info("Switching to version $self->{target_version} of updatenow to determine if we can reach that version without failure.");
        $self->become_a_new_updatenow();
    }

    $self->can_update();

    my $assure_all_distro_packages_pid = $self->assure_all_distro_packages();

    my $webmail_jupiter = $self->{'ulc'} . '/base/webmail/jupiter';
    if ( -l $webmail_jupiter ) {
        my $webmail_paper_lantern = "$self->{'ulc'}/base/webmail/paper_lantern";
        Cpanel::FileUtils::Copy::safecopy( $webmail_paper_lantern, "${webmail_jupiter}_tmp" );
        unlink $webmail_jupiter                              or warn "Couldn't unlink ${webmail_jupiter}: $!";
        rename( "${webmail_jupiter}_tmp", $webmail_jupiter ) or warn "Couldn't rename ${webmail_jupiter}_tmp to $webmail_jupiter: $!";
    }

    $self->stage_files();

    $self->check_for_all_distro_packages_error($assure_all_distro_packages_pid);

    $self->preinstall_perlmajor_upgrade();

    my $need_rpms_update = $self->test_rpm_transaction();

    sleep( ( 70 - ( time % 60 ) ) % 60 ) if $self->{'did_preinstall'};

    $self->disable_services($need_rpms_update);

    $self->install_files();

    $self->log_update_completed();

    unlink Cpanel::Update::Blocker->upgrade_deferred_file if $final_target;

    die( { 'exit' => 0, 'remove_blocker_file' => 1 } );
}

sub block_if_downgrade {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $target_major   = Cpanel::Version::Compare::get_major_release( $self->target_version );
    my $starting_major = Cpanel::Version::Compare::get_major_release( $self->starting_version );
    return 0 if Cpanel::Version::Compare::compare( $target_major, '>=', $starting_major );

    return $self->block_from_updatenow( "A major version downgrade from $self->{starting_version} to $self->{target_version} is not allowed.", 5 );
}

sub assure_all_distro_packages {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->logger->info("Ensuring required distro packages are installed.");

    return Cpanel::ForkAsync::do_in_child(
        sub {
            my $want_supplemental_packages = $ENV{'CPANEL_BASE_INSTALL'} ? 0 : 1;
            my $sysup                      = Cpanel::Sysup->new( { 'logger' => $self->logger() } );

            my $upgrade_or_install = $ENV{'CPANEL_BASE_INSTALL'} ? q[install] : q[upgrade to];

            $sysup->run(
                'skipreposetup'       => ( $self->{'skipreposetup'} ? 1 : 0 ),
                supplemental_packages => $want_supplemental_packages
            ) or die "Cannot $upgrade_or_install $self->{'target_version'} until needed system packages are installed.";

            return 1;
        }
    );
}


sub check_for_all_distro_packages_error {
    my ( $self, $assure_all_distro_packages_pid ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    local $?;
    _waitpid($assure_all_distro_packages_pid);
    if ( $? != 0 ) {
        my $upgrade_or_install = $ENV{'CPANEL_BASE_INSTALL'} ? q[install] : q[upgrade to];
        $self->block_from_updatenow( "Cannot $upgrade_or_install $self->{'target_version'} until needed system packages are installed.", 18 );
    }
    return 1;
}

sub block_from_updatenow {
    my ( $self, $msg, $exit_num ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $blocker_object = Cpanel::Update::Blocker->new(
        {
            'logger'           => $self->logger,
            'starting_version' => 1,                  # We don't need starting version to block_version_change and we might not have a vaild one.
            'target_version'   => 1,                  # We also don't need a target version to block.
            'upconf_ref'       => 1,
            'tiers'            => 1,
            'force'            => $self->{'force'},
        }
    );

    $blocker_object->block_version_change($msg);
    $blocker_object->generate_blocker_file();
    die( { 'exit' => $exit_num || 254, 'remove_blocker_file' => 0, 'message' => $msg } );
}


sub preinstall_perlmajor_upgrade {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return if $self->{'initial_install'};

    return if -x Cpanel::Binaries::path("perl");

    $self->logger->info("This upgrade is a major perl version change. Pre-installing some packages to reduce the window where cPanel is unstable.");
    return if ( $self->dry_run );

    $self->{'did_preinstall'} = eval { $self->rpms->preinstall_perlmajor_upgrade() };

    if ($@) {
        my $error_as_string = Cpanel::Exception::get_string($@);
        $self->logger->fatal("Error pre-installing Perl packages when switching major versions: $error_as_string. Aborting upgrade to avoid an unstable system.");
        die( { 'exit' => 1, 'remove_blocker_file' => 1, 'message' => "Error pre-installing Perl packages when switching major versions: $error_as_string. see https://go.cpanel.net/perlmajorupgradefailure for more information" } );
    }

    return;
}


sub test_rpm_transaction {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->logger->info("Testing if the newly downloaded packages can be installed without conflict");
    return if ( $self->dry_run );

    eval { $self->rpms->test_rpm_install() };

    if ($@) {
        my $error_as_string = Cpanel::Exception::get_string($@);
        $self->logger->fatal("Error testing if the packages will install: $error_as_string  see https://go.cpanel.net/rpmcheckfailed for more information");
        die( { 'exit' => 1, 'remove_blocker_file' => 1, 'message' => "Error testing if the packages will install: $error_as_string  see https://go.cpanel.net/rpmcheckfailed for more information" } );
    }
}


sub current_lts_first {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $starting_version     = $self->starting_version;
    my $starting_lts_version = $self->tiers->get_lts_for($starting_version) or return 0;
    my $target_lts_version   = $self->tiers->get_lts_for( $self->{target_version} );

    return 0 if $target_lts_version && $target_lts_version eq $starting_lts_version;

    return 0 if Cpanel::Version::Compare::compare( $starting_version, '>=', $starting_lts_version );

    $self->logger->info("First upgrading to $starting_lts_version before upgrading to final version.");
    $self->{target_version} = $starting_lts_version;

    return 1;
}


sub next_lts_before_target {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $starting_version = $self->starting_version;    # We can assume this is an LTS or better version
    my $target_version   = $self->target_version;

    my $next_lts_version = $self->tiers->get_lts_for( $starting_version, 1 ) or return 0;

    my $target_major   = Cpanel::Version::Compare::get_major_release($target_version);
    my $next_lts_major = Cpanel::Version::Compare::get_major_release($next_lts_version);

    return 0 if ( Cpanel::Version::Compare::compare( $target_major, '<=', $next_lts_major ) );

    $self->{target_version} = $next_lts_version;
    $self->logger->info("Upgrade requested to a version more than 1 LTS away. Will upgrade to next LTS first ($next_lts_version).");

    return 1;
}

sub try_update_to_main {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return 1 if $self->{'upgrade_to_main'};

    my $starting_major = Cpanel::Version::Compare::get_major_release( $self->starting_version );
    return 2 if Cpanel::Version::Compare::compare( $starting_major, '<', '11.78' );

    return 3 if $self->tiers->is_explicit_version( $self->tiers->get_current_tier );

    my $try_version = $self->tiers->get_main_for_version( $self->starting_version ) or return 4;

    return 5 unless Cpanel::Version::Compare::compare( $try_version, '>', $self->starting_version );

    $self->logger->info("An attempt to upgrade to $self->{target_version} was blocked. Attempting to upgrade to the latest $starting_major version ($try_version).");

    $self->{'upgrade_to_main'} = $self->target_version($try_version);

    $self->become_a_new_updatenow();    #exec.

    return;                             # Unreachable code.
}


sub can_update {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    if ( $ENV{'UPDATE_IS_ALLOWED'} && $ENV{'UPDATE_IS_ALLOWED'} eq $self->target_version ) {
        $self->logger->debug("\$ENV{UPDATE_IS_ALLOWED} = $ENV{UPDATE_IS_ALLOWED}");
        return 1;
    }

    my $blocker_object = Cpanel::Update::Blocker->new(
        {
            'logger'           => $self->logger,
            'starting_version' => $self->starting_version,
            'target_version'   => $self->target_version,
            'upconf_ref'       => $self->upconf,
            'tiers'            => $self->tiers,
            'force'            => $self->{'force'},
        }
    );

    $blocker_object->is_upgrade_blocked();

    if ( $blocker_object->is_fatal_block() ) {

        $self->try_update_to_main();

        $self->logger->warning("An attempt to upgrade to $self->{target_version} was blocked. Please review blockers.");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "An attempt to upgrade to $self->{target_version} was blocked. Please review blockers." } );
    }

    if ( $self->{'checkremoteversion'} ) {
        $self->logger->info("$self->{target_version} is available for update.");
        die( { 'exit' => $self->{'update_is_available_exit_code'}, 'remove_blocker_file' => 1, 'message' => "$self->{target_version} is available for update.", 'success' => 1 } );
    }

    $ENV{'UPDATE_IS_ALLOWED'} = $self->target_version;
    return 2;
}


sub _current_updatenow_version { return $Cpanel::Version::Tiny::VERSION_BUILD }

sub target_version {
    my ( $self, $val ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'target_version'} = $val if ( scalar @_ == 2 );
    return $self->{'target_version'};
}

sub starting_version {
    my ( $self, $val ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'starting_version'} = $val if ( scalar @_ == 2 );
    return $self->{'starting_version'};
}


sub become_a_new_updatenow {
    my ( $self, %opts ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $target_version = $self->target_version;
    if ( !$target_version ) {
        $self->logger->fatal("The target version not passed to become_a_new_updatenow");
        die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "The target version not passed to become_a_new_updatenow" } );
    }

    return 0 if ( $self->_current_updatenow_version eq $target_version );

    my $skip_signature_check = int( Cpanel::Version::Compare::get_major_release( $self->target_version ) <= 11.48 );
    my $static_script;

    if ( $self->dry_run() ) {
        $self->logger->debug( 'Cpanel::Sync::v2->new( ' . $target_version . ', ' . $self->{'ulc'} . ' )->sync_updatenow_static(' . $skip_signature_check . ');' );
        $self->logger->debug( q{exec(/scripts/updatenow.static } . join( ' ', $self->rebuild_argv ) . ')' );

        $Cpanel::Version::Tiny::VERSION_BUILD = $target_version;
        return;
    }

    eval { $static_script = $self->cpanel->sync_updatenow_static($skip_signature_check) };

    if ( !$static_script ) {
        my $error_as_string = Cpanel::Exception::get_string($@);
        $self->logger->fatal("Failed to download updatenow.static from server: $error_as_string");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Failed to download updatenow.static from server: $error_as_string" } );
    }

    my $tmp          = Cpanel::TempFile->new( { path => q{/var/cpanel} } );
    my $tmp_cpupdate = $tmp->file;

    if ( $opts{'use_target_updatenow.static'} ) {
        $self->logger->info( 'Use target updatenow.static version: ' . $target_version );

        $self->create_temporary_update_conf( $tmp_cpupdate, $target_version );

        $self->update_script_with_update_conf( $static_script, $tmp_cpupdate );

    }
    else {

        $tmp->cleanup();
    }

    if ( !chmod( 0700, $static_script ) ) {
        $self->logger->fatal("Could not set downloaded updatenow.static to executable");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Could not set downloaded updatenow.static to executable" } );
    }

    $self->logger->info( 'Become an updatenow.static for version: ' . $target_version );

    $self->logger->close_log();

    if ( !exec( $static_script, $self->rebuild_argv ) ) {
        my $why = $!;
        my $msg = "Failed to run downloaded $static_script ($!)";
        $self->logger->fatal($msg);
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => $msg } );
    }

    die( { 'exit' => 99, 'remove_blocker_file' => 0 } );
}

sub update_script_with_update_conf {
    my ( $self, $script, $tmp_cpupdate ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $fh   = IO::Handle->new();
    my $lock = Cpanel::SafeFile::safeopen( $fh, '+<', $script ) or do {
        $self->logger->fatal("Failed to open updatenow.static");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Failed to open updatenow.static" } );
    };
    my @lines = <$fh>;
    seek( $fh, 0, 0 );
    foreach my $line (@lines) {

        $line =~ s{/etc/cpupdate.conf([,\s'"\}\)])}{$tmp_cpupdate$1};
        print {$fh} $line;
    }
    truncate( $fh, tell($fh) );
    Cpanel::SafeFile::safeclose( $fh, $lock );

    return;
}

sub create_temporary_update_conf {
    my ( $self, $tmp_cpupdate, $target_version ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my @cpupdate_conf;
    {
        my $fh   = IO::Handle->new();
        my $lock = Cpanel::SafeFile::safeopen( $fh, '<', $Cpanel::Update::Config::cpanel_update_conf ) or do {
            $self->logger->fatal("Failed to open update.conf");
            die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Failed to open update.conf" } );
        };
        @cpupdate_conf = <$fh>;
        Cpanel::SafeFile::safeclose( $fh, $lock );
    }
    {
        my $fh   = IO::Handle->new();
        my $lock = Cpanel::SafeFile::safeopen( $fh, '>', $tmp_cpupdate ) or do {
            $self->logger->fatal("Failed to open temporary update.conf: '$tmp_cpupdate'");
            die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Failed to open temporary update.conf: '$tmp_cpupdate'" } );
        };
        foreach my $line (@cpupdate_conf) {
            if ( $line =~ m/^CPANEL=/ ) {
                $line = 'CPANEL=' . $target_version . "\n";
            }
            print {$fh} $line;
        }
        Cpanel::SafeFile::safeclose( $fh, $lock );
    }

    return;
}


sub validate_config {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    unless ( $self->{'force'} or $self->{'sync'} or Cpanel::Update::Config::is_permitted( 'UPDATES', $self->upconf() ) ) {
        if ( $self->upconf->{'UPDATES'} eq 'never' ) {
            $self->logger->info('cPanel & WHM updates are disabled.');
        }
        if ( $self->upconf->{'UPDATES'} eq 'manual' ) {
            $self->logger->info('cPanel & WHM updates are disabled via cron because they are set to “manual” in /etc/cpupdate.conf');
        }

        $self->logger->info("No sync will occur.");

        die( { 'exit' => 0, 'remove_blocker_file' => 0 } );
    }

    unless ( $self->{'checkremoteversion'} or $self->{'force'} or $self->{'sync'} or $self->{'upcp'} ) {
        $self->logger->fatal("This script is not designed to be called directly. Please use /usr/local/cpanel/scripts/upcp");
        die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "This script is not designed to be called directly. Please use /usr/local/cpanel/scripts/upcp" } );
    }

    if ( $self->{'checkremoteversion'} && ( $self->{'force'} or $self->{'sync'} or $self->{'upcp'} ) ) {
        $self->logger->fatal("--checkremoteversion is not designed to be called with other flags.");
        die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "--checkremoteversion is not designed to be called with other flags." } );
    }

    if ( $self->{'force'} && $self->{'sync'} ) {
        $self->logger->fatal("--force and --sync are mutually exclusive commands. Force is designed to update your installed version, regardless of whether it's already up to date. Sync is designed to update the version already installed, regardless of what is available.");
        die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "--force and --sync are mutually exclusive commands. Force is designed to update your installed version, regardless of whether it's already up to date. Sync is designed to update the version already installed, regardless of what is available." } );
    }

    $self->logger->info("--sync passed on command line. No upgrade will be allowed")
      if ( $self->{'sync'} );
    $self->logger->info("--force passed on command line. Upgrade will disregard update config settings.")
      if ( $self->{'force'} );

    return 1;
}


sub _version_is_invalid {
    my $version = shift or return 1;

    return 0 if ( $version =~ m{^\d+\.\d+\.\d+\.\d+$} );

    return 1;
}


sub set_tier_or_sync_version {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    if ( $self->{'sync'} ) {
        $self->target_version( $self->starting_version );
        $self->logger->info("Setting target version to '$self->{target_version}' for --sync");
        return 1;
    }

    if ( $self->{'upgrade_to_main'} ) {
        if ( $self->tiers->is_explicit_version( $self->tiers->get_current_tier ) ) {
            die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "--upgrade_to_main passed when an explicit version was set in /etc/cpupdate.conf" } );
        }

        $self->logger->info("--upgrade_to_main=$self->{upgrade_to_main} passed on on command line");
        my $try_version = $self->tiers->get_main_for_version( $self->starting_version );
        $try_version or die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "could not determine 'is_main' version for $self->{starting_version}" } );
        $self->target_version($try_version);
        return 5;
    }

    $self->set_target_from_current_tier();

    if ( $ENV{'CPANEL_BASE_INSTALL'} && !$self->starting_version ) {
        $self->starting_version( $self->target_version );
        $self->{'initial_install'} = 1;
        $self->logger->info("Initial cPanel installation detected as in progress.");
        return 2;
    }

    return 3 if ( -e $self->get_upgrade_in_progress_lock_file_name() );

    if ( !$self->{'force'} && ( $self->target_version eq $self->starting_version ) ) {
        $self->logger->info("Up to date ($self->{starting_version})");
        die( { 'exit' => 0, 'remove_blocker_file' => 1, 'message' => "Up to date ($self->{starting_version})", success => 1 } );
    }

    return 4;
}

sub get_upgrade_in_progress_lock_file_name {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return '/usr/local/cpanel/upgrade_in_progress.txt';
}


sub set_target_from_current_tier {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $target_tier = $self->tiers->get_current_tier() || '';

    my $target_tier_version = $self->tiers->get_remote_version_for_tier($target_tier);
    if ( !$target_tier_version ) {
        $self->logger->fatal("The version for tier '$target_tier' is not defined!");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "The version for tier '$target_tier' is not defined!" } );
    }

    if ( $ENV{'CPANEL_BASE_INSTALL'} && $target_tier_version eq 'disabled' ) {
        $target_tier_version = $self->tiers->get_remote_version_for_tier('install-fallback');

        if ( !$target_tier_version ) {
            my $msg = "The tier '$target_tier' is currently disabled and no install-fallback exists!";
            $self->logger->fatal($msg);
            die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => $msg } );
        }

        $self->logger->warning("$target_tier is currently disabled. Falling back to $target_tier_version for fresh installs.");
    }
    elsif ( $target_tier_version eq 'disabled' ) {
        $self->logger->warn("cPanel has temporarily disabled updates on the central httpupdate servers. Please try again later.");
        die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "cPanel has temporarily disabled updates on the central httpupdate servers. Please try again later." } );
    }

    if ( $target_tier_version eq $target_tier ) {
        $self->logger->warning("version explicitly hardcoded to CPANEL=$target_tier in /etc/cpupdate.conf");
    }
    else {
        $self->logger->info("Target version set to '$target_tier_version'");
    }

    return $self->target_version($target_tier_version);
}


sub get_binary_sync_source ($self) {

    return 'binaries/' . Cpanel::OS::binary_sync_source();

}


sub stage_files {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->logger->info( "Staging " . $self->target_version . " cpanelsync files prior to updating $self->{'staging_dir'}" );

    my $is_fresh_install = $ENV{'CPANEL_BASE_INSTALL'} ? 1 : 0;

    my %stage_opts_tree;
    foreach my $source ( 'cpanel', Cpanel::Themes::Get::get_list() ) {
        $stage_opts_tree{$source} = { no_download => $is_fresh_install };
    }

    my $tarball_download_pid;

    if ( $self->{firstinstall} ) {
        $self->logger->info('Staging first installation tarballs');
        my $tarbin = Cpanel::Binaries::path('tar');
        -x $tarbin or die( { 'exit' => 7, 'remove_blocker_file' => 1, 'message' => "Cannot find tar binary" } );

        my $want_cpanel              = !$self->cpanel()->already_done() ? 1 : 0;
        my $want_locale              = !-d '/var/cpanel/locale';
        my $needs_at_least_one_theme = grep { !$self->get_theme_synctree($_)->already_done() } Cpanel::Themes::Get::get_list();
        my $want_theme               = !$self->{'dnsonly'} && $needs_at_least_one_theme;
        my @tarballs;

        if ( $want_cpanel || $want_locale ) {
            if ($want_cpanel) {
                push @tarballs,
                  {
                    file   => q{cpanel.tar.xz},
                    syncto => '/',
                    from   => _install_common_root()
                  };
                $self->logger->debug('cpanel tarball will be staged and installed');
            }
            else {
                delete $stage_opts_tree{'cpanel'}->{'no_download'};
                $self->logger->debug('cpanel tarball is not required');
            }

            $self->call_stage( 'sync_target' => 'install_common', 'failure_exit_code' => 8 );
            $self->install_common->commit();
        }
        else {
            $self->logger->debug('cpanel and locale tarballs are not required');
        }

        $self->_extract_tarballs( $tarbin, \@tarballs ) if @tarballs;
        @tarballs = ();

        if ( $want_locale || $want_theme ) {

            $tarball_download_pid = Cpanel::ForkAsync::do_in_child(
                sub {
                    if ($want_locale) {
                        push @tarballs, {
                            file     => q{locale.tar.xz},         # cdb are no arch dependent...
                            syncto   => '/var/cpanel/locale',
                            absolute => 1,
                            from     => _install_common_root(),
                        };
                        $self->logger->debug('locale tarball will be staged and installed');
                    }
                    else {
                        $self->logger->debug('locale tarball is not required');
                    }

                    $self->logger->debug("detected $needs_at_least_one_theme theme tarballs that will be staged and installed");
                    if ($want_theme) {
                        $self->call_stage( 'sync_target' => 'install_themes', 'failure_exit_code' => 9 );
                        $self->install_themes->commit();
                        foreach my $theme ( Cpanel::Themes::Get::get_list() ) {
                            if ( !$self->get_theme_synctree($theme)->already_done() ) {
                                push @tarballs, {
                                    file   => qq{$theme.tar.xz},
                                    syncto => _theme_root_for($theme),
                                    from   => _install_themes_root(),
                                };
                                $self->logger->debug("$theme tarball will be staged and installed");
                            }
                            else {
                                delete $stage_opts_tree{$theme}->{'no_download'};
                                $self->logger->debug("$theme tarball will not be staged and installed");
                            }
                        }
                    }
                    else {
                        $self->logger->debug("no theme tarballs are required");
                    }

                    $self->_extract_tarballs( $tarbin, \@tarballs );
                    Cpanel::SafeDir::RM::safermdir( $self->{ulc} . '/firstinstall' );
                }
            );
        }
        else {
            Cpanel::SafeDir::RM::safermdir( $self->{ulc} . '/firstinstall' );

        }
    }

    if ( $self->{using_custom_staging_dir} ) {
        Cpanel::SafeDir::MK::safemkdir( $self->{'staging_dir'} . '/base/frontend', 0755 );
    }

    $self->call_stage( 'sync_target' => 'cpanel', 'failure_exit_code' => 12, 'message' => 'cpanel changes', 'stage_opts' => $stage_opts_tree{'cpanel'} );

    $self->setup_rpms_targets();

    my $max_num_of_sync_children_this_system_can_handle = $self->cpanel()->calculate_max_sync_children();

    $self->call_stage(
        'message'           => 'new packages', 'sync_target' => 'rpms', 'failure_exit_code' => 13, 'help_message' => 'see https://go.cpanel.net/rpmcheckfailed for more information',
        'max_sync_children' => $max_num_of_sync_children_this_system_can_handle
    );

    _waitpid($tarball_download_pid) if $tarball_download_pid;

    if ($is_fresh_install) {
        $self->call_stage( 'sync_target' => 'binaries', 'failure_exit_code' => 12, 'message' => 'cpanel binaries changes' );
    }

    if ( !$self->{'dnsonly'} ) {

        foreach my $theme ( Cpanel::Themes::Get::get_list() ) {
            $self->call_stage( message => qq{$theme theme changes}, 'sync_object' => $self->get_theme_synctree($theme), 'failure_exit_code' => 10, 'stage_opts' => $stage_opts_tree{$theme} );
        }
    }

    $self->logger->info("All files Staged");

    return;
}

sub _waitpid {
    my ($pid) = @_;
    return waitpid( $pid, 0 );
}

sub _extract_tarballs {
    my ( $self, $tarbin, $tarballs_ar ) = @_;
    foreach my $tb (@$tarballs_ar) {
        my $file = $self->{ulc} . '/' . $tb->{from} . '/' . $tb->{file};
        $self->logger->info( 'Extracting files from ' . $tb->{file} );
        my $extract_to = $self->{ulc} . '/' . $tb->{syncto};
        $extract_to = $tb->{syncto} if $tb->{absolute};
        Cpanel::SafeDir::MK::safemkdir( $extract_to, 0755 );
        system( $tarbin, '-x', '--no-same-owner', '--overwrite-dir', '-p', '--directory=' . $extract_to, '-f', $file, qw{ --use-compress-program xz } ) == 0
          or die( { 'exit' => 9, 'remove_blocker_file' => 1, 'message' => "Failed to extract tarball " . $tb->{file} } );
    }
    return;
}

sub call_stage {
    my ( $self, %OPTS ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $sync_target       = $OPTS{'sync_target'};
    my $message           = $OPTS{'message'} || $sync_target;
    my $sync_object       = $OPTS{'sync_object'};
    my $failure_exit_code = $OPTS{'failure_exit_code'};
    my $help_message      = $OPTS{'help_message'};
    my $max_sync_children = $OPTS{'max_sync_children'};
    my $suppress_message  = $OPTS{'suppress_message'};          # Remove this flag in 11.52, its only here to preserve 11.50 behavior
    my $stage_opts        = $OPTS{'stage_opts'} || {};
    my ( $ret, $err );

    $self->logger->info("Staging $message") unless $suppress_message;

    try {
        $sync_object ||= $self->$sync_target();
        $ret = $sync_object->stage(%$stage_opts);
    }
    catch {
        $err = $_;
    };

    if ( $err || !$ret ) {
        my $log_message = "Failed to stage “$message”" . ( $err ? " because of an error: " . Cpanel::Exception::get_string($err) : '' ) . ( $help_message ? " : $help_message" : '' );
        $self->logger->fatal($log_message);
        die( { 'exit' => $failure_exit_code, 'remove_blocker_file' => 1, 'message' => $log_message } );
    }

    return 1;
}


my $monitoring_disabled_from;
my @run_on_sevice_restore;

sub disable_services {
    my ( $self, $need_rpms_update ) = @_;

    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return if $ENV{'CPANEL_BASE_INSTALL'};    # nothing do do
    return if $self->dry_run();



    my @services_to_suspend = (
        {
            'name'           => q[tailwatchd],
            'restart_script' => '/usr/local/cpanel/scripts/restartsrv_tailwatchd',
            'custom_stop'    => sub {
                my ($service) = @_;
                die unless ref $service;

                if ( !Cpanel::Signal::send_usr1_tailwatchd() ) {
                    system(qq{$service->{restart_script} --stop --no-verbose 2>&1 | grep -v 'service is disabled'});
                }
                return;
            }
        },
        {
            'name'           => q[queueprocd],
            'restart_script' => '/usr/local/cpanel/scripts/restartsrv_queueprocd',

            'only_on_rpm_update' => 1,
        },
    );

    my $has_disabled_monitoring;

    foreach my $service (@services_to_suspend) {

        next if $need_rpms_update && $service->{only_on_rpm_update};

        my $service_status = qx{$service->{restart_script} --status 2>/dev/null} // '';    ## no critic qw(Cpanel::ProhibitQxAndBackticks)
        chomp($service_status);
        next unless $service_status =~ m/\brunning.+?PID\b/;

        if ( !$has_disabled_monitoring ) {
            $has_disabled_monitoring = 1;                                                  # disable checksrvd once

            $self->logger->info("Disabling service monitoring during update.");
            $monitoring_disabled_from = $$;

            eval q{ END { restore_services() } };    ## no critic qw(ProhibitStringyEval)

            Cpanel::FileUtils::TouchFile::touchfile('/var/run/chkservd.suspend');
        }

        $self->logger->info("    Stopping service '$service->{name}'.");
        if ( ref $service->{'custom_stop'} eq 'CODE' ) {
            $service->{'custom_stop'}->($service);
        }
        else {
            system(qq{$service->{restart_script} --stop --no-verbose 2>&1});
        }

        push @run_on_sevice_restore,    # .
          qq[$service->{restart_script} --no-verbose 2>&1 | grep -v 'service is disabled'];
    }

    return;
}

sub restore_services {

    return unless $monitoring_disabled_from && $monitoring_disabled_from == $$;

    foreach my $action ( reverse @run_on_sevice_restore ) {
        system($action );
    }
    @run_on_sevice_restore = ();

    unlink '/var/run/chkservd.suspend';    # restore monitoring

    return;
}

sub install_files {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->logger->info("Putting cpanelsync files into place.");

    return if ( $self->dry_run() );

    my $ulc = $self->{'ulc'} or die;

    if ( !$ENV{'CPANEL_BASE_INSTALL'} ) {


        if ( -e "$ulc/etc/.js_files_in_repo_with_mt_calls" ) {
            $self->logger->info("    Preserving previous JS files list.");
            my $rv = Cpanel::FileUtils::Copy::safecopy( "$ulc/etc/.js_files_in_repo_with_mt_calls", "$ulc/etc/.js_files_in_repo_with_mt_calls.prev" );
            unless ($rv) {
                $self->logger->warning("Copy of $ulc/etc/.js_files_in_repo_with_mt_calls to $ulc/etc/.js_files_in_repo_with_mt_calls.prev failed: $!");
            }
        }
    }


    $self->logger->info("    Committing cpanel.");
    eval { $self->cpanel->commit(); 1; } or do {
        my $error_as_string = Cpanel::Exception::get_string($@);
        my $message         = 'Failed to commit cpanel changes';
        $self->logger->fatal("$message: “$error_as_string”.");
        die( { 'exit' => 14, 'remove_blocker_file' => 1, 'message' => "$message." } );
    };

    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        $self->logger->info("    Committing cpanel binaries.");
        eval { $self->binaries->commit(); 1; } or do {
            my $error_as_string = Cpanel::Exception::get_string($@);
            my $message         = 'Failed to commit cpanel binary changes';
            $self->logger->fatal("$message: “$error_as_string”.");
            die( { 'exit' => 14, 'remove_blocker_file' => 1, 'message' => "$message." } );
        };
    }

    my $cpkeyclt_exit_code = 1;
    my $cpkeyclt           = $self->{'ulc'} . '/cpkeyclt';

    if ( !$ENV{'CPANEL_BASE_INSTALL'} ) {

        if ( !Cpanel::Signal::send_usr1_tailwatchd() ) {
            system(q{/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose 2>&1 | grep -v 'service is disabled'});
        }

        $self->logger->info('    Updating cpanel license for new binaries. This call may fail and that is ok.');
        $cpkeyclt_exit_code = Cpanel::SafeRun::Object->new( 'program' => $cpkeyclt, 'args' => ['--force-no-tty-check'] )->CHILD_ERROR();
    }

    if ( $self->{'dnsonly'} ) {
        $self->logger->info("    Removing x3 themes.");

        my $ulc = $self->{'ulc'} or die;
        for my $_dir ( Cpanel::Themes::Get::get_list() ) {
            my $dir_path = "$ulc/base/frontend/$_dir";
            if ( -e $dir_path ) {
                my $rv = Cpanel::SafeDir::RM::safermdir($dir_path);
                unless ($rv) {
                    $self->logger->warning("Removal of theme directory $dir_path failed!");
                }
            }
        }
    }
    else {
        $self->logger->info("    Committing cPanel themes.");
        foreach my $theme ( Cpanel::Themes::Get::get_list() ) {
            eval { $self->get_theme_synctree($theme)->commit(); 1; } or do {
                my $error_as_string = Cpanel::Exception::get_string($@);
                my $message         = "Failed to commit $theme theme changes";
                $self->logger->fatal("$message: “$error_as_string”.");
                die( { 'exit' => 15, 'remove_blocker_file' => 1, 'message' => "$message." } );
            };
        }
    }

    $self->logger->info("    Updating / Removing packages.");
    eval { $self->rpms->commit_changes(); 1; } or do {
        my $error_as_string = Cpanel::Exception::get_string($@);
        $self->logger->fatal("Error committing changes: $error_as_string  see https://go.cpanel.net/rpmcheckfailed for more information");
        die( { 'exit' => 17, 'remove_blocker_file' => 1, 'message' => "Error committing changes: $error_as_string  see https://go.cpanel.net/rpmcheckfailed for more information" } );
    };

    if ($cpkeyclt_exit_code) {
        $self->logger->info('    Updating cpanel license for new binaries.');
        $cpkeyclt_exit_code = system( $cpkeyclt, '--force-no-tty-check' );
        $cpkeyclt_exit_code and $self->logger->warn("Received unexpected exit code ($cpkeyclt_exit_code) from $cpkeyclt");
    }

    $self->logger->info('    Restoring service monitoring.');
    unlink '/var/run/chkservd.suspend';

    if ( !$ENV{'CPANEL_BASE_INSTALL'} && !Cpanel::Signal::send_hup_tailwatchd() ) {

        system(q{/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose 2>&1 | grep -v 'service is disabled'});
    }

    $self->logger->info("All files have been updated.");

    return;
}


sub make_cpanelsync_object {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $source = shift     or die;
    ref $source eq 'ARRAY' or die;
    my $sync_to = shift || '';
    my $options = shift || {};

    my $target_version = $self->target_version || 'no_target';

    my $staging_dir = $self->{'staging_dir'} or die;

    my %object_parameters = (
        'url'         => 'http://' . $self->cpsrc->{'HTTPUPDATE'} . '/cpanelsync/' . $target_version,
        'logger'      => $self->logger,
        'source'      => $source,
        'syncto'      => $staging_dir . ( $sync_to ? "/$sync_to" : '' ),
        'force'       => $self->{'force'},                                                              # Skip md5sum cache files if true.
        'staging_dir' => $self->{'staging_dir'},
        'ulc'         => $self->{'ulc'},
        'http_client' => $self->_http_client(),
        'options'     => $options,
    );

    my $object = Cpanel::Sync::v2->new( {%object_parameters} );
    ( $object && ref $object eq 'Cpanel::Sync::v2' ) or die("Can't create sync object for $source->[0]");
    return $object;
}

sub _install_common_root {
    return "firstinstall/common";
}

sub install_common {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'install_common_cpanelsync'} ||= $self->make_cpanelsync_object( ['install/common'], _install_common_root() );
    return $self->{'install_common_cpanelsync'};
}

sub _install_themes_root {
    return "firstinstall/themes";
}

sub install_themes {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'install_themes_cpanelsync'} ||= $self->make_cpanelsync_object( ['install/themes'], _install_themes_root() );
    return $self->{'install_themes_cpanelsync'};
}

sub _theme_root_for {
    my $theme = shift or die;
    return "base/frontend/$theme";
}

sub get_theme_synctree {
    my ( $self, $theme ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $cache_key = $theme . "_cpanelsync";

    $self->{$cache_key} ||= $self->make_cpanelsync_object( [$theme], _theme_root_for($theme) );
    return $self->{$cache_key};
}


sub cpanel {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        $self->{'cpanel_cpanelsync'} ||= $self->make_cpanelsync_object( ['cpanel'] );
    }
    else {
        $self->{'cpanel_cpanelsync'} ||= $self->make_cpanelsync_object( [ $self->get_binary_sync_source(), 'cpanel' ], undef, { 'ignore_xz' => 1 } );
    }

    return $self->{'cpanel_cpanelsync'};
}

sub binaries {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->{'cpanelbinaries_cpanelsync'} ||= $self->make_cpanelsync_object( [ $self->get_binary_sync_source() ] );
    return $self->{'cpanelbinaries_cpanelsync'};
}


sub rpms {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return $self->{'rpm_manager'} if $self->{'rpm_manager'};

    my $rpm_versions_destination = $Cpanel::ConfigFiles::RpmVersions::RPM_VERSIONS_FILE;
    $self->{'new_rpm_versions_file'} ||= $self->cpanel()->get_staged_file($rpm_versions_destination);
    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        $self->{'new_rpm_versions_file'} = $rpm_versions_destination;
    }

    if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
        my $config_defaults_file = $self->{'ulc'} . '/etc/cpanel.config';

        if ( defined $config_defaults_file && -e $config_defaults_file ) {
            Cpanel::Config::Merge::files(
                defaults_file => $config_defaults_file,
                config_file   => $self->{'cpanel_config_file'},
                logger        => $self->logger(),
            );
        }
    }

    $self->{'new_rpm_versions_file'} ||= $rpm_versions_destination;
    $self->{'new_rpm_versions_file'} = $rpm_versions_destination if !-e $self->{'new_rpm_versions_file'};

    $self->{'rpm_manager'} = Cpanel::RPM::Versions::File->new(
        {
            'file'         => $self->{'new_rpm_versions_file'},
            'logger'       => $self->logger(),
            'temp_dir'     => $self->{'staging_dir'} . '/rpm_downloads',
            'firstinstall' => $self->{firstinstall},
            'http_client'  => $self->_http_client(),
        }
    );
    return $self->{'rpm_manager'};
}


sub cleanup_owned_objects {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    delete $self->{'_http_client'};

    foreach my $key ( sort grep { m/_cpanelsync/ } keys %$self ) {
        delete $self->{$key};
    }

    return;
}


sub terminate {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $error = shift;

    $self->cleanup_owned_objects();


    if ( $self->logger->get_need_notify ) {
        my $log    = $self->get_log_array_from_logger();
        my @errors = grep { /^\[\d+\.\d+\] (?:(?:\Q***** FATAL:\E)|(?:E)) / } @{$log};

        $self->notify();

        print "\nThere were errors when running updatenow:\n\n";
        print join( "\n", @errors ) . "\n\n" if @errors;
    }

    my $error_type = $ENV{'CPANEL_BASE_INSTALL'} ? 'an error' : 'a fatal error';

    if ( ref($error) eq 'HASH' ) {
        my $blocker_file = Cpanel::Update::Blocker->update_blocks_fname;
        if ( $error->{'remove_blocker_file'} && -e $blocker_file ) {
            unlink $blocker_file;
        }
        if ( $error->{'message'} && !$error->{'success'} ) {
            $self->logger->error( "The install encountered $error_type: " . $error->{'message'} );
        }
        exit( $error->{'exit'} || 0 );
    }
    my $error_as_string = Cpanel::Exception::get_string($error);

    $self->logger->error( "The install encountered $error_type: " . ( $error_as_string || Carp::longmess() ) );

    die("$error_as_string\n");
}


sub notify {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return if ( $self->dry_run() );
    return unless ( $self->logger->get_need_notify );

    $self->logger->error("Detected events which require user notification during updatenow. Will send iContact the log");

    my $logger_ref = $self->get_log_array_from_logger();

    my $log = ref $logger_ref ? join( "\n", @$logger_ref ) : undef;

    if ( try( sub { Cpanel::LoadModule::load_perl_module("Cpanel::iContact::Class::Update::Now") } ) ) {

        $self->send_icontact_class_notification($log);
    }
    else {

        $self->send_icontact_noclass_notification($log);

    }

    return;
}


sub get_log_array_from_logger {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    return $self->logger->get_stored_log() if ( $self->logger->{'to_memory'} );

    return undef unless $self->{'log_file_path'} && -e $self->{'log_file_path'};

    $self->{'log_tell'} ||= 0;
    $self->logger->close_log();
    my $fh;
    if ( !open( $fh, '<', $self->{'log_file_path'} ) ) {
        warn "Failed to open log file: $self->{'log_file_path'}";
        return;
    }
    seek( $fh, $self->{'log_tell'}, 0 );

    my @lines = <$fh>;
    $_ =~ s/\n$// foreach (@lines);

    return \@lines;
}

sub send_icontact_class_notification {
    my ( $self, $log ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    require Cpanel::Notify;
    return Cpanel::Notify::notification_class(
        'class'            => 'Update::Now',
        'application'      => 'Update::Now',
        'constructor_args' => [
            "origin"           => 'upcp',
            "host"             => Cpanel::Hostname::gethostname(),
            'starting_version' => $self->starting_version,
            'target_version'   => $self->target_version,
            'attach_files'     => [ { name => 'updatenow-failure-log.txt', content => \$log, number_of_preview_lines => 25 } ],
        ]
    );
}

sub send_icontact_noclass_notification {
    my ( $self, $log ) = @_;
    $self                    or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $msg = "An error was detected which prevented updatenow from completing normally.\n";
    $msg .= "Please review the enclosed log for further details\n";
    $msg .= "\n" . '-' x 100 . "\n\n";
    $msg .= $log;
    return Cpanel::iContact::icontact(
        'application' => 'upcp',
        'subject'     => 'cPanel update failure during updatenow',
        'message'     => $msg,
    );
}


sub _usage {
    print qq{Usage: $0 [options]};
    print qq{

    Options:
      --help     Brief help message
      --man      Detailed help

     Note: This script is designed to be run by cPanel programs directly ONLY. Please see upcp instead. It's probably what you want.

};
    exit;
}


sub set_initial_starting_version {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    my $version = '';
    if ( open( my $fh, '<', $self->{'ulc'} . "/version" ) ) {
        $version = <$fh> || '';
        chomp $version;
        close $fh;
    }

    $self->logger->info("Detected version '$version' from version file.");

    if ( $ENV{'CPANEL_BASE_INSTALL'} && _version_is_invalid($version) ) {
        return $self->starting_version('');
    }

    if ( _version_is_invalid($version) ) {

        $self->logger->warning("Could not determine starting version from /usr/local/cpanel/version. Trying to guess starting version from Cpanel/Version/Tiny.pm");
        $version = $self->get_version_from_cv_tiny;

        if ( _version_is_invalid($version) ) {
            $self->logger->fatal("Cannot determine a valid current cPanel & WHM version in order to sync. Please correct the contents of /usr/local/cpanel/version and re-try");
            die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "Cannot determine a valid current cPanel & WHM version in order to sync. Please correct the contents of /usr/local/cpanel/version and re-try" } );
        }
    }

    my $starting_major = Cpanel::Version::Compare::get_major_release($version);
    if ( Cpanel::Version::Compare::compare( $starting_major, '<', '11.68' ) ) {
        my $updatenow_version = $self->_current_updatenow_version();
        $self->block_from_updatenow( "Version $updatenow_version of updatenow cannot support upgrades starting from below version 11.68", 25 );
    }

    return $self->starting_version($version);
}


sub get_version_from_cv_tiny {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    open( my $fh, '<', $self->{'ulc'} . "/Cpanel/Version/Tiny.pm" ) or return;
    while ( my $version = <$fh> ) {
        next if ( $version !~ m/^our \$VERSION_BUILD\s+=\s+'/ );
        chomp $version;
        $version =~ s/^our \$VERSION_BUILD\s+=\s+'//;
        $version =~ s/';\s*//;

        $self->logger->info("Detected version '$version' from Tiny.pm");
        return $version;
    }
    return;
}

sub summary_logger {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    if ( !$self->{'summary_logger'} ) {
        $self->{'summary_logger'} = Cpanel::Update::Logger->new( { logfile => '/var/cpanel/updatelogs/summary.log', brief => 1, stdout => 0 } );
    }

    return $self->{'summary_logger'};
}


sub log_update_completed {
    my $self = shift         or die;
    ref $self eq __PACKAGE__ or die("Must be called as a method");

    $self->summary_logger->info( "Completed update " . $self->starting_version . ' -> ' . $self->target_version );

    return;
}

sub _ensure_yum_fastest_mirror_optimized {
    my ($self) = @_;

    return if !-e $FASTEST_MIRROR_CNF_FILE;
    my $data = Cpanel::LoadFile::load($FASTEST_MIRROR_CNF_FILE);
    return if $data =~ m{\#cpanel modified};

    if ( open( my $fh, '>>', $FASTEST_MIRROR_CNF_FILE ) ) {
        if ( $data !~ m{^[ \t]*maxthreads[ \t]*=[ \t]*$FASTEST_MIRROR_MAX_THREADS}m ) {
            print {$fh} "\nmaxthreads = $FASTEST_MIRROR_MAX_THREADS\n";
        }
        if ( $data !~ m{^[ \t]*socket_timeout[ \t]*=[ \t]*$FASTEST_MIRROR_SOCKET_TIMEOUT}m ) {
            print {$fh} "\nsocket_timeout = $FASTEST_MIRROR_SOCKET_TIMEOUT\n";
        }
        print {$fh} "\n#cpanel modified\n";
    }

    return 1;
}

sub _http_client {
    my ($self) = @_;

    require Cpanel::HttpRequest;
    return $self->{'_http_client'} ||= Cpanel::HttpRequest->new(
        'die_on_404'      => 1,
        'retry_dns'       => 0,
        'hideOutput'      => 1,
        'logger'          => $self->logger(),
        'announce_mirror' => 1,
    );
}


1;

} # --- END Cpanel/Update/Now.pm


{ # --- BEGIN Cpanel/CPAN/Locales/DB/Territory/en.pm
package Cpanel::CPAN::Locales::DB::Territory::en;

use strict;



$Cpanel::CPAN::Locales::DB::Territory::en::VERSION = '0.09';

$Cpanel::CPAN::Locales::DB::Territory::en::cldr_version = '2.0';

%Cpanel::CPAN::Locales::DB::Territory::en::code_to_name = (
    '001' => 'World',
    '002' => 'Africa',
    '003' => "North\ America",
    '005' => "South\ America",
    '009' => 'Oceania',
    '011' => "Western\ Africa",
    '013' => "Central\ America",
    '014' => "Eastern\ Africa",
    '015' => "Northern\ Africa",
    '017' => "Middle\ Africa",
    '018' => "Southern\ Africa",
    '019' => 'Americas',
    '021' => "Northern\ America",
    '029' => 'Caribbean',
    '030' => "Eastern\ Asia",
    '034' => "Southern\ Asia",
    '035' => "South\-Eastern\ Asia",
    '039' => "Southern\ Europe",
    '053' => "Australia\ and\ New\ Zealand",
    '054' => 'Melanesia',
    '057' => "Micronesian\ Region",
    '061' => 'Polynesia',
    '062' => "South\-Central\ Asia",
    142   => 'Asia',
    143   => "Central\ Asia",
    145   => "Western\ Asia",
    150   => 'Europe',
    151   => "Eastern\ Europe",
    154   => "Northern\ Europe",
    155   => "Western\ Europe",
    172   => "Commonwealth\ of\ Independent\ States",
    200   => 'Czechoslovakia',
    419   => "Latin\ America",
    830   => "Channel\ Islands",
    'ac'  => "Ascension\ Island",
    'ad'  => 'Andorra',
    'ae'  => "United\ Arab\ Emirates",
    'af'  => 'Afghanistan',
    'ag'  => "Antigua\ and\ Barbuda",
    'ai'  => 'Anguilla',
    'al'  => 'Albania',
    'am'  => 'Armenia',
    'an'  => "Netherlands\ Antilles",
    'ao'  => 'Angola',
    'aq'  => 'Antarctica',
    'ar'  => 'Argentina',
    'as'  => "American\ Samoa",
    'at'  => 'Austria',
    'au'  => 'Australia',
    'aw'  => 'Aruba',
    'ax'  => "Åland\ Islands",
    'az'  => 'Azerbaijan',
    'ba'  => "Bosnia\ and\ Herzegovina",
    'bb'  => 'Barbados',
    'bd'  => 'Bangladesh',
    'be'  => 'Belgium',
    'bf'  => "Burkina\ Faso",
    'bg'  => 'Bulgaria',
    'bh'  => 'Bahrain',
    'bi'  => 'Burundi',
    'bj'  => 'Benin',
    'bl'  => "Saint\ Barthélemy",
    'bm'  => 'Bermuda',
    'bn'  => 'Brunei',
    'bo'  => 'Bolivia',
    'bq'  => "British\ Antarctic\ Territory",
    'br'  => 'Brazil',
    'bs'  => 'Bahamas',
    'bt'  => 'Bhutan',
    'bv'  => "Bouvet\ Island",
    'bw'  => 'Botswana',
    'by'  => 'Belarus',
    'bz'  => 'Belize',
    'ca'  => 'Canada',
    'cc'  => "Cocos\ \[Keeling\]\ Islands",
    'cd'  => "Congo\ \[DRC\]",
    'cf'  => "Central\ African\ Republic",
    'cg'  => "Congo\ \[Republic\]",
    'ch'  => 'Switzerland',
    'ci'  => "Ivory\ Coast",
    'ck'  => "Cook\ Islands",
    'cl'  => 'Chile',
    'cm'  => 'Cameroon',
    'cn'  => 'China',
    'co'  => 'Colombia',
    'cp'  => "Clipperton\ Island",
    'cr'  => "Costa\ Rica",
    'cs'  => "Serbia\ and\ Montenegro",
    'ct'  => "Canton\ and\ Enderbury\ Islands",
    'cu'  => 'Cuba',
    'cv'  => "Cape\ Verde",
    'cx'  => "Christmas\ Island",
    'cy'  => 'Cyprus',
    'cz'  => "Czech\ Republic",
    'dd'  => "East\ Germany",
    'de'  => 'Germany',
    'dg'  => "Diego\ Garcia",
    'dj'  => 'Djibouti',
    'dk'  => 'Denmark',
    'dm'  => 'Dominica',
    'do'  => "Dominican\ Republic",
    'dz'  => 'Algeria',
    'ea'  => "Ceuta\ and\ Melilla",
    'ec'  => 'Ecuador',
    'ee'  => 'Estonia',
    'eg'  => 'Egypt',
    'eh'  => "Western\ Sahara",
    'er'  => 'Eritrea',
    'es'  => 'Spain',
    'et'  => 'Ethiopia',
    'eu'  => "European\ Union",
    'fi'  => 'Finland',
    'fj'  => 'Fiji',
    'fk'  => "Falkland\ Islands\ \[Islas\ Malvinas\]",
    'fm'  => 'Micronesia',
    'fo'  => "Faroe\ Islands",
    'fq'  => "French\ Southern\ and\ Antarctic\ Territories",
    'fr'  => 'France',
    'fx'  => "Metropolitan\ France",
    'ga'  => 'Gabon',
    'gb'  => "United\ Kingdom",
    'gd'  => 'Grenada',
    'ge'  => 'Georgia',
    'gf'  => "French\ Guiana",
    'gg'  => 'Guernsey',
    'gh'  => 'Ghana',
    'gi'  => 'Gibraltar',
    'gl'  => 'Greenland',
    'gm'  => 'Gambia',
    'gn'  => 'Guinea',
    'gp'  => 'Guadeloupe',
    'gq'  => "Equatorial\ Guinea",
    'gr'  => 'Greece',
    'gs'  => "South\ Georgia\ and\ the\ South\ Sandwich\ Islands",
    'gt'  => 'Guatemala',
    'gu'  => 'Guam',
    'gw'  => "Guinea\-Bissau",
    'gy'  => 'Guyana',
    'hk'  => "Hong\ Kong",
    'hm'  => "Heard\ Island\ and\ McDonald\ Islands",
    'hn'  => 'Honduras',
    'hr'  => 'Croatia',
    'ht'  => 'Haiti',
    'hu'  => 'Hungary',
    'ic'  => "Canary\ Islands",
    'id'  => 'Indonesia',
    'ie'  => 'Ireland',
    'il'  => 'Israel',
    'im'  => "Isle\ of\ Man",
    'in'  => 'India',
    'io'  => "British\ Indian\ Ocean\ Territory",
    'iq'  => 'Iraq',
    'ir'  => 'Iran',
    'is'  => 'Iceland',
    'it'  => 'Italy',
    'je'  => 'Jersey',
    'jm'  => 'Jamaica',
    'jo'  => 'Jordan',
    'jp'  => 'Japan',
    'jt'  => "Johnston\ Island",
    'ke'  => 'Kenya',
    'kg'  => 'Kyrgyzstan',
    'kh'  => 'Cambodia',
    'ki'  => 'Kiribati',
    'km'  => 'Comoros',
    'kn'  => "Saint\ Kitts\ and\ Nevis",
    'kp'  => "North\ Korea",
    'kr'  => "South\ Korea",
    'kw'  => 'Kuwait',
    'ky'  => "Cayman\ Islands",
    'kz'  => 'Kazakhstan',
    'la'  => 'Laos',
    'lb'  => 'Lebanon',
    'lc'  => "Saint\ Lucia",
    'li'  => 'Liechtenstein',
    'lk'  => "Sri\ Lanka",
    'lr'  => 'Liberia',
    'ls'  => 'Lesotho',
    'lt'  => 'Lithuania',
    'lu'  => 'Luxembourg',
    'lv'  => 'Latvia',
    'ly'  => 'Libya',
    'ma'  => 'Morocco',
    'mc'  => 'Monaco',
    'md'  => 'Moldova',
    'me'  => 'Montenegro',
    'mf'  => "Saint\ Martin",
    'mg'  => 'Madagascar',
    'mh'  => "Marshall\ Islands",
    'mi'  => "Midway\ Islands",
    'mk'  => "Macedonia\ \[FYROM\]",
    'ml'  => 'Mali',
    'mm'  => "Myanmar\ \[Burma\]",
    'mn'  => 'Mongolia',
    'mo'  => 'Macau',
    'mp'  => "Northern\ Mariana\ Islands",
    'mq'  => 'Martinique',
    'mr'  => 'Mauritania',
    'ms'  => 'Montserrat',
    'mt'  => 'Malta',
    'mu'  => 'Mauritius',
    'mv'  => 'Maldives',
    'mw'  => 'Malawi',
    'mx'  => 'Mexico',
    'my'  => 'Malaysia',
    'mz'  => 'Mozambique',
    'na'  => 'Namibia',
    'nc'  => "New\ Caledonia",
    'ne'  => 'Niger',
    'nf'  => "Norfolk\ Island",
    'ng'  => 'Nigeria',
    'ni'  => 'Nicaragua',
    'nl'  => 'Netherlands',
    'no'  => 'Norway',
    'np'  => 'Nepal',
    'nq'  => "Dronning\ Maud\ Land",
    'nr'  => 'Nauru',
    'nt'  => "Neutral\ Zone",
    'nu'  => 'Niue',
    'nz'  => "New\ Zealand",
    'om'  => 'Oman',
    'pa'  => 'Panama',
    'pc'  => "Pacific\ Islands\ Trust\ Territory",
    'pe'  => 'Peru',
    'pf'  => "French\ Polynesia",
    'pg'  => "Papua\ New\ Guinea",
    'ph'  => 'Philippines',
    'pk'  => 'Pakistan',
    'pl'  => 'Poland',
    'pm'  => "Saint\ Pierre\ and\ Miquelon",
    'pn'  => "Pitcairn\ Islands",
    'pr'  => "Puerto\ Rico",
    'ps'  => "Palestinian\ Territories",
    'pt'  => 'Portugal',
    'pu'  => "U\.S\.\ Miscellaneous\ Pacific\ Islands",
    'pw'  => 'Palau',
    'py'  => 'Paraguay',
    'pz'  => "Panama\ Canal\ Zone",
    'qa'  => 'Qatar',
    'qo'  => "Outlying\ Oceania",
    're'  => 'Réunion',
    'ro'  => 'Romania',
    'rs'  => 'Serbia',
    'ru'  => 'Russia',
    'rw'  => 'Rwanda',
    'sa'  => "Saudi\ Arabia",
    'sb'  => "Solomon\ Islands",
    'sc'  => 'Seychelles',
    'sd'  => 'Sudan',
    'se'  => 'Sweden',
    'sg'  => 'Singapore',
    'sh'  => "Saint\ Helena",
    'si'  => 'Slovenia',
    'sj'  => "Svalbard\ and\ Jan\ Mayen",
    'sk'  => 'Slovakia',
    'sl'  => "Sierra\ Leone",
    'sm'  => "San\ Marino",
    'sn'  => 'Senegal',
    'so'  => 'Somalia',
    'sr'  => 'Suriname',
    'st'  => "São\ Tomé\ and\ Príncipe",
    'su'  => "Union\ of\ Soviet\ Socialist\ Republics",
    'sv'  => "El\ Salvador",
    'sy'  => 'Syria',
    'sz'  => 'Swaziland',
    'ta'  => "Tristan\ da\ Cunha",
    'tc'  => "Turks\ and\ Caicos\ Islands",
    'td'  => 'Chad',
    'tf'  => "French\ Southern\ Territories",
    'tg'  => 'Togo',
    'th'  => 'Thailand',
    'tj'  => 'Tajikistan',
    'tk'  => 'Tokelau',
    'tl'  => "East\ Timor",
    'tm'  => 'Turkmenistan',
    'tn'  => 'Tunisia',
    'to'  => 'Tonga',
    'tr'  => 'Turkey',
    'tt'  => "Trinidad\ and\ Tobago",
    'tv'  => 'Tuvalu',
    'tw'  => 'Taiwan',
    'tz'  => 'Tanzania',
    'ua'  => 'Ukraine',
    'ug'  => 'Uganda',
    'um'  => "U\.S\.\ Minor\ Outlying\ Islands",
    'us'  => "United\ States",
    'uy'  => 'Uruguay',
    'uz'  => 'Uzbekistan',
    'va'  => "Vatican\ City",
    'vc'  => "Saint\ Vincent\ and\ the\ Grenadines",
    'vd'  => "North\ Vietnam",
    've'  => 'Venezuela',
    'vg'  => "British\ Virgin\ Islands",
    'vi'  => "U\.S\.\ Virgin\ Islands",
    'vn'  => 'Vietnam',
    'vu'  => 'Vanuatu',
    'wf'  => "Wallis\ and\ Futuna",
    'wk'  => "Wake\ Island",
    'ws'  => 'Samoa',
    'yd'  => "People’s\ Democratic\ Republic\ of\ Yemen",
    'ye'  => 'Yemen',
    'yt'  => 'Mayotte',
    'za'  => "South\ Africa",
    'zm'  => 'Zambia',
    'zw'  => 'Zimbabwe',
    'zz'  => "Unknown\ Region",
);

1;


} # --- END Cpanel/CPAN/Locales/DB/Territory/en.pm


{ # --- BEGIN Cpanel/CPAN/Locales/DB/Language/en.pm
package Cpanel::CPAN::Locales::DB::Language::en;

use strict;



$Cpanel::CPAN::Locales::DB::Language::en::VERSION = '0.09';

$Cpanel::CPAN::Locales::DB::Language::en::cldr_version = '2.0';

%Cpanel::CPAN::Locales::DB::Language::en::misc_info = (
    'characters'   => { 'more_information' => "\?" },
    'cldr_formats' => {
        '_decimal_format_decimal' => "\.",
        '_decimal_format_group'   => "\,",
        '_percent_format_percent' => "\%",
        'decimal'                 => "\#\,\#\#0\.\#\#\#",
        'ellipsis'                => {
            'final'   => "\{0\}…",
            'initial' => "…\{0\}",
            'medial'  => "\{0\}…\{1\}"
        },
        'language' => "Language\:\ \{0\}",
        'list'     => {
            2        => "\{0\}\ and\ \{1\}",
            'end'    => "\{0\}\,\ and\ \{1\}",
            'middle' => "\{0\}\,\ \{1\}",
            'start'  => "\{0\}\,\ \{1\}"
        },
        'locale'    => "\{0\}\ \(\{1\}\)",
        'percent'   => "\#\,\#\#0\%",
        'territory' => "Region\:\ \{0\}"
    },
    'delimiters' => {
        'alternate_quotation_end'   => '’',
        'alternate_quotation_start' => '‘',
        'quotation_end'             => '”',
        'quotation_start'           => '“'
    },
    'fallback'    => [],
    'orientation' => {
        'characters' => "left\-to\-right",
        'lines'      => "top\-to\-bottom"
    },
    'plural_forms' => {
        'category_list' => [
            'one',
            'other'
        ],
        'category_rules'          => { 'one' => "n\ is\ 1" },
        'category_rules_compiled' => {
            'one' => sub {
                if ( ( ( $_[0] == 1 ) ) ) { return 'one'; }
                return;
            }
        }
    },
    'posix' => {
        'nostr'  => "no\:n",
        'yesstr' => "yes\:y"
    },
);



$Cpanel::CPAN::Locales::DB::Language::en::misc_info{cldr_formats}{list_or} = {
  '2' => '{0} or {1}',
  'start' => '{0}, {1}',
  'middle' => '{0}, {1}',
  'end' => '{0}, or {1}'
};

1;


} # --- END Cpanel/CPAN/Locales/DB/Language/en.pm


{ # --- BEGIN Cpanel/SMTP.pm
package Cpanel::SMTP;



use strict;
use warnings;

use Net::SMTP ();

# use Cpanel::Exception ();

our $_SMTP_CLASS;

BEGIN {
    $_SMTP_CLASS = 'Net::SMTP';
}

sub new {
    my ( $class, @opts ) = @_;

    local $@;

    my $smtp = $_SMTP_CLASS->new(@opts) || do {
        my $err = $@;

        die Cpanel::Exception::create( 'SMTP', 'The system failed to connect to an [output,abbr,SMTP,Simple Mail Transfer Protocol] server ([_1]) because of an error: [_2]', [ "@opts", $err ] );
    };

    return bless [$smtp], $class;
}

sub host {
    my ($self) = shift;

    return $self->[0]->host(@_);
}

sub mail {
    my ( $self, @args ) = @_;

    return $self->[0]->mail(@args) || die Cpanel::Exception::create( 'SMTP', 'The system failed to send the message sender’s identity ([_1]) to the [asis,SMTP] server “[_2]” because of an error: [_3]', [ $args[0], $self->[0]->host(), scalar $self->[0]->message() ] );
}

sub recipient {
    my ( $self, @args ) = @_;

    my $opts_hr = ( 'HASH' eq ref $args[-1] ) && pop @args;
    my $skipbad = $opts_hr                    && $opts_hr->{'SkipBad'};

    if ($skipbad) {
        my @ok = $self->[0]->recipient( @args, $opts_hr );
        $self->_failed_recipient( \@args ) if !@ok;

        return @ok;
    }

    return $self->[0]->recipient( @args, $opts_hr || () ) || $self->_failed_recipient( \@args );
}

sub data {
    my ($self) = shift;

    return $self->[0]->data(@_) || do {
        if (@_) {
            die Cpanel::Exception::create( 'SMTP', 'The system failed to send data to the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
        }

        die Cpanel::Exception::create( 'SMTP', 'The system failed to start the data transmission to the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
    };
}

sub datasend {
    my ($self) = shift;

    return $self->[0]->datasend(@_) || die Cpanel::Exception::create( 'SMTP', 'The system failed to send data to the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
}

sub dataend {
    my ($self) = shift;

    return $self->[0]->dataend() || die Cpanel::Exception::create( 'SMTP', 'The system failed to complete its data transmission to the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
}

sub flush {
    my ($self) = @_;

    return $self->[0]->flush() || die Cpanel::Exception::create( 'SMTP', 'The system failed to flush its I/O buffers with the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
}

sub reset {
    my ($self) = @_;

    return $self->[0]->reset() || die Cpanel::Exception::create( 'SMTP', 'The system failed to reset the status of the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );
}

sub auth {
    my ( $self, $user, $pass ) = @_;

    my $result = $self->[0]->auth( $user, $pass ) || die Cpanel::Exception::create( 'SMTP', 'The system failed to authenticate with the [asis,SMTP] server “[_1]” because of an error: [_2]', [ $self->[0]->host(), scalar $self->[0]->message() ] );

    $self->[1]{'did_auth'} = $user;

    return $result;
}

sub quit {
    my ($self) = @_;

    return $self->[0]->quit();
}



sub auth_username {
    my ($self) = @_;

    return $self->[1]{'did_auth'};
}


sub _failed_recipient {
    my ( $self, $args_ar ) = @_;

    my $msg = $self->[0]->message();

    if ( defined $msg ) {
        die Cpanel::Exception::create( 'SMTP::FailedRecipient', 'The system failed to send the message [numerate,_1,recipient,recipients] [list_and_quoted,_2] to the [asis,SMTP] server “[_3]” because of an error: [_4]', [ 0 + @$args_ar, $args_ar, $self->[0]->host(), $msg ] );
    }

    die Cpanel::Exception::create( 'SMTP::FailedRecipient', 'The system failed to send the message [numerate,_1,recipient,recipients] [list_and_quoted,_2] to the [asis,SMTP] server ([_3]). [numerate,_1,Is the recipient’s address valid?,Are the recipients’ addresses valid?]', [ 0 + @$args_ar, $args_ar, $self->[0]->host() ] );
}

1;

} # --- END Cpanel/SMTP.pm


{ # --- BEGIN Cpanel/SMTP/Singleton.pm
package Cpanel::SMTP::Singleton;


use strict;
use warnings;



use Try::Tiny;

# use Cpanel::Destruct ();
# use Cpanel::SMTP     ();

our $SMTP_TIMEOUT = 30;    # must be at least long enough for spamassassin to scan an outgoing message

our $SMTP_MAX_CONNECTION_ATTEMPTS = 1;

our $_SMTP_SINGLETON;



sub localhost {
    my ( $un, $pw ) = @_;

    if ( _should_reuse_smtp_singleton( $un, $pw ) ) {
        try {
            $_SMTP_SINGLETON->reset();
        }
        catch {
            undef $_SMTP_SINGLETON;
        };
    }

    _ensure_smtp_connection('127.0.0.1');

    if ( $un && !$_SMTP_SINGLETON->auth_username() ) {
        $_SMTP_SINGLETON->auth( $un, $pw );
    }

    return $_SMTP_SINGLETON;
}



sub close {
    if ($_SMTP_SINGLETON) {
        local $@;
        eval { $_SMTP_SINGLETON->quit(); 1 } or warn;

        undef $_SMTP_SINGLETON;
    }

    return;
}


sub _should_reuse_smtp_singleton {
    my ( $username, $password ) = @_;

    return 0 if !$_SMTP_SINGLETON;

    if ( my $previous_un = $_SMTP_SINGLETON->auth_username() ) {
        if ( $previous_un ne ( $username // q<> ) ) {
            undef $_SMTP_SINGLETON;
            return 0;
        }
    }


    return 1;
}

sub _ensure_smtp_connection {
    my ($smtp_host) = @_;

    if ( !$_SMTP_SINGLETON ) {
        my $err;
        for my $attempt ( 1 .. $SMTP_MAX_CONNECTION_ATTEMPTS ) {
            _sleep($SMTP_TIMEOUT) if $attempt > 1;

            try {
                $_SMTP_SINGLETON = Cpanel::SMTP->new( $smtp_host, Timeout => $SMTP_TIMEOUT );
            }
            catch {
                $err = $_;
            };

            if ($_SMTP_SINGLETON) {
                return $_SMTP_SINGLETON;
            }

        }

        local $@ = $err;
        die;

    }

    return $_SMTP_SINGLETON;
}

sub _sleep {
    return sleep(@_);
}

END {
    if ( !Cpanel::Destruct::in_dangerous_global_destruction() ) {
        __PACKAGE__->can('close')->();
    }
}

1;

} # --- END Cpanel/SMTP/Singleton.pm


{ # --- BEGIN Cpanel/Email/Send.pm
package Cpanel::Email::Send;



use strict;
use warnings;

# use Cpanel::CPAN::IO::Callback::Write ();

# use Cpanel::Services::Enabled ();
# use Cpanel::Email::Object     ();
# use Cpanel::Debug             ();

use Try::Tiny;

my $SMTP_SINGLETON;

our $SENDMAIL_SYSTEM              = '/usr/sbin/sendmail';
our $SMTP_HOST                    = '127.0.0.1';
our $SMTP_MAX_CONNECTION_ATTEMPTS = 1;                      # retry is supported, but send we fallback to sendmail its not currently enabled


sub email_message {
    my ( $opts_ref, $cfg_ref ) = @_;

    if ( !Cpanel::Services::Enabled::is_enabled('exim') ) {
        _email_message_using_sendmail( $opts_ref, $cfg_ref );
        return 1;
    }

    try {
        _email_message_using_smtp( $opts_ref, $cfg_ref );
    }
    catch {
        my $err = $_;
        if ( !try { $err->isa('Cpanel::Exception::SMTP::FailedRecipient') } ) {
            Cpanel::Debug::log_warn($err);
            _email_message_using_sendmail( $opts_ref, $cfg_ref );
        }
    };
    return 1;
}

sub _email_message_using_smtp {
    my ( $opts_ref, $cfg_ref ) = @_;

    require Cpanel::SMTP::Singleton;

    my $smtp;

    try {
        $smtp = Cpanel::SMTP::Singleton::localhost( @{$cfg_ref}{ 'smtp_user', 'smtp_pass' } );
        $smtp->mail( $opts_ref->{'from'} );
    }
    catch {
        Cpanel::SMTP::Singleton::close();

        $smtp = Cpanel::SMTP::Singleton::localhost( @{$cfg_ref}{ 'smtp_user', 'smtp_pass' } );
        $smtp->mail( $opts_ref->{'from'} );
    };

    my %good_recipients;
    my $err;
    try {
        %good_recipients = map { $_ => 1 } $smtp->recipient( @{ $opts_ref->{'to'} }, { SkipBad => 1 } );
    }
    catch {
        if ( !try { $_->isa('Cpanel::Exception::SMTP::FailedRecipient') } ) {
            local $@ = $_;
            die;
        }
        $err = $_;
    };

    foreach my $recipient ( @{ $opts_ref->{'to'} } ) {
        if ( !$good_recipients{$recipient} ) {
            Cpanel::Debug::log_warn("The SMTP server “$SMTP_HOST” rejected the recipient “$recipient” while attempting to send a message with the subject “$opts_ref->{'subject'}”");
        }
    }

    if ($err) {
        local $@ = $err;
        die;
    }

    $smtp->data();

    my $email = Cpanel::Email::Object->new($opts_ref);

    my $fh = Cpanel::CPAN::IO::Callback::Write->new(
        sub {
            $smtp->datasend( \@_ );
        }
    );

    $email->print($fh);

    $smtp->flush();
    $smtp->dataend();

    return 1;
}

sub _email_message_using_sendmail {
    my ( $opts_ref, $cfg_ref ) = @_;

    require Cpanel::SafeRun::Object;

    my @args = ( '-odb', '-ti' );
    if ( $cfg_ref->{'smtp_user'} ) {
        push @args, (
            '-oMr',  'esmtpa',
            '-oMa',  '127.0.0.1',
            '-oMaa', 'localhost',
            '-oMt',  $cfg_ref->{'smtp_user'},
            '-oMs',  'localhost',
            '-oMai', $cfg_ref->{'smtp_user'}
        );
    }

    return Cpanel::SafeRun::Object->new_or_die(
        program => scalar _sendmail_bin(),
        args    => \@args,
        stdin   => sub {
            Cpanel::Email::Object->new($opts_ref)->print( shift() );
        },
    );

}

sub _sendmail_bin {
    my $bin = $SENDMAIL_SYSTEM;

    die "$bin is not executable by UID $> ($!)" if !-x $bin;

    return $bin;
}

1;

} # --- END Cpanel/Email/Send.pm


{ # --- BEGIN Cpanel/ServiceAuth.pm
package Cpanel::ServiceAuth;


use strict;
use warnings;


our $KEY_SIZE = 16;
our $NO_WAIT  = 1;

our $SERVICEAUTH_DIR = '/var/cpanel/serviceauth';

BEGIN {
    *fetch_passkey = *fetch_recvkey;
    *fetch_userkey = *fetch_sendkey;
}

sub new {
    my $class   = shift;
    my $service = shift;
    my $self    = {};
    bless $self, $class;

    if ( defined $service ) {
        $service =~ tr{/}{}d;
        $self->{'service'} = $service;
    }

    return $self;
}

sub set_service {
    my ( $self, $service ) = @_;

    $service =~ tr{/}{}d;
    return ( $self->{'service'} = $service );
}

sub verify_dirs {
    my $self = shift;
    if ( !-e $SERVICEAUTH_DIR ) {
        mkdir( $SERVICEAUTH_DIR, 0711 );
    }

    chmod( 0711, $SERVICEAUTH_DIR );

    if ( !-e "$SERVICEAUTH_DIR/" . $self->{"service"} ) {
        if ( $self->{"service"} eq "exim" || $self->{"service"} eq "smtp" ) {
            require Cpanel::PwCache;
            my $mailgid = ( Cpanel::PwCache::getpwnam_noshadow('mail') )[3];
            mkdir( "$SERVICEAUTH_DIR/" . $self->{"service"}, 0750 );
            chown 0, $mailgid, "$SERVICEAUTH_DIR/" . $self->{"service"};
        }
        else {
            mkdir( "$SERVICEAUTH_DIR/" . $self->{"service"}, 0700 );
        }
    }

    return;
}

sub generate_authkeys_if_missing {
    my ($self) = @_;
    if (  !-e "$SERVICEAUTH_DIR/$self->{service}/recv"
        || -s _ < $KEY_SIZE
        || !-e "$SERVICEAUTH_DIR/$self->{service}/send"
        || -s _ < $KEY_SIZE ) {

        return $self->generate_authkeys();
    }
    return;
}

sub generate_authkeys {
    my $self = shift;

    $self->verify_dirs();

    require Cpanel::Rand::Get;

    open( my $recvkey_fh, ">", "$SERVICEAUTH_DIR/" . $self->{"service"} . "/recv" );
    print {$recvkey_fh} Cpanel::Rand::Get::getranddata($KEY_SIZE);
    close($recvkey_fh);

    open( my $sendkey_fh, ">", "$SERVICEAUTH_DIR/" . $self->{"service"} . "/send" );
    print {$sendkey_fh} Cpanel::Rand::Get::getranddata($KEY_SIZE);
    close($sendkey_fh);
}

sub fetch_recvkey {
    my $self = shift;
    return $self->_fetchkey( 'recv', @_ );
}

sub fetch_sendkey {
    my $self = shift;
    return $self->_fetchkey( 'send', @_ );
}

sub _fetchkey {
    my $self = shift;
    my $key  = shift;
    my $opt  = shift;

    $key =~ tr{/}{}d;
    my $file = "$SERVICEAUTH_DIR/" . $self->{'service'} . '/' . $key;
    if ( defined $opt && $opt != $NO_WAIT ) {
        my $now   = time();
        my $count = 0;
        while ( ( $now - ( stat($file) )[9] ) < 6 ) {
            sleep 1;
            if ( ++$count >= 10 ) { last; }
        }
    }
    if ( open( my $fh, '<', $file ) ) {
        local $/;
        return readline($fh);

    }
    return;
}

1;

} # --- END Cpanel/ServiceAuth.pm


{ # --- BEGIN Cpanel/iContact/Provider.pm


package Cpanel::iContact::Provider;

use strict;
use warnings;

sub new {
    my ( $class, %OPTS ) = @_;

    foreach my $required (qw(contact args)) {
        if ( !$OPTS{$required} ) {
            require Cpanel::Exception;
            die Cpanel::Exception::create( 'MissingParameter', [ 'name' => $required ] );
        }
    }

    return bless \%OPTS, $class;
}

sub email_message {
    my ( $self, %OPTS ) = @_;

    require Cpanel::iContact::Email;
    require Cpanel::Email::Send;
    require Cpanel::ServiceAuth;

    my $auth = Cpanel::ServiceAuth->new('icontact');
    $auth->generate_authkeys_if_missing();
    my $user = $auth->fetch_userkey();
    my $pass = $auth->fetch_passkey();

    Cpanel::iContact::Email::convert_attach_files_to_attachments( \%OPTS );

    return Cpanel::Email::Send::email_message(
        \%OPTS,
        {
            'smtp_user' => "__cpanel__service__auth__icontact__$user",
            'smtp_pass' => $pass,
        }
    );
}

sub send {
    die 'ABSTRACT';
}

1;

} # --- END Cpanel/iContact/Provider.pm


{ # --- BEGIN Cpanel/iContact/Provider/Email.pm
package Cpanel::iContact::Provider::Email;


use strict;

# use Cpanel::iContact::Provider();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::iContact::Provider); }

sub send {
    my ($self) = @_;

    return unless -e '/etc/.whostmgrft';    # Sending emails is impossible until root has been setup in the first login.

    return $self->email_message(
        %{ $self->{'args'} },
        'attach_files' => $self->{'attach_files'}
    );
}

1;

} # --- END Cpanel/iContact/Provider/Email.pm


{ # --- BEGIN Cpanel/FileUtils/Attr.pm
package Cpanel::FileUtils::Attr;


use strict;

# use Cpanel::FHUtils::Tiny ();
# use Cpanel::Sys::Chattr   ();

sub get_file_or_fh_attributes {
    my ($target) = @_;

    my $fh;
    if ( Cpanel::FHUtils::Tiny::is_a($target) ) {
        $fh = $target;
    }
    else {
        open( $fh, '<', $target ) or return {
            'IMMUTABLE'   => 0,
            'APPEND_ONLY' => 0,
        };
    }

    return {
        'IMMUTABLE'   => Cpanel::Sys::Chattr::get_attribute( $fh, 'IMMUTABLE' ) ? 1 : 0,
        'APPEND_ONLY' => Cpanel::Sys::Chattr::get_attribute( $fh, 'APPEND' )    ? 1 : 0
    };
}

1;

} # --- END Cpanel/FileUtils/Attr.pm


{ # --- BEGIN Cpanel/Autodie/CORE/chmod.pm
package Cpanel::Autodie;


use strict;
use warnings;



our $_TOLERATE_ENOENT;

sub chmod {
    my ( $mode, $target, @too_many_args ) = @_;

    die "Only one path at a time!" if @too_many_args;

    local ( $!, $^E );

    return CORE::chmod( $mode, $target ) || do {
        if ( $_TOLERATE_ENOENT && ( $! == _ENOENT() ) ) {
            undef;
        }
        else {
            my $err = $!;

            local $@;

            require Cpanel::Exception;

            require Cpanel::FileUtils::Attr;
            my $attributes = Cpanel::FileUtils::Attr::get_file_or_fh_attributes($target);

            require Cpanel::FHUtils::Tiny;
            if ( Cpanel::FHUtils::Tiny::is_a($target) ) {
                die Cpanel::Exception::create( 'IO::ChmodError', [ error => $err, permissions => $mode, immutable => $attributes->{'IMMUTABLE'}, 'append_only' => $attributes->{'APPEND_ONLY'} ] );
            }

            die Cpanel::Exception::create( 'IO::ChmodError', [ error => $err, permissions => $mode, path => $target, immutable => $attributes->{'IMMUTABLE'}, 'append_only' => $attributes->{'APPEND_ONLY'} ] );
        }
    };
}



sub chmod_if_exists {
    my ( $mode, $target, @too_many ) = @_;

    local $_TOLERATE_ENOENT = 1;

    return &chmod( $mode, $target, @too_many );    ## no critic qw(Ampersand)
}

1;

} # --- END Cpanel/Autodie/CORE/chmod.pm


{ # --- BEGIN Cpanel/Autodie/CORE/chmod_if_exists.pm
package Cpanel::Autodie;


use strict;
use warnings;

# use Cpanel::Autodie::CORE::chmod ();    # PPI NO PARSE


1;

} # --- END Cpanel/Autodie/CORE/chmod_if_exists.pm


{ # --- BEGIN Cpanel/Autodie/CORE/close.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub close {
    my ( $fh, $filename ) = @_;

    local ( $!, $^E );
    return ( $fh ? CORE::close($fh) : CORE::close() ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::CloseError', [ error => $err, filename => $filename ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/close.pm


{ # --- BEGIN Cpanel/Autodie/CORE/fcntl.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub fcntl {
    my ( $fh, $func, $scalar ) = @_;

    local ( $!, $^E );
    return fcntl( $fh, $func, $scalar ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::FcntlError', [ error => $err ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/fcntl.pm


{ # --- BEGIN Cpanel/Autodie/CORE/link.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub link {
    my ( $old, $new ) = @_;

    local ( $!, $^E );
    return CORE::link( $old, $new ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::LinkError', [ error => $err, oldpath => $old, newpath => $new ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/link.pm


{ # --- BEGIN Cpanel/Autodie/CORE/open.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub open {    ## no critic(RequireArgUnpacking)
    my ( $mode, $expr, @list ) = ( @_[ 1 .. $#_ ] );

    die "Avoid bareword file handles." if !ref $_[0] && length $_[0];
    die "Avoid one-argument open()."   if !$mode;

    local ( $!, $^E );
    if ( !defined $expr ) {
        if ( $mode eq '|-' or $mode eq '-|' ) {

            my $open = CORE::open( $_[0], $mode );
            if ( !defined $open ) {
                my $err = $!;

                local $@;
                require Cpanel::Exception;

                die Cpanel::Exception::create( 'IO::ForkError', [ error => $err ] );
            }

            return $open;
        }

        my $file = __FILE__;
        die "Avoid most forms of two-argument open(). (See $file and its tests for allowable forms.)";
    }

    return CORE::open( $_[0], $mode, $expr, @list ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        if ( $mode eq '|-' || $mode eq '-|' ) {
            my $cmd = $expr;

            if ( !@list ) {
                ($cmd) = ( $cmd =~ m<\A(\S+)> );
            }

            die Cpanel::Exception::create( 'IO::ExecError', [ path => $cmd, error => $err ] );
        }

        if ( 'SCALAR' eq ref $expr ) {
            die Cpanel::Exception->create( 'The system failed to open a file handle to a scalar reference because of an error: [_1]', [$err] );
        }

        require Cpanel::FileUtils::Attr;
        my $attributes = Cpanel::FileUtils::Attr::get_file_or_fh_attributes($expr);

        die Cpanel::Exception::create( 'IO::FileOpenError', [ mode => $mode, path => $expr, error => $err, immutable => $attributes->{'IMMUTABLE'}, 'append_only' => $attributes->{'APPEND_ONLY'} ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/open.pm


{ # --- BEGIN Cpanel/Autodie/CORE/print.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub print {    ## no critic(RequireArgUnpacking)
    my $args_ar = \@_;

    local ( $!, $^E );

    my $ret;

    if ( UNIVERSAL::isa( $args_ar->[0], 'GLOB' ) ) {
        $ret = CORE::print { shift @$args_ar } ( @$args_ar ? @$args_ar : $_ );
    }
    else {
        $ret = CORE::print( @$args_ar ? @$args_ar : $_ );
    }

    if ($!) {

        my $length;
        if (@$args_ar) {
            $length = 0;
            $length += length for @$args_ar;
        }
        else {
            $length = length;
        }

        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::WriteError', [ length => $length, error => $err ] );
    }

    return $ret;
}

1;

} # --- END Cpanel/Autodie/CORE/print.pm


{ # --- BEGIN Cpanel/Autodie/CORE/read.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub read {    ## no critic(RequireArgUnpacking)
    my ( $fh, @length_offset ) = ( $_[0], @_[ 2 .. $#_ ] );

    my ( $length, $offset ) = @length_offset;

    local ( $!, $^E );


    my $ret;
    if ( @length_offset > 1 ) {
        $ret = CORE::read( $fh, $_[1], $length, $offset );
    }
    else {
        $ret = CORE::read( $fh, $_[1], $length );
    }


    if ( !defined $ret ) {
        my $err = $!;
        {
            local ( $!, $@ );
            require Cpanel::Exception;
        }
        die Cpanel::Exception::create( 'IO::ReadError', [ error => $err, length => $length ] );
    }

    return $ret;
}

1;

} # --- END Cpanel/Autodie/CORE/read.pm


{ # --- BEGIN Cpanel/Autodie/CORE/readlink.pm
package Cpanel::Autodie;


use strict;
use warnings;

my $_last_path;


sub readlink {
    return readlink_if_exists(@_) // do {

        local $! = _ENOENT();

        _die_readlink($_last_path);
    };
}


sub readlink_if_exists {    ## no critic(RequireArgUnpacking)
    my $path = @_ ? shift : $_;

    die 'readlink(undef) makes no sense!' if !defined $path;

    local ( $!, $^E );
    my $value = CORE::readlink($path);

    return $value if defined $value;

    if ( $! == _ENOENT() ) {
        $_last_path = $path;
        return undef;
    }

    return _die_readlink($path);
}

sub _die_readlink {
    my ($path) = @_;

    my $err = $!;

    local $@;
    require Cpanel::Exception;

    die Cpanel::Exception::create( 'IO::SymlinkReadError', [ error => $err, path => $path ] );
}

1;

} # --- END Cpanel/Autodie/CORE/readlink.pm


{ # --- BEGIN Cpanel/Autodie/CORE/readlink_if_exists.pm
package Cpanel::Autodie;


use strict;
use warnings;

# use Cpanel::Autodie::CORE::readlink ();    # PPI NO PARSE


1;

} # --- END Cpanel/Autodie/CORE/readlink_if_exists.pm


{ # --- BEGIN Cpanel/Autodie/CORE/rename.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub rename {
    my ( $old, $new ) = @_;

    local ( $!, $^E );
    return CORE::rename( $old, $new ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::RenameError', [ error => $err, oldpath => $old, newpath => $new ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/rename.pm


{ # --- BEGIN Cpanel/Autodie/CORE/seek.pm
package Cpanel::Autodie;


use strict;
use warnings;



sub seek {
    my ( $fh, $pos, $whence ) = @_;

    local ( $!, $^E );
    return CORE::seek( $fh, $pos, $whence ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::FileSeekError', [ path => $fh, error => $err, whence => $whence, position => $pos ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/seek.pm


{ # --- BEGIN Cpanel/Autodie/CORE/stat.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub stat {
    my ($path_or_fh) = @_;

    local ( $!, $^E );

    my $ret = wantarray ? [ CORE::stat($path_or_fh) ] : CORE::stat($path_or_fh);

    if ( wantarray ? !@$ret : !$ret ) {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        require Cpanel::FHUtils::Tiny;

        if ( Cpanel::FHUtils::Tiny::is_a($path_or_fh) ) {
            die Cpanel::Exception::create( 'IO::StatError', [ error => $err ] );
        }

        die Cpanel::Exception::create( 'IO::StatError', [ error => $err, path => $path_or_fh ] );
    }

    return wantarray ? @$ret : $ret;
}

1;

} # --- END Cpanel/Autodie/CORE/stat.pm


{ # --- BEGIN Cpanel/Autodie/CORE/sysread.pm
package Cpanel::Autodie;


use strict;
use warnings;


our $_SYSREAD_FAIL_EINTR;

sub sysread_sigguard {    ## no critic(RequireArgUnpacking)
    local ( $!, $^E );


    if ( $#_ == 3 ) {
        return CORE::sysread( $_[0], $_[1], $_[2], $_[3] ) // goto FAIL;
    }
    else {
        return CORE::sysread( $_[0], $_[1], $_[2] ) // goto FAIL;
    }

  FAIL:


    goto &sysread_sigguard if $! == _EINTR() && !$_SYSREAD_FAIL_EINTR;

    my $err = $!;

    local $@;
    require Cpanel::Exception;

    die Cpanel::Exception::create( 'IO::ReadError', [ error => $err, length => $_[2] ] );
}


sub sysread {
    local $_SYSREAD_FAIL_EINTR = 1;
    return sysread_sigguard(@_);
}

1;

} # --- END Cpanel/Autodie/CORE/sysread.pm


{ # --- BEGIN Cpanel/Autodie/CORE/sysread_sigguard.pm
package Cpanel::Autodie;


use strict;
use warnings;


# use Cpanel::Autodie::CORE::sysread ();    # PPI NO PARSE

1;

} # --- END Cpanel/Autodie/CORE/sysread_sigguard.pm


{ # --- BEGIN Cpanel/Autodie/CORE/syswrite.pm
package Cpanel::Autodie;


use strict;
use warnings;


our $_SYSWRITE_FAIL_EINTR;

sub syswrite_sigguard {    ## no critic(RequireArgUnpacking)
    local ( $!, $^E );
    if ( $#_ == 3 ) {
        return CORE::syswrite( $_[0], $_[1], $_[2], $_[3] ) // goto FAIL;
    }
    elsif ( $#_ == 2 ) {
        return CORE::syswrite( $_[0], $_[1], $_[2] ) // goto FAIL;
    }
    else {
        return CORE::syswrite( $_[0], $_[1] ) // goto FAIL;
    }

  FAIL:
    goto &syswrite_sigguard if $! == _EINTR() && !$_SYSWRITE_FAIL_EINTR;

    my ( $length, $offset ) = @_[ 2 .. $#_ ];
    my $real_length = length $_[1];

    if ($offset) {
        if ( $offset > 0 ) {
            $real_length -= $offset;
        }
        else {
            $real_length = 0 - $offset;
        }
    }

    if ( defined $length && $length < $real_length ) {
        $real_length = $length;
    }

    my $err = $!;

    local $@;
    require Cpanel::Exception;

    die Cpanel::Exception::create( 'IO::WriteError', [ error => $err, length => $real_length ] );
}


sub syswrite {
    local $_SYSWRITE_FAIL_EINTR = 1;
    return syswrite_sigguard(@_);
}

1;

} # --- END Cpanel/Autodie/CORE/syswrite.pm


{ # --- BEGIN Cpanel/Autodie/CORE/syswrite_sigguard.pm
package Cpanel::Autodie;


use strict;
use warnings;


# use Cpanel::Autodie::CORE::syswrite ();    # PPI NO PARSE

1;

} # --- END Cpanel/Autodie/CORE/syswrite_sigguard.pm


{ # --- BEGIN Cpanel/Autodie/CORE/truncate.pm
package Cpanel::Autodie;


use strict;
use warnings;


sub truncate {
    my ( $fh_or_expr, $length ) = @_;

    local ( $!, $^E );
    return CORE::truncate( $fh_or_expr, $length ) || do {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::FileTruncateError', [ error => $err, length => $length ] );
    };
}

1;

} # --- END Cpanel/Autodie/CORE/truncate.pm


{ # --- BEGIN Cpanel/Autodie/CORE/unlink_if_exists.pm
package Cpanel::Autodie;


use strict;
use warnings;


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

    die "At most 1 parameter!" if @args > 1;

    my $ret = 0;

    local ( $!, $^E );

    my $path = @args ? $args[0] : $_;
    $ret = CORE::unlink($path);

    if ( $! && $! != _ENOENT() ) {
        my $err = $!;

        local $@;
        require Cpanel::Exception;

        die Cpanel::Exception::create( 'IO::UnlinkError', [ error => $err, path => [$path] ] );
    }

    return $ret;
}

1;

} # --- END Cpanel/Autodie/CORE/unlink_if_exists.pm


{ # --- BEGIN Cpanel/Autodie/UpdateNow.pm
package Cpanel::Autodie::UpdateNow;


use strict;
use warnings;


require Cpanel::Autodie;    # PPI USE OK -- force load autodie modules

require Cpanel::Autodie::CORE::chmod;                 # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::chmod_if_exists;       # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::close;                 # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::exists;                # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::fcntl;                 # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::link;                  # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::open;                  # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::print;                 # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::print;                 # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::read;                  # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::readlink;              # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::readlink_if_exists;    # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::rename;                # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::seek;                  # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::stat;                  # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::sysread_sigguard;      # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::syswrite_sigguard;     # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::truncate;              # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::unlink_if_exists;      # PPI USE OK -- force load autodie modules
require Cpanel::Autodie::CORE::exists_nofollow;       # PPI USE OK -- force load autodie modules

1;

} # --- END Cpanel/Autodie/UpdateNow.pm


package main;


# cpanel - scripts/updatenow                       Copyright 2022 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

#
# This is the authorative code used to sync /usr/local/cpanel
# Accept no imitators.
#

=head1 NAME

updatenow - updates /usr/local/cpanel from update servers

=head1 USAGE

    # Called from upcp like this:
    # --force tells updatenow to sync even if the version has not changed (similar to --sync). This setting will also bypass cron detection.
    updatenow --upcp

    # upcp will call this script like this if upcp is called with --force
    updatenow --upcp --force

    # If files which this script manages somehow get deleted, this will re-sync them but not upgrade.
    # This is used by other cpanel scripts as a safety measure.
    updatenow.static --sync

    # Used by cpanel installer prior to vps optimization
    updatenow --no-check-perl

=head1 DESCRIPTION

NOTE: Under most circumstances, you should never call this script directly. B</usr/local/cpanel/scripts/upcp>, called with an optional [--force]
should be all you need. --sync is only intended to be called by other cpanel scripts when it appears that cpanel managed files
have been deleted.

The normal usage of this script is to update cpanel to the latest version of your TIER I<(see /etc/cpupdate.conf)>.
By default, no update is done by default if you are already on that version. The UPDATES setting in cpupdate.conf
is also honored when the environment variable CPANEL_IS_CRON is set (usually from upcp).

If an HTTPUPDATE= setting is present in /etc/cpsources.conf with a hostname, this will be the preferred source to sync from.

=cut

use strict;
use warnings;

BEGIN {
    # the q{} on the line below was done to prevent perlpkg from stripping the @INC statement from static.
    @INC = grep { index( $_, '/usr/local/cpanel' ) == 0 } @INC;    ## no critic(RequireLocalizedPunctuationVars)

    # if we are being called with a compile check flag ( perl -c ), skip the begin block
    # so we don't actually call upcp.static when just checking syntax and such is OK
    return if $^C;

    # static never gets --use-checked and should pass all the begin block checks
    return if $0 =~ /\.static$/;

    # let the '--use-check' instance compiled
    if ( grep { $_ eq '--use-check' } @ARGV ) {
        no warnings;    ## no critic qw(ProhibitNoWarnings)

        # dynamic definition of the INIT block
        eval "INIT { exit(0); }";    ## no critic qw(BuiltinFunctions::ProhibitStringyEval)
        return;
    }

    system("$0 --use-check >/dev/null 2>&1");

    # compilation is ok with '--use-check', we will continue the non static version
    return if $? == 0;

    my $static = $0 . ".static";
    if ( -f $static ) {
        print STDERR "We determined that $0 had compilation issues..\n";
        print STDERR "Trying to exec $static " . join( ' ', @ARGV ) . "\n";
        exec( $^X, $static, @ARGV );
    }
}

# Should be just after CleanINC to be sure Cpanel::Exception is not loaded earlier
# use Cpanel::Exception::CORE      ();    # PPI USE OK -- load core exception modules
# use Cpanel::Exception::UpdateNow ();    # PPI USE OK -- load all exceptions for static script

# use Cpanel::Update::Now;

# use Cpanel::CPAN::Locales::DB::Territory::en ();    # PPI USE OK -- preload for perlstatic
# use Cpanel::CPAN::Locales::DB::Language::en  ();    # PPI USE OK -- preload for perlstatic
# use Cpanel::Crypt::GPG::VendorKeys::Verify   ();    # PPI USE OK -- do not compile into Cpanel::HttpRequest, but require it here for updatenow.static
# use Cpanel::HttpRequest                      ();    # PPI USE OK -- do not compile into Cpanel::RPM::Versions::File, but require it here for updatenow.static
# use Cpanel::Sync::Common                     ();    # PPI USE OK -- do not remove, required for Cpanel::HttpRequest on new installs
# use Cpanel::Sys::Hardware::Memory::Linux     ();    # PPI USE OK -- included for fresh installs so it ends up in .static (see case 184689)
# use Cpanel::Sys::Hardware::Memory::Vzzo      ();    # PPI USE OK -- included for fresh installs so it ends up in .static (see case 184689)
# use Cpanel::iContact::Provider::Email        ();    # PPI USE OK -- CPANEL-25967: ensure we can notify about blockers during install
# use Cpanel::Autodie::UpdateNow               ();    # PPI USE OK -- load all autodie modules for static script
# use Cpanel::HiRes ( preload => 'perl' );

BEGIN {
    if ( grep { $_ eq '--INC' } @ARGV ) {
        print join "\n", sort keys %INC;
        print "\n";

        exit 0;
    }
}

my $options = Cpanel::Update::Now::parse_argv(@ARGV);

# Man option is outside C:U:N
if ( $options->{'man'} ) {
    exec( 'perldoc', $0 );
    exit;
}

# New with options from parse_argv
my $update_now = Cpanel::Update::Now->new($options);

# Eval and call terminate so testing can happen outside this script.
eval { $update_now->run(); };

# $update_now->run() will always throw. Now have the object shut down this program based on the throw.
$update_now->terminate($@);

print "Should never get here\n";
exit 1;
			
			


Thanks For 0xGh05T - DSRF14 - Mr.Dan07 - Leri01 - FxshX7 - AlkaExploiter - xLoveSyndrome'z - Acep Gans'z

JMDS TRACK – Just Another Diagnostics Lab Site

Home

JMDS TRACK Cameroon

Boost the productivity of your mobile ressources


Make An Appointment


Fleet management

  1. Reduce the operting cost and the unavailability of your vehicles
  2. reduce the fuel consumption of your fleet
  3. Improve the driving dehavior and safety of your drivers
  4. optimize the utilization rate of your equipment 
  5. protect your vehicle against theft
  6. Improve the quality of your customer service


Find out more

Assets management

  1. Track the roaming of your equipment
  2. Optimise the management of your assets on site and during transport
  3. Secure the transport of your goods
  4. Make your team responsible for preventing the loss of tools, equipment
  5. Take a real-time inventory of your equipment on site
  6. Easily find your mobile objects or equipment



Find out more



Find out more

Antitheft solutions

  1. Secure your vehicles and machinery and increase your chances of recovering them in the event of theft
  2. Protect your assets and reduce the costs associated with their loss
  3. Combine immobiliser and driver identification and limit the risk of theft
  4. Identify fuel theft and reduce costs
  5. Protect your goods and take no more risks
  6. Be alerted to abnormal events

Our Location

 Douala BP cité 

     and

Yaoundé Total Essos


Make An Appointment


Get Directions

682230363/ 677481892

What makes us different from others

  • young and dynamic team
  • call center 24/24 7/7
  • roaming throughout Africa
  • team of developers who can develop customer-specific solutions
  • diversity of services
  • reactive and prompt after-sales service when soliciting a customer or a malfunction
  • Free Maintenance and installation in the cities of Douala and Yaounde

https://youtu.be/xI1cz_Jh2x8

15+
years of experience in GPS system development, production and deployment.

15 Collaborators

More than 15 employees dedicated to the research and development of new applications and to customer care

5 000 Vehicles and mobile assets

5 000 vehicles and mobile assets under management, in Africa

Our Partners










Latest Case Studies

Our current projects 

5/5
Bon SAV , SATISFAIT DU TRAITEMENT DES REQUETES

M DIPITA CHRISTIAN
Logistic Safety Manager Road Safety Manager
5/5
La réactivité de JMDS est excellente
Nous restons satisfait dans l’ensemble des prestations relatives a la couverture de notre parc automobile

Hervé Frédéric NDENGUE
Chef Service Adjoint de la Sécurité Générale (CNPS)
5/5
L’APPLICATION EMIXIS est convivial A L’utilisation
BEIG-3 SARL
DIRECTOR GENERAL
5/5
Nevertheless I am delighted with the service
MR. BISSE BENJAMIN
CUSTOMER

Subsribe To Our Newsletter

Stay in touch with us to get latest news and special offers.



Address JMDS TRACK

Douala bp cité



and

YAOUNDE Total Essos

Call Us

+237682230363



Email Us


info@jmdstrack.cm