File: //scripts/updatenow.static
#!/bin/sh
eval 'if [ -x /usr/local/cpanel/3rdparty/bin/perl ]; then exec /usr/local/cpanel/3rdparty/bin/perl -x -- $0 ${1+"$@"}; else exec /usr/bin/perl -x $0 ${1+"$@"}; fi;'
if 0;
#!/usr/bin/perl
BEGIN { # Suppress load of all of these at earliest point.
$INC{'HTTP/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Try/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CleanINC.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/Locale/Maketext/Utils/MarkPhrase.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Exception.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Autodie/More/Lite.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/LoadModule/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/LoadModule.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StatCache.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/Server/Utils.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/Encoder/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Carp.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Debug.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeFileLock.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/OSSys/Bits.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/TimeHiRes.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FHUtils/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Autodie/Fcntl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FHUtils/Blocking.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/FindBin.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeRun/InOut.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/RcsRecord.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeDir/MK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/TouchFile.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/Autodie/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Autodie.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Hash.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Readlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Finally.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/AdminBin/Serializer/FailOK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/LoadConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ConfigFiles/Apache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ConfigFiles.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Bits.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/LoadUserDomains.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/DomainOwnerCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IO.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/Reseller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DB/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/JSON/FailOK.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/LoadCpUserFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Hulk/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Socket/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Socket/UNIX/Micro.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Pack.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/NSCD.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/PwCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/Account.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/Lookup.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/Owner.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/DomainOwner.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/MIME/Base64/Perl.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/URI/Escape.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Encoder/URI.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Errno.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ChildErrorStringifier.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ForkAsync.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeStorable.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ForkSync.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/UTF8/Strict.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Email/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/JSON.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/IteratorBase.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Read/DirectoryNodeIterator.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/Sys/Uname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/LoadFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Hostname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/Case.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/Trim.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Validate/EmailLocalPart.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/WildcardDomain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Validate/EmailCpanel.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/Encoder/Punycode.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Validate/Hostname.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sys/Hostname.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/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ReadMultipleFH.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Kill/Single.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeRun/Object.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/LoginDefs.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/LoadWwwAcctConf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/iContact/Email.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Whostmgr/Transfers/State.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/IP/Collapse.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Match.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Validate/IP/Expand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Convert.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Linux/Netlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Linux/RtNetlink.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CachedCommand/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Loopback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Configured.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/LocalCheck.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Caller.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Context.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/GlobalCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DIp/MainIP.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Ips/Fetch.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Local.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Domain/Local.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/MyCnf/Basic.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Socket/INET.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/Unprivileged.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Version/Compare.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/Version.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AdminBin/Serializer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AdminBin/Utils/Exit.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Wrap.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Wrap/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AdminBin/Cache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AdminBin.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Mysql/Privs.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Destruct.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/Match.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/File.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/SplitBreak.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/UnquoteMeta.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Path.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Copy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Link.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Move.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Equiv.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils/Lines.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FileUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/LoadConfig/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Parser/Vars.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/Paths.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils.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/CPAN/Locale/Maketext/Pseudo.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.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/Locale/Maketext/Utils.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/CPAN/YAML/Syck.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/MkDB.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/Legacy.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ArrayFunc.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/StringFunc/LineIterator.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/PwUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AccessIds/Utils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AccessIds/SetUids.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AccessIds/ReducedPrivileges.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Syscall.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sys/Setsid.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AccessIds.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DataStore.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/3rdparty.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ServerTasks.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/Display.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/DateTime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale/Utils/User.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Locale.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/FlushConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/GreyList/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Services/Enabled.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/RPM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Cpu.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Maxmem.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/Config/CpConfGuard/Default.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/DB/Prefix.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/Validate/Username.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/Domain.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/GetHomeDir.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/Auth/Digest/Realm.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Rollback.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CommandQueue.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Umask.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Autodie/More.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/TouchFileBase.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Email/MTAAuthIsExternal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/PasswdStrength/Check.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MD5/Lite.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/PwFileCache.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/AcctUtils/Lookup/MailUser.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/Logger.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeRun/Timed.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeRun/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/QuotaMtime.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CachedCommand/Save.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CachedCommand.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/OSSys/Env.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sys/GetOS.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sys/OS.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/GenSysInfo.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CloudLinux.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeDir/RM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/TempFile.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Crypt/GPG.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/YAML/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CachedDataStore.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Crypt/GPG/VendorKeys.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/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/UrlTools.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/HttpTimer.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MirrorSearch.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/PipeHandler.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/URL.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/HttpRequest.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/Update/Logger.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/RPM/Versions/Directory.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/RPM/Versions/Hooks.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeChdir.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/IO/Callback/Write.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IOCallbackWriteLine.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeRun/Dynamic.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sync/Digest.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Version/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Version.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/ConfigFiles/RpmVersions.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/CPAN/Template/Tiny.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/RPM/Versions/File.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SafeDir.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sync/Common.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/Sync/v2.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sync/v2_shared_list.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/IP/Parse.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/Httpd.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/Output.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/Terminal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Term/ANSIColor/Solarize.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Output/Formatted/Terminal.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SysPkgs/YUM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/SysPkgs.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Sysup.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/App.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Conf.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Themes/Get.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Themes/List.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/Services.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Update.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DB/Map/Path.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Session/Constants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DB/Map/Reader.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Config/Users.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DB/Map/Collection.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/DbUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Mysql/Error.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Encoder/utf8.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Validate/LineTerminatorFree.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/Grants.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/Quote.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils/MyCnf/Full.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/MysqlUtils.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Update/Blocker/CpanelConfig.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/FastInstall.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Update/Blocker/RPM.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Whostmgr/Transfers/Session/Config.pm'} = '/usr/local/cpanel/scripts/updatenow.static';
$INC{'Cpanel/Update/Blocker.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';
}
{ # --- 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.054';
#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> —
#pod A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If C<agent> — ends in a space character, the default user-agent string is appended.
#pod * C<cookie_jar> —
#pod An instance of L<HTTP::CookieJar> — or equivalent class that supports the C<add> and C<cookie_header> methods
#pod * C<default_headers> —
#pod A hashref of default headers to apply to requests
#pod * C<local_address> —
#pod The local IP address to bind to
#pod * C<keep_alive> —
#pod Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1)
#pod * C<max_redirect> —
#pod Maximum number of redirects allowed (defaults to 5)
#pod * C<max_size> —
#pod Maximum response size (only when not using a data callback). If defined, responses larger than this will return an exception.
#pod * C<http_proxy> —
#pod URL of a proxy server to use for HTTP connections (default is C<$ENV{http_proxy}> — if set)
#pod * C<https_proxy> —
#pod URL of a proxy server to use for HTTPS connections (default is C<$ENV{https_proxy}> — if set)
#pod * C<proxy> —
#pod URL of a generic proxy server for both HTTP and HTTPS connections (default is C<$ENV{all_proxy}> — if set)
#pod * C<no_proxy> —
#pod List of domain suffixes that should not be proxied. Must be a comma-separated string or an array reference. (default is C<$ENV{no_proxy}> —)
#pod * C<timeout> —
#pod Request timeout in seconds (default is 60)
#pod * C<verify_SSL> —
#pod A boolean that indicates whether to validate the SSL certificate of an C<https> —
#pod connection (default is false)
#pod * C<SSL_options> —
#pod A hashref of C<SSL_*> — options to pass through to L<IO::Socket::SSL>
#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 Exceptions from C<max_size>, C<timeout> or other errors will result in a
#pod pseudo-HTTP status code of 599 and a reason of "Internal Exception". The
#pod content field in the response will contain the text of the exception.
#pod
#pod The C<keep_alive> parameter enables a persistent connection, but only to a
#pod single destination scheme, host and port. Also, if any connection-relevant
#pod attributes are modified, or if the process ID or thread ID change, the
#pod 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
sub croak {
require Carp;
Carp::croak(@_);
}
my @attributes;
BEGIN {
@attributes = qw(
cookie_jar default_headers http_proxy https_proxy keep_alive
local_address max_redirect max_size proxy no_proxy timeout
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 new {
my($class, %args) = @_;
my $self = {
max_redirect => 5,
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} 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|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 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 ( -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 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 A specific IP to connect to. Normally the provided hostname will be looked
#pod up, but if a specific IP is required, it can be specified here.
#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
#pod On an exception 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 exception.
#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)};
}
if (my $e = $@) {
# maybe we got a response hash thrown from somewhere deep
if ( ref $e eq 'HASH' && exists $e->{status} ) {
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,
}
};
}
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);
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) );
}
#--------------------------------------------------------------------------#
# private methods
#--------------------------------------------------------------------------#
my %DefaultPort = (
http => 80,
https => 443,
);
sub _agent {
my $class = ref($_[0]) || $_[0];
(my $default_agent = $class) =~ s{::}{-}g;
return $default_agent . "/" . $class->VERSION;
}
sub _request {
my ($self, $method, $url, $args) = @_;
my ($scheme, $host, $port, $path_query, $auth) = $self->_split_url($url);
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;
# 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};
if ( my @redir_args = $self->_maybe_redirect($request, $response, $args) ) {
$handle->close;
return $self->_request(@redir_args, $args);
}
my $known_message_length;
if ($method eq 'HEAD' || $response->{status} =~ /^[23]04/) {
# response has no message body
$known_message_length = 1;
}
else {
my $data_cb = $self->_prepare_data_cb($response, $args);
$known_message_length = $handle->read_body($data_cb, $response);
}
if ( $self->{keep_alive}
&& $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;
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;
}
}
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};
if ( defined $args->{content} ) {
if (ref $args->{content} eq 'CODE') {
$request->{headers}{'content-type'} ||= "application/octet-stream";
$request->{headers}{'transfer-encoding'} = 'chunked'
unless $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});
if (($status eq '303' or ($status =~ /^30[127]/ && $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) = @_;
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}/ge;
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];
# 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 = 'IO::Socket::IP';
if ( $] >= 5.022 ) {
$SOCKET_CLASS = 'IO::Socket::IP';
} else {
$SOCKET_CLASS = $ENV{PERL_HTTP_TINY_IPV4_ONLY} ? 'IO::Socket::INET' :
eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.25) } ? '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]/;
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 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;
}
elsif ( $scheme ne 'http' ) {
die(qq/Unsupported URL scheme '$scheme'\n/);
}
eval qq{ require $SOCKET_CLASS; 1 } or die $@;
$self->{fh} = $SOCKET_CLASS->new(
PeerHost => $peer,
PeerPort => $port,
$self->{local_address} ?
( LocalAddr => $self->{local_address} ) : (),
Proto => 'tcp',
Type => SOCK_STREAM,
Timeout => $self->{timeout},
KeepAlive => !!$self->{keep_alive}
) or die(qq/Could not connect to '$host:$port': $@\n/);
binmode($self->{fh})
or die(qq/Could not binmode() 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 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;
}
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/});
$self->write_body($request) if $request->{cb};
return;
}
my %HeaderCase = (
'content-md5' => 'Content-MD5',
'etag' => 'ETag',
'te' => 'TE',
'www-authenticate' => 'WWW-Authenticate',
'x-xss-protection' => 'X-XSS-Protection',
);
# 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 || @_ == 3 && ref $_[1] eq 'HASH') || die(q/Usage: $handle->write_header_lines(headers[,prefix])/ . "\n");
my($self, $headers, $prefix_data) = @_;
my $buf = (defined $prefix_data ? $prefix_data : '');
while (my ($k, $v) = each %$headers) {
my $field_name = lc $k;
if (exists $HeaderCase{$field_name}) {
$field_name = $HeaderCase{$field_name};
}
else {
$field_name =~ /\A $Token+ \z/xo
or die(q/Invalid HTTP header field name: / . $Printable->($field_name) . "\n");
$field_name =~ s/\b(\w)/\u$1/g;
$HeaderCase{lc $field_name} = $field_name;
}
for (ref $v eq 'ARRAY' ? @$v : $v) {
$_ = '' 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 ($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");
$self->write_header_lines($request->{trailer_cb}->())
if ref $request->{trailer_cb} eq 'CODE';
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);
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 {
@_ == 4 || die(q/Usage: $handle->write_request_header(method, request_uri, headers)/ . "\n");
my ($self, $method, $request_uri, $headers) = @_;
return $self->write_header_lines($headers, "$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 {
# Need IO::Socket::SSL 1.42 for SSL_create_ctx_callback
die(qq/IO::Socket::SSL 1.42 must be installed for https support\n/)
unless eval {require IO::Socket::SSL; IO::Socket::SSL->VERSION(1.42)};
# Need Net::SSLeay 1.49 for MODE_AUTO_RETRY
die(qq/Net::SSLeay 1.49 must be installed for https support\n/)
unless eval {require Net::SSLeay; Net::SSLeay->VERSION(1.49)};
}
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();
return $self->{SSL_options}->{SSL_ca_file}
if $self->{SSL_options}->{SSL_ca_file} and -e $self->{SSL_options}->{SSL_ca_file};
return Mozilla::CA::SSL_ca_file()
if eval { require Mozilla::CA };
# 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;
BEGIN {
$Try::Tiny::AUTHORITY = 'cpan:NUFFIN';
}
$Try::Tiny::VERSION = '0.22';
use 5.006;
# ABSTRACT: minimal try/catch with proper preservation of $@
use strict;
use warnings;
BEGIN {
use Exporter 5.57 'import';
our @EXPORT = our @EXPORT_OK = qw(try catch finally);
use Carp;
$Carp::Internal{+__PACKAGE__}++;
}
# 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
if ( $INC{'Sub/Name.pm'} ) {
my $caller = caller;
"Sub::Name"->can('subname')->( "${caller}::try {...} " => $try );
"Sub::Name"->can('subname')->( "${caller}::catch {...} " => $catch ) if $catch;
"Sub::Name"->can('subname')->( "${caller}::finally {...} " => $_ ) foreach @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 $fail to false
};
# preserve the current error and reset the original value of $@
$error = $@;
$@ = $prev_error;
# set up a scope guard to invoke the finally block at the end
my @guards =
map { Try::Tiny::ScopeGuard->_new($_, $failed ? $error : ()) }
@finally;
# at this point $failed contains a true value if the eval died, even if some
# destructor overwrote $@ as the eval was unwinding.
if ( $failed ) {
# 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;
return (
bless(\$block, 'Try::Tiny::Catch'),
@rest,
);
}
sub finally (&;@) {
my ( $block, @rest ) = @_;
croak 'Useless bare finally()' unless wantarray;
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 Cpanel/CleanINC.pm
package Cpanel::CleanINC;
use strict;
our $test_load_order;
BEGIN {
if ( $test_load_order && !$INC{'Cpanel/BinCheck.pm'} ) {
my @unsafe_loads;
foreach my $loaded_module ( keys %INC ) {
push @unsafe_loads, $loaded_module unless ( $loaded_module =~ m{^(?:strict|lib|warnings|INCCheck|Cpanel/CleanINC)\.pm$} );
}
die "Found unsafe module loads of (@unsafe_loads)... load Cpanel::CleanINC first." if scalar @unsafe_loads;
}
my %seen_inc;
@INC = grep { !/(?:^\.|\.\.|\/\.+)/ && !$seen_inc{$_}++ } @INC;
undef %seen_inc;
}
1;
} # --- END Cpanel/CleanINC.pm
{ # --- BEGIN Cpanel/CPAN/Locale/Maketext/Utils/MarkPhrase.pm
package Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase;
sub import {
no strict 'refs';
*{ caller() . '::translatable' } = \&translatable;
}
sub translatable {
return $_[0];
}
1;
} # --- END Cpanel/CPAN/Locale/Maketext/Utils/MarkPhrase.pm
{ # --- BEGIN Cpanel/Exception.pm
package Cpanel::Exception;
use strict;
# use Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase ();
our $_EXCEPTION_MODULE_PREFIX = __PACKAGE__;
our $IN_EXCEPTION_CREATION = 0;
my $PACKAGE = __PACKAGE__;
my $locale;
our $gl_longmess;
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;
sub _init {
die "Cannot call _init during compile" if $INC{'B/C.pm'};
local $@;
eval 'require Cpanel::ExceptionMessage::Raw;1;' or die "Failed to init Cpanel::ExceptionMessage::Raw: $@";
eval 'require Cpanel::ExceptionMessage::Locale;1;' or die "Failed to init Cpanel::ExceptionMessage::Locale: $@";
eval q{use overload ( '""' => \&__spew, fallback => 1 );1;} or die "Failed to init overload: $@"; ## no critic qw(ProhibitStringyEval)
no warnings 'redefine';
no strict 'refs'; ##no critic qw(ProhibitNoStrict)
my $f = __PACKAGE__ . "::_init";
*$f = sub { 1 };
return 1;
}
sub create {
my ( $exception_type, @args ) = @_;
_init();
if ($IN_EXCEPTION_CREATION) {
_load_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";
}
__PACKAGE__->load_perl_module($perl_class) unless $perl_class->can('new');
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 ( $class, $module ) = @_;
local ( $!, $@ );
if ( !defined $module ) {
die __PACKAGE__->new( 'Cpanel::ExceptionMessage::Raw'->new("load_perl_module requires a module name.") );
}
my $module_path = $module;
$module_path =~ s{::}{/}g;
$module_path .= '.pm' unless $module_path =~ /\.pm$/;
return 1 if exists $INC{$module_path};
my $module_name = $module;
$module_name =~ s{\.pm$}{};
if ( $module_name !~ m/\A[A-Za-z_]\w*(?:(?:'|::)\w+)*\z/ ) {
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 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'} && $INC{'JSON/XS.pm'} ) { # for updatenow.static we must check JSON::XS as well
local $@;
my $ret = eval { 'Cpanel::JSON'->can('Dump')->($exc); };
return $ret if defined $ret && !$@;
}
return $exc;
}
sub set_longmess_global {
my $longmess_sub = shift;
$gl_longmess = $longmess_sub;
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 ( defined $gl_longmess ) {
$self->{'_longmess'} = &{$gl_longmess}($self);
}
else {
if ( !$INC{'Cpanel/Carp.pm'} ) { _load_carp(); }
$self->{'_longmess'} = scalar do {
local $Carp::CarpInternal{$class} = 1;
'Cpanel::Carp'->can('safe_longmess')->();
};
}
_init();
my $message;
if ( UNIVERSAL::isa( $args[0], 'Cpanel::ExceptionMessage' ) ) {
$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 {
@mt_args = $self->_default_maketext_arguments( $args[0] ); ## no extract maketext
}
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!") );
}
$message = 'Cpanel::ExceptionMessage::Locale'->new(@mt_args);
}
$self->{'_message'} = $message;
$self->{'_auxiliaries'} = [];
return $self;
}
sub set_id {
my ( $self, $new_id ) = @_;
$self->{'_id'} = $new_id;
return $self;
}
sub id {
my ($self) = @_;
return $self->{'_id'} ||= do {
join(
q<>,
map { $ID_CHARS[ int rand( scalar @ID_CHARS ) ]; } ( 1 .. $ID_LENGTH ),
),
;
};
}
sub get {
my ( $self, $key ) = @_;
return $self->{'_metadata'}{$key};
}
sub _default_maketext_arguments { ## no extract maketext
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('An unknown error has occurred.');
}
sub _auxiliary_introduction {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The following additional [numerate,_1,error,errors] occurred:');
}
sub longmess {
my ($self) = @_;
return $self->{'_longmess'};
}
sub to_string {
my ($self) = @_;
return $self->_add_id_prefix( $self->to_string_no_id );
}
sub to_string_no_id {
my ($self) = @_;
my $string = $self->to_locale_string_no_id();
my $en_string = $self->to_en_string_no_id();
$string .= "\n$en_string" if ( $en_string ne $string );
return $string;
}
sub _add_id_prefix {
my ( $self, $msg ) = @_;
return sprintf "(XID %s) %s", $self->id(), $msg;
}
sub to_en_string {
my ($self) = @_;
return $self->_add_id_prefix( $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 $self->_add_id_prefix( $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) = @_;
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'} } ) {
if ( $method eq 'to_locale_string' ) {
push @lines, _locale()->makevar( _auxiliary_introduction(), scalar @{ $self->{'_auxiliaries'} } );
}
elsif ( $method eq 'to_en_string' ) {
push @lines, _locale()->makethis_base( _auxiliary_introduction(), scalar @{ $self->{'_auxiliaries'} } );
}
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{'Cpanel/Carp.pm'} ) {
local $@;
eval 'require Cpanel::Carp; 1;' or die $@; # hide from perlcc
}
return;
}
1;
} # --- END Cpanel/Exception.pm
{ # --- BEGIN Cpanel/Autodie/More/Lite.pm
package Cpanel::Autodie::More::Lite;
use strict;
use warnings;
# use Cpanel::Exception ();
sub exists {
my ($path) = @_;
local ( $!, $^E );
return 1 if -e $path;
return 0 if $!{'ENOENT'};
die Cpanel::Exception::create( 'IO::StatError', { error => $!, path => $path } );
}
1;
} # --- END Cpanel/Autodie/More/Lite.pm
{ # --- BEGIN Cpanel/LoadModule/Utils.pm
package Cpanel::LoadModule::Utils;
use strict;
use warnings;
# use Cpanel::Autodie::More::Lite ();
sub module_is_loaded {
my ($module_name) = @_;
return exists $INC{ module_path($module_name) } ? 1 : 0;
}
sub get_INC_dir_for_module {
my ($module_name) = @_;
my $path = module_path($module_name);
local ( $!, $^E );
for (@INC) {
return $_ if Cpanel::Autodie::More::Lite::exists("$_/$path") && -f _;
}
return undef;
}
sub module_path {
my ($module_name) = @_;
$module_name =~ s{::}{/}g;
$module_name .= '.pm' unless $module_name =~ /\.pm$/;
return $module_name;
}
1;
} # --- END Cpanel/LoadModule/Utils.pm
{ # --- BEGIN Cpanel/LoadModule.pm
package Cpanel::LoadModule;
use strict;
# use Cpanel::Autodie::More::Lite ();
# 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'} && $^X !~ '/usr/local/cpanel';
if ( $INC{'Cpanel/Logger.pm'} ) {
$logger ||= 'Cpanel::Logger'->new();
$logger->warn($msg);
}
warn $msg;
}
sub _reset_has_perl_dir {
$has_perl_dir = 0;
return;
}
sub load_perl_module {
my ( $mod, @LIST ) = @_;
local ( $!, $@ );
if ( !Cpanel::LoadModule::Utils::module_is_loaded($mod) ) {
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) {
load_perl_module('String::PerlQuote');
$args_str = join ',', map {
die "Only scalar arguments allowed in LIST! (@LIST)" if ref;
String::PerlQuote::single_quote($_);
} @LIST;
}
else {
$args_str = q<>;
}
eval "use $mod ($args_str);";
}
if ($@) {
die Cpanel::Exception::create( 'ModuleLoadError', { module => $mod, error => $@ } );
}
return 1;
}
sub get_module_names_from_directory {
my ($dir) = @_;
die "List context only!" if !wantarray;
my @names;
if ( Cpanel::Autodie::More::Lite::exists($dir) && -d _ ) {
local $!;
opendir( my $dh, $dir ) or die Cpanel::Exception::create( 'IO::DirectoryOpenError', { path => $dir, error => $! } );
@names = map { m{\A(.*)\.pm\z} ? $1 : () } readdir $dh;
die Cpanel::Exception::create( 'IO::DirectoryReadError', { path => $dir, error => $! } ) if $!;
closedir $dh or warn "Failed to close directory $dir: $!";
}
return @names;
}
*module_is_loaded = \&Cpanel::LoadModule::Utils::module_is_loaded;
sub is_valid_module_name {
my $module = shift;
return $module && $module =~ m/\A[A-Za-z_]\w*(?:(?:'|::)\w+)*\z/ ? 1 : 0;
}
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"); ]; #issafe #nomunge
if ($@) {
_logger_warn("Error loading module $module - $@");
return;
}
return 1;
}
1;
} # --- END Cpanel/LoadModule.pm
{ # --- BEGIN Cpanel/StatCache.pm
package Cpanel::StatCache;
our $VERSION = 0.3;
my %STATCACHE;
sub StatCache_init { }
sub cachedmtime {
return (
exists $STATCACHE{ $_[0] } ?
$STATCACHE{ $_[0] }->[0] :
($STATCACHE{ $_[0] } =
( -r $_[0] ?
[ ( stat(_) )[ 9, 7, 10 ] ] :
[ 0, 0, 0 ] )
)->[0]
);
}
sub cachedmtime_size {
return (
exists $STATCACHE{ $_[0] } ?
@{ $STATCACHE{ $_[0] } }[ 0, 1 ] :
@{ ( $STATCACHE{ $_[0] } =
( -r $_[0] ?
[ ( stat(_) )[ 9, 7, 10 ] ] :
[ 0, 0, 0 ] )
) }[ 0, 1 ]
);
}
sub cachedmtime_ctime {
return (
exists $STATCACHE{ $_[0] } ?
@{ $STATCACHE{ $_[0] } }[ 0, 2 ] :
@{ ( $STATCACHE{ $_[0] } =
( -r $_[0] ?
[ ( stat(_) )[ 9, 7, 10 ] ] :
[ 0, 0, 0 ] ) )
}[ 0, 2 ]
);
}
sub clearcache {
%STATCACHE = ();
return 1;
}
sub api2 {
my $func = shift;
my $API = {
'clearcache' => {
'func' => 'clearcache',
},
};
return $API->{$func};
}
1;
} # --- END Cpanel/StatCache.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;
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 $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_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 Cpanel::Fcntl::Constants ();
my %CONSTANTS;
sub or_flags {
my (@flags) = @_;
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 $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;
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/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/SafeRun/Simple.pm
package Cpanel::SafeRun::Simple;
use strict;
sub saferun_r {
return _saferun_r( \@_ );
}
sub _saferun_r {
my ( $cmdline, $error_flag ) = @_;
my $output;
if ( substr( $cmdline->[0], 0, 1 ) eq '/' ) {
my ($check) = !-e $cmdline->[0] && $cmdline->[0] =~ /[\s<>&\|\;]/ ? split( /[\s<>&\|\;]/, $cmdline->[0], 2 ) : $cmdline->[0];
if ( !-x $check ) {
$? = -1;
return \$output;
}
}
local ($/);
my ( $pid, $prog_fh );
if ( $pid = open( $prog_fh, '-|' ) ) {
}
elsif ( defined $pid ) {
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
( $ENV{'PATH'} ) = ( $ENV{'PATH'} || '' ) =~ m/(.*)/; # untaint, case 6622
if ( $error_flag && $error_flag == 1 ) { no strict 'subs'; open( STDERR, '>&STDOUT' ); }
elsif ( $error_flag && $error_flag == 2 ) { no strict 'subs'; open( STDERR, '>', '/dev/null' ); }
elsif ( $error_flag && $error_flag == 3 ) { no strict 'subs'; open( STDERR, '>&STDOUT' ); open( STDOUT, '>', '/dev/null' ); }
{ # Block statement unlikely to be reached warning.
exec(@$cmdline);
}
exit( $! || 127 );
}
else {
$? = -1;
return;
}
if ( !$prog_fh || !$pid ) {
$? = -1;
return \$output;
}
$output = readline($prog_fh);
close($prog_fh);
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( \@_, 0 );
}
sub saferunallerrors {
return _call_saferun( \@_, 1 );
}
sub saferunnoerror {
return _call_saferun( \@_, 2 );
}
sub saferunonlyerrors {
return _call_saferun( \@_, 3 );
}
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/Encoder/Tiny.pm
package Cpanel::Encoder::Tiny;
use strict;
my %XML_ENCODE_MAP = ( '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''' );
my %JSON_ENCODE_MAP = ( "\n" => '\n', "\r" => '\r', "\t" => '\t', "\f" => '\f', "\b" => '\b', "\"" => '\"', "\\" => '\\\\', "\'" => '\\\'' );
my %HTML_ENCODE_MAP = ( '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''' );
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{<}{<}xmsg;
$string =~ s{>}{>}xmsg;
return $string;
}
sub angle_bracket_decode {
my ($string) = @_;
$string =~ s{ < }{<}xmsg;
$string =~ s{ > }{>}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 undef if !defined $_[0];
my $data = join( '', @_ );
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 decode_utf8_html_entities {
my $str = shift;
my $c;
$str =~ s/&\#(\d{4})\;/chr($1);/eg;
return $str;
}
sub remove_html_from_string {
my ($string) = @_;
$string =~ s{ < \s* [!] \s* [-] \s* [-] \s* .*? [-] \s* [-] \s* > }{}xms;
$string =~ s{ < \W* [^>]* > (?: [^<]* >)* }{}xmsg;
$string =~ s{ [&][#]? \w+ [;]? }{}xmsg;
return $string;
}
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/CPAN/URI/Escape.pm') && Cpanel::CPAN::URI::Escape::fast_uri_escape($1)
}ge;
return $str;
}
sub json_encode_str {
my ($str) = @_;
return 'null' if !defined $str;
$str =~ s/([\x22\x5c\n\r\t\f\b])/$JSON_ENCODE_MAP{$1}/g;
$str =~ s/\//\\\//g;
$str =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
return '"' . $str . '"';
}
1;
} # --- END Cpanel/Encoder/Tiny.pm
{ # --- BEGIN Cpanel/Carp.pm
package Cpanel::Carp;
use strict;
our ( $SHOW_TRACE, $OUTPUT_FORMAT ) = ( 1, 'text' );
my $error_count = 0;
use Carp ();
$Carp::Internal{'Cpanel::Carp'} = 1;
sub import { enable(); }
sub enable {
my ($callback) = @_;
$SIG{'__WARN__'} = sub {
my @caller = caller(1);
return if defined $caller[3] && $caller[3] =~ m/eval/; # 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;
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(@_);
}
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'} );
_run_callback_without_die_handler($callback) if $callback;
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 {
return if $^S;
delete $SIG{'__DIE__'};
_run_callback_without_die_handler($callback) if $callback;
goto \&spew_on_die;
};
}
sub spew_on_die {
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");
}
return;
}
my @SAFE_LONGMESS_KEY_REGEXP_ITEMS = (
'(?<![a-zA-Z0-9_])pw(?![a-zA-Z0-9_])',
qw(
hash
pass
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 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>
</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;">$safe_error_message</textarea>
</div>
</div>
</div>
</div>
</div>
];
}
sub safe_longmess {
my (@args) = @_;
my @safe_longmess = split( m{\n}, Carp::longmess(@args) );
foreach my $line (@safe_longmess) {
$line = sanitize_line($line);
}
return join( "\n", @safe_longmess ) . "\n";
}
sub sanitize_line {
my $line = shift;
my $do_substitution = 0;
my $key_regexp_items = join '|', @SAFE_LONGMESS_KEY_REGEXP_ITEMS;
my $key_regexp = qr<
'
.*?
(?:
$key_regexp_items
)
.*?
'
\s*
,
>x;
my $key_regexp_double = $key_regexp;
$key_regexp_double =~ tr{'}{"}; # "' fix for poor editors
my $function_regexp_items = join '|', @SAFE_LONGMESS_FUNCTION_REGEXP_ITEMS;
my $function_regexp = qr<
::
.*?
(?:
$function_regexp_items
)
.*?
$
>x;
if ( $line =~ $key_regexp || $line =~ $key_regexp_double ) {
$do_substitution = 1;
}
else {
my ($function) = $line =~ m{^[ \t]*([^\(]+)\(};
if ( defined $function && ( $function =~ $function_regexp ) ) {
$do_substitution = 1;
}
}
if ($do_substitution) {
local $@;
eval { local $SIG{__DIE__}; local $SIG{__WARN__}; require Cpanel::Regex; };
for my $regexp (qw/singlequotedstring doublequotedstring/) {
$line =~ s/$Cpanel::Regex::regex{$regexp}/__CPANEL_HIDDEN__/g;
}
}
return $line;
}
1;
} # --- END Cpanel/Carp.pm
{ # --- BEGIN Cpanel/Debug.pm
package Cpanel::Debug;
use strict;
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 logger {
$logger = shift if (@_); # Set method for $logger if something is passed in.
return $logger if $logger;
eval 'require Cpanel::Logger' unless $INC{'Cpanel/Logger.pm'};
$logger = Cpanel::Logger->new();
return $logger;
}
sub log_warn {
my $msg = shift;
local $!; #prevent logger from overwriting $!
return logger()->warn($msg);
}
sub log_invalid {
my $msg = shift;
local $!; #prevent logger from overwriting $!
return logger()->invalid($msg);
}
sub log_die {
my $msg = shift;
local $!; #prevent logger from overwriting $!
return logger()->die($msg);
}
sub log_info {
my $msg = shift;
local $!; #prevent logger from overwriting $!
return logger()->info($msg);
}
sub log_debug {
my $msg = shift;
local $!; #prevent logger from overwriting $!
return logger()->debug($msg);
}
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/SafeFileLock.pm
package Cpanel::SafeFileLock;
use strict;
my $DEBUG;
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)';
}
eval 'require Cpanel::Carp' if $DEBUG;
if ($fh) {
if ( !syswrite( $fh, $$ . "\n" . $0 . "\n" . ( $DEBUG ? Cpanel::Carp::safe_longmess() . "\n" : q<> ) ) ) {
warn "Failed to write lock file: $path_to_lockfile: $!" unless $!{'EDQUOT'};
close($fh);
unlink $path_to_lockfile;
return;
}
}
my $self = [ $path_to_lockfile, $fh, $path_to_file_being_locked ];
bless $self, $class;
my $the_stat_ar = $self->stat_ar();
push @$self, @{$the_stat_ar}[ 1, 9 ];
return $self;
}
sub get_path {
my ($self) = @_;
return $self->[0];
}
sub get_path_to_file_being_locked {
my ($self) = @_;
if ( !length $self->[2] ) {
die "get_path_to_file_being_locked requires the object to be instantiated with the path_to_file_being_locked";
}
return $self->[2];
}
sub get_filehandle {
my ($self) = @_;
return $self->[1];
}
sub get_inode {
my ($self) = @_;
return $self->[3];
}
sub get_mtime {
my ($self) = @_;
return $self->[4];
}
sub stat_ar {
my ($self) = @_;
return [ stat( $self->[1] ) ] if $self->[1] && int( fileno( $self->[1] ) || 0 ) > 0;
return [ stat( $self->[0] ) ];
}
sub lstat_ar {
my ($self) = @_;
return [ $self->[1] && int( fileno( $self->[1] ) || 0 ) > 0 ? stat( $self->[1] ) : lstat( $self->[0] ) ];
}
sub close {
my ($self) = @_;
if ( ref $self->[1] ) {
return close $self->[1];
}
return;
}
1;
} # --- END Cpanel/SafeFileLock.pm
{ # --- BEGIN Cpanel/OSSys/Bits.pm
package Cpanel::OSSys::Bits;
use strict;
use warnings;
our $MAX_32_BIT_SIGNED;
our $MAX_32_BIT_UNSIGNED;
our $MAX_64_BIT_SIGNED;
our $MAX_64_BIT_UNSIGNED;
our $MAX_NATIVE_SIGNED;
our $MAX_NATIVE_UNSIGNED;
sub getbits {
return length( pack( 'l!', 1000 ) ) * 8;
}
BEGIN {
$MAX_32_BIT_UNSIGNED = ( 1 << 32 ) - 1;
$MAX_32_BIT_SIGNED = ( 1 << 31 ) - 1;
$MAX_64_BIT_UNSIGNED = ~0; #true on both 32- and 64-bit systems
$MAX_64_BIT_SIGNED = -1 >> 1; #true on both 32- and 64-bit systems
if ( getbits() == 32 ) {
$MAX_NATIVE_SIGNED = $MAX_32_BIT_SIGNED;
$MAX_NATIVE_UNSIGNED = $MAX_32_BIT_UNSIGNED;
}
else {
$MAX_NATIVE_SIGNED = $MAX_64_BIT_SIGNED;
$MAX_NATIVE_UNSIGNED = $MAX_64_BIT_UNSIGNED;
}
}
1;
} # --- END Cpanel/OSSys/Bits.pm
{ # --- BEGIN Cpanel/TimeHiRes.pm
package Cpanel::TimeHiRes;
use strict;
# use Cpanel::OSSys::Bits ();
my $SYS_gettimeofday;
my $EINTR = 4;
sub _set_constants {
my $sys_bits = Cpanel::OSSys::Bits::getbits();
if ( $sys_bits == 32 ) {
$SYS_gettimeofday = 78;
}
elsif ( $sys_bits == 64 ) {
$SYS_gettimeofday = 96;
}
return;
}
sub gettimeofday {
_set_constants() if !$SYS_gettimeofday;
my $timeval;
local $!;
my $retval = syscall( $SYS_gettimeofday, $timeval = pack( 'L!L!', () ), undef );
if ( $retval == -1 ) {
eval 'require Cpanel::Exception';
die 'Cpanel::Exception'->can('create')->( 'SystemCall', 'The system failed to retrieve the time because of an error: [_1]', [$!] );
}
return unpack( 'L!L!', $timeval );
}
sub time {
my ( $secs, $usecs ) = gettimeofday();
return $secs + ( $usecs / 1000000 );
}
sub sleep {
my ($secs) = @_;
local $!;
my $retval = select( undef, undef, undef, $secs );
if ( $retval == -1 && $! != $EINTR ) {
eval '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;
}
1;
} # --- END Cpanel/TimeHiRes.pm
{ # --- BEGIN Cpanel/FHUtils/Tiny.pm
package Cpanel::FHUtils::Tiny;
use strict;
sub is_a { ## no critic qw(RequireArgUnpacking)
return 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, fileno($fh), 1 ) = 1;
}
return $mask;
}
1;
} # --- END Cpanel/FHUtils/Tiny.pm
{ # --- BEGIN Cpanel/Autodie/Fcntl.pm
package Cpanel::Autodie::Fcntl;
use strict;
sub fcntl {
my ( $fh, $func, $scalar ) = @_;
local ( $!, $^E, $@ );
return fcntl( $fh, $func, $scalar ) || do {
eval 'require Cpanel::Exception;';
die 'Cpanel::Exception'->can('create')->( 'IO::FcntlError', { error => $! } );
};
}
1;
} # --- END Cpanel/Autodie/Fcntl.pm
{ # --- BEGIN Cpanel/FHUtils/Blocking.pm
package Cpanel::FHUtils::Blocking;
use strict;
# use Cpanel::Fcntl::Constants ();
# use Cpanel::Autodie::Fcntl ();
sub set_non_blocking {
my ($fh) = @_;
Cpanel::Autodie::Fcntl::fcntl( $fh, $Cpanel::Fcntl::Constants::F_SETFL, _get_fl_flags($fh) | $Cpanel::Fcntl::Constants::O_NONBLOCK );
return 1;
}
sub set_blocking {
my ($fh) = @_;
Cpanel::Autodie::Fcntl::fcntl( $fh, $Cpanel::Fcntl::Constants::F_SETFL, _get_fl_flags($fh) & ~$Cpanel::Fcntl::Constants::O_NONBLOCK );
return 1;
}
sub is_set_to_block {
my ($fh) = @_;
return !( _get_fl_flags($fh) & $Cpanel::Fcntl::Constants::O_NONBLOCK ) ? 1 : 0;
}
sub _get_fl_flags {
my ($fh) = @_;
return _get_flags_of_type( $fh, $Cpanel::Fcntl::Constants::F_GETFL );
}
sub _get_flags_of_type {
my ( $fh, $type ) = @_;
my $flags = Cpanel::Autodie::Fcntl::fcntl( $fh, $type, 0 );
return $flags;
}
1;
} # --- END Cpanel/FHUtils/Blocking.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;
my $last_entropy_pool_owner = $$;
my %TR_CODE_CACHE;
my $DEFAULT_LENGTH = 10;
my @DEFAULT_CHARACTERS = (
0 .. 9,
'A' .. 'Z',
'a' .. 'z',
'_',
);
my $DEFAULT_PRELOAD_16TH = 100;
my $MAX_READ_ATTEMPTS = 50;
sub getranddata {
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 !~ m{ \A \d+ \z }xms ) {
eval 'require Cpanel::Exception;';
die 'Cpanel::Exception'->can('create')->( 'InvalidParameter', '“[_1]” is not a valid number of bytes.', $bytes_of_random_data_wanted );
}
}
else {
$bytes_of_random_data_wanted = $DEFAULT_LENGTH;
}
my @chars;
if ( !$my_chars_ar ) {
$my_chars_ar = \@DEFAULT_CHARACTERS;
}
if ( @$my_chars_ar < 1 || @$my_chars_ar > 256 ) {
eval 'require Cpanel::Exception;';
die 'Cpanel::Exception'->can('create')->( 'InvalidParameter', 'The number of desired characters must be at least 1 and at most 256.' );
}
my $number_of_acceptable_characters = scalar @{$my_chars_ar};
my $want_chars = join( '', @{$my_chars_ar} );
$entropy_pool{$want_chars} ||= '';
my $cur_entropy_pool_sr = \$entropy_pool{$want_chars};
my $first_bad_value = 256 - ( 256 % @$my_chars_ar );
my $first_bad_value_hex = sprintf( "%02x", $first_bad_value );
my $code_ref_to_remove_chars_above_upper_limit = $TR_CODE_CACHE{$first_bad_value_hex} ||= ( $first_bad_value == 256 ? sub { } : eval 'sub { ${$_[0]} =~ tr/\x' . $first_bad_value_hex . '-\xff//d; }' );
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;
if ( !$rand_fh ) {
if ( open $rand_fh, '<', $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;
}
$entropy_pool_remaining = $bytes_of_data_to_preload_into_entropy_pool - length($$cur_entropy_pool_sr);
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 );
$$cur_entropy_pool_sr .= join( '', map { $my_chars_ar->[ $_ % $number_of_acceptable_characters ] } ( unpack 'C*', $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(
$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 ) = @_;
srand( time ^ $$ ^ unpack '%L*', `ps axww | gzip` );
my $num_chars = @$my_chars_ar;
my $random_data_collected = q<>;
for ( 1 .. $bytes_of_random_data_wanted ) {
$random_data_collected .= $my_chars_ar->[ rand $num_chars ];
}
return $random_data_collected;
}
sub clear_pool {
%entropy_pool = ();
}
1;
} # --- END Cpanel/Rand/Get.pm
{ # --- BEGIN Cpanel/Rand.pm
package Cpanel::Rand;
use strict;
no strict 'subs';
# use Cpanel::Rand::Get ();
# use Cpanel::Exception ();
# use Cpanel::Fcntl ();
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(gettmpfile getranddata);
our $VERSION = '2.1';
my $logger;
my $MAX_TMPFILE_CREATE_ATTEMPTS = 50;
my $entropy_owner = $$;
my @entropy;
our ( $DO_OPEN, $SKIP_OPEN, $TYPE_FILE, $TYPE_DIR ) = ( 0, 1, 0, 1 );
{
no warnings 'once';
*getranddata = *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 = @_;
return { 'random' => Cpanel::Rand::Get::getranddata( $CFG{'length'} || 16 ) };
}
sub api2 {
my $func = shift;
my (%API);
$API{'getranddata'} = {};
return $API{$func};
}
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 ( $suffix !~ m/^[.]/ ) {
$suffix = '.' . $suffix;
}
my $last_error;
my $fh;
my $tmpfile = $templatefile . $suffix . '.' . Cpanel::Rand::Get::getranddata( 16, undef, 10 );
($tmpfile) = $tmpfile =~ /(.*)/; #untaint
local $!;
my $attempts = 0;
while (
++$attempts < $MAX_TMPFILE_CREATE_ATTEMPTS
&& (
-e $tmpfile
|| (
$open == $DO_OPEN
? (
$type == $TYPE_DIR
? !mkdir( $tmpfile, 0700 )
: !sysopen( $fh, $tmpfile, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_EXCL O_CREAT )), 0600 )
)
: 0
)
)
) {
$last_error = $!;
$tmpfile = $templatefile . $suffix . '.' . Cpanel::Rand::Get::getranddata( 16, undef, 10 );
($tmpfile) = $tmpfile =~ /(.*)/; #untaint
}
if ( $attempts == $MAX_TMPFILE_CREATE_ATTEMPTS ) {
die Cpanel::Exception::create( 'TempFileCreateError', { path => $tmpfile, error => $last_error } );
}
chmod( 0700, $tmpfile ) if $type == $TYPE_DIR; #in case of odd umask
return ( $tmpfile, $fh ) if wantarray && $type == $TYPE_FILE;
return $tmpfile; # file will close when $fh leaves context
}
1;
} # --- END Cpanel/Rand.pm
{ # --- BEGIN Cpanel/FindBin.pm
package Cpanel::FindBin;
use strict;
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 {
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) {
if ( -x $path . '/' . $binname ) {
$bin_cache{$binname} = $path . '/' . $binname unless $nocache;
return $path . '/' . $binname;
}
}
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/SafeRun/InOut.pm
package Cpanel::SafeRun::InOut;
use strict;
use Symbol ();
sub inout {
my $wtr = $_[0] ||= Symbol::gensym();
my $rdr = $_[1] ||= Symbol::gensym();
my $child_read;
pipe( $child_read, $wtr ) or warn "Failed to pipe(): $!";
select( ( select($wtr), $| = 1 )[0] ); #aka $wtr->autoflush(1);
select( ( select($child_read), $| = 1 )[0] ); #aka $child_read->autoflush(1);
if ( my $pid = open( $rdr, '-|' ) ) {
close $child_read or warn $!;
return $pid;
}
elsif ( defined $pid ) {
close $wtr or warn $!;
open( STDIN, '<&=' . fileno($child_read) );
if ( ref $_[2] eq 'CODE' ) {
$_[2]->();
_exec( @_[ 3 .. $#_ ] );
}
else {
_exec( @_[ 2 .. $#_ ] );
}
exit( $! || 127 );
}
else {
return;
}
}
sub inout_with_default_signal_handlers {
local @SIG{ keys %SIG } = ('DEFAULT') x keys %SIG;
return inout(@_);
}
sub _exec {
exec(@_);
}
1;
} # --- END Cpanel/SafeRun/InOut.pm
{ # --- BEGIN Cpanel/RcsRecord.pm
package Cpanel::RcsRecord;
use strict;
# use Cpanel::SafeFile ();
# use Cpanel::FindBin ();
# use Cpanel::SafeRun::InOut ();
our $SKIP_IF_MTIME_MATCHES = 2;
our $VERSION = '4.4';
sub rcsrecord {
my ( $file, $description, $skip_lock, $flags ) = @_;
$description ||= '';
$flags ||= 0;
my ( $uid, $gid, $size, $mtime ) = ( stat($file) )[ 4, 5, 7, 9 ];
if ( !$mtime || $file =~ tr/\0// ) { return 0; }
my $maxsize = ( $size * 25 );
if ( $maxsize < 32768 ) { $maxsize = 32768; }
my @DIR = split( /\//, $file );
my $truefile = pop(@DIR);
my $dir = '';
if ( $#DIR > -1 ) {
$dir = join( '/', @DIR );
}
if ( !$dir ) {
$dir = '.';
}
if ( $uid != $> ) {
my $dir_uid = ( stat($dir) )[4];
if ( $dir_uid != $> ) {
warn "rcsrecord skipped on $file because we do not own it or the directory it is in";
return 0;
}
}
my $rcslock;
if ( !$skip_lock ) {
$rcslock = Cpanel::SafeFile::safelock($file);
if ( !$rcslock ) {
return 0;
}
}
if ( -e "$dir/,$truefile," ) {
my $tmp_mtime = ( stat("$dir/,$truefile,") )[9];
if ( ( time() - $tmp_mtime ) > 360 ) { #remove temp files after 5 minutes
unlink("$dir/,$truefile,");
}
}
my $rcs_bin;
if ( !-e "$dir/$truefile,v" ) {
$rcs_bin = Cpanel::FindBin::findbin('rcs');
if ($rcs_bin) {
if ( my $rcs_pid = fork() ) {
waitpid( $rcs_pid, 0 );
}
elsif ( defined $rcs_pid ) {
open( STDOUT, '>&STDERR' );
open( STDIN, '<', '/dev/null' );
umask(0077);
exec( $rcs_bin, '-q', '-i', $file ) or do {
exit 1;
};
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
elsif ( $flags && ( $flags & $SKIP_IF_MTIME_MATCHES ) ) {
if ( $mtime && $mtime <= ( stat(_) )[9] ) {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
my $ci_bin = Cpanel::FindBin::findbin('ci');
if ($ci_bin) {
my $safe_msg = "Modified by $0 $description";
$safe_msg =~ s/\"//g;
if ( my $ci_pid = fork() ) {
waitpid( $ci_pid, 0 );
}
elsif ( defined $ci_pid ) {
open( STDIN, '<', '/dev/null' );
open( STDOUT, '>', '/dev/null' );
open( STDERR, '>', '/dev/null' );
umask(0077);
chmod( ( stat($file) )[2] & 00777, $file . ',v' );
exec( $ci_bin, '-l', qq{-m"$safe_msg"}, $file ) or do {
exit 1;
}
}
else { #fork failed
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
if ( ( stat("$dir/$truefile,v") )[7] > $maxsize ) {
my $rlog_bin = Cpanel::FindBin::findbin('rlog');
my @REVS;
if ($rlog_bin) {
my $head;
my $rlog_pid = Cpanel::SafeRun::InOut::inout( my $wtr_rlog, my $rdr_rlog, $rlog_bin, $file );
if ($rlog_pid) {
close($wtr_rlog);
while ( readline($rdr_rlog) ) {
if (/revision[\s\t]+([\d\.]+)/) {
push @REVS, $1;
}
}
close($rdr_rlog); # no waitpid needed because inout will use an open call which will waitpid automaticlly when this is closed
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
if (@REVS) {
my $rev = $REVS[ int( $#REVS / 2 ) ]; #remove 50% of revisions
if ( !$rcs_bin ) { $rcs_bin = Cpanel::FindBin::findbin('rcs'); }
if ( !$rcs_bin ) {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
if ( my $rcs_pid = fork() ) {
waitpid( $rcs_pid, 0 );
}
elsif ( defined $rcs_pid ) {
open( STDOUT, '>&STDERR' );
open( STDIN, '<', '/dev/null' );
umask(0077);
chmod( ( stat($file) )[2] & 00777, $file . ',v' );
exec( $rcs_bin, '-q', '-o:' . $rev, $file ) or do {
exit 1;
};
}
else {
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
return 0;
}
}
}
if ($rcslock) { Cpanel::SafeFile::safeunlock($rcslock); }
chown $uid, $gid, $file;
return 1;
}
1;
} # --- END Cpanel/RcsRecord.pm
{ # --- BEGIN Cpanel/SafeFile.pm
package Cpanel::SafeFile;
use strict;
use Symbol ();
use Errno ();
# use Cpanel::Debug ();
# use Cpanel::Fcntl ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::SafeFileLock ();
# use Cpanel::TimeHiRes ();
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::Rand ();
# use Cpanel::LoadModule ();
$Cpanel::SafeFile::VERSION = '3.2';
my $MAGIC_FCNTL_VALUE;
my $verbose; # initialized in safelock
our $OPEN_LOCKS = 0;
our $MAX_LOCK_CREATE_ATTEMPTS = 90;
our $MAX_WAIT_FOR_WRITE_TO_LOCKFILE = 15;
our $MAX_FLOCK_WAIT = 60;
our $LOCK_WAIT_TIME; #allow lock wait time to be overwritten
our $DOUBLE_LOCK_DETECTED = 4096;
sub safeopen {
$_[0] = Symbol::gensym() if !ref $_[0]; # If we don't pass a filehandle then we generate a Symbol
my $fh = shift;
my ( $mode, $file ) = _get_open_args(@_);
my $open_method_coderef = sub { return open $_[0], $_[1], $_[2]; };
return _safe_open( $fh, $mode, $file, $open_method_coderef, 'safeopen' );
}
sub safereopen { ##no critic qw(RequireArgUnpacking)
my $fh = shift or return; # If the file handle isn't open, then it's not a re-open
my ( $mode, $file ) = _get_open_args(@_);
my $open_method_coderef = sub { return open $_[0], $_[1], $_[2]; };
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 ] );
if ( !Cpanel::FHUtils::Tiny::is_a( $_[0] ) ) {
$_[0] = Symbol::gensym();
}
my $fh = $_[0];
my ( $sysopen_perms, $original_umask );
$open_mode = _sanitize_open_mode($open_mode);
my $open_method_coderef = sub { return sysopen $_[0], $_[2], $_[1], $sysopen_perms; };
if ( defined $custom_perms ) {
$custom_perms &= 0777;
$original_umask = umask;
umask( $custom_perms ^ 07777 );
$sysopen_perms = $custom_perms;
}
else {
$sysopen_perms = 0666;
}
my $lock_ref = _safe_open( $fh, $open_mode, $file, $open_method_coderef, 'safesysopen' );
if ( defined $custom_perms ) {
umask($original_umask);
}
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 ) {
$success = close $fh;
}
my $safe_unlock = safeunlock($lockref);
$OPEN_LOCKS-- if ( $safe_unlock && $success );
return ( $safe_unlock && $success );
}
sub locked_atomic_replace_contents {
my ( $fh, $safelock, $coderef ) = @_;
my $lock_ex_nb = Cpanel::Fcntl::or_flags(qw( LOCK_EX LOCK_NB ));
if ( !flock $fh, $lock_ex_nb ) {
Cpanel::LoadModule::load_perl_module('Cpanel::Exception');
die Cpanel::Exception::create_raw( 'IOError', "fh was not locked" );
}
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 ) = Cpanel::Rand::get_tmp_file_by_name($locked_path);
if ( !flock $temp_fh, Cpanel::Fcntl::or_flags('LOCK_EX') ) {
Cpanel::LoadModule::load_perl_module('Cpanel::Exception');
die Cpanel::Exception::create_raw( 'IOError', "Failed to lock temporary file" );
}
select( ( select($temp_fh), $| = 1 )[0] ); # autoflush
if ( $coderef->($temp_fh) ) {
chmod( ( stat($fh) )[2] & 07777, $temp_fh );
rename( $temp_file, $locked_path );
return $temp_fh;
}
die "locked_atomic_replace_contents coderef returns false";
}
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;
Cpanel::LoadModule::load_perl_module('Cpanel::Exception');
die Cpanel::Exception::create( 'IO::WriteError', { length => $length, error => $! } );
}
return 1;
}
);
}
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// ) {
Cpanel::Debug::log_warn('safelock: Invalid arguments');
return;
}
$verbose ||= ( -e '/var/cpanel/safefile_verbose' ? 1 : -1 );
local $0 = ( $verbose == 1 ) ? "$0 - waiting for lock on $file" : "$0 - waiting for lock";
my $lockfile = _calculate_lockfile($file);
my ( $lock_status, $lock_fh, $attempts );
while ( ++$attempts < $MAX_LOCK_CREATE_ATTEMPTS ) {
( $lock_status, $lock_fh ) = _lock_wait($file);
last if $lock_status;
if ( $lock_fh && $lock_fh == $DOUBLE_LOCK_DETECTED ) {
return 0;
}
elsif ( $lock_fh && ( $lock_fh == &Errno::EPERM || $lock_fh == &Errno::EDQUOT ) ) {
return 1;
}
elsif ( !-w _getdir($lockfile) ) {
return 1;
}
}
if ($lock_fh) {
return Cpanel::SafeFileLock->new( $lockfile, $lock_fh, $file );
}
Cpanel::Debug::log_warn( 'safelock: waited for lock ' . $attempts . ' times' );
return;
}
sub safeunlock {
my $lockref = shift;
if ( !$lockref ) {
Cpanel::Debug::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 ( my $fh = $lockref->get_filehandle ) {
return 1 unless defined fileno($fh);
}
my ( $filesys_lock_ino, $filesys_lock_mtime ) = @{ $lockref->lstat_ar() }[ 1, 9 ];
if ( !$filesys_lock_mtime ) {
Cpanel::Debug::log_warn( 'Lock on ' . $lockref->get_path() . ' lost!' );
$lockref->close();
return;
}
my $lock_path = $lockref->get_path();
my $lock_inode = $lockref->get_inode();
my $lock_mtime = $lockref->get_mtime();
$lockref->close();
if ( $lock_inode && ( $lock_inode == $filesys_lock_ino ) && $lock_path && ( $lock_mtime == $filesys_lock_mtime ) ) {
unlink $lock_path or do {
Cpanel::Debug::log_warn("Could not unlink lock file “$lock_path” as ($>/$)): $!\n");
return;
};
return 1;
}
else {
my ( $lock_pid, $lock_name, $lock_obj ) = _fetch_lockfile_info($lock_path);
if ( !$lock_pid ) {
unlink $lock_path or Cpanel::Debug::log_warn("Could not unlink lock file “$lock_path” as ($>/$)): $!\n");
Cpanel::Debug::log_warn( "Invalid zero-length lock file '" . $lock_path . "' detected." );
return;
}
else {
Cpanel::Debug::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]=[$lock_inode] [ACTUAL_INODE]=[$filesys_lock_ino] [LOCK_MTIME]=[$lock_mtime] [ACTUAL_MTIME]=[$filesys_lock_mtime]");
return;
}
}
}
sub _safe_open {
my ( $fh, $open_mode, $file, $open_method_coderef, $open_method ) = @_;
if ( !defined $open_mode || !$open_method_coderef || !$file || $file =~ tr/\0// ) {
Cpanel::Debug::log_warn('_safe_open: Invalid arguments');
return;
}
elsif ( !defined $fh ) {
Cpanel::Debug::log_warn("Undefined file handle provided for $open_method of '$file'");
return;
}
else {
my $fh_type = ref $fh;
if ( !Cpanel::FHUtils::Tiny::is_a($fh) ) {
Cpanel::Debug::log_warn("Invalid file handle type '$fh_type' provided for $open_method of '$file'");
return;
}
}
if ( my $lockref = _safelock($file) ) {
if ( $open_method_coderef->( $fh, $open_mode, $file ) ) {
my $lock_ex_nb = Cpanel::Fcntl::or_flags(qw( LOCK_EX LOCK_NB ));
if ( !flock $fh, $lock_ex_nb ) {
eval {
local $SIG{'ALRM'} = sub { die "flock LOCK_EX timeout"; };
my $orig_alarm = alarm $MAX_FLOCK_WAIT;
flock $fh, Cpanel::Fcntl::or_flags('LOCK_EX'); # This will hang
alarm $orig_alarm;
};
}
$OPEN_LOCKS++;
return $lockref;
}
else {
local $!;
safeunlock($lockref);
return;
}
}
else {
Cpanel::Debug::log_warn("could not acquire a lock for '$file': $!");
return;
}
}
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// ) {
Cpanel::Debug::log_warn('_safe_re_open: Invalid arguments');
return;
}
elsif ( !defined $fh ) {
Cpanel::Debug::log_warn("Undefined file handle provided for $open_method of '$file'");
return;
}
else {
my $fh_type = ref $fh;
if ( !Cpanel::FHUtils::Tiny::is_a($fh) ) {
Cpanel::Debug::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 ) ) {
my $lock_ex_nb = Cpanel::Fcntl::or_flags(qw( LOCK_EX LOCK_NB ));
if ( !flock $fh, $lock_ex_nb ) {
eval {
local $SIG{'ALRM'} = sub { die "flock LOCK_EX timeout"; };
my $orig_alarm = alarm $MAX_FLOCK_WAIT;
flock $fh, Cpanel::Fcntl::or_flags(qw( LOCK_EX )); # This will hang
alarm $orig_alarm;
};
}
return $fh;
}
return;
}
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 {
( $_[0] =~ /^[><]*(.*)/ )[0] . '.lock';
}
sub is_locked {
my ($file) = @_;
my $lockfile = _calculate_lockfile($file);
my ( $lock_pid, $lock_name, $lock_obj ) = _fetch_lockfile_info($lockfile);
if ( _is_valid_pid($lock_pid) && _pid_is_alive($lock_pid) ) {
return 1;
}
return 0;
}
sub _lock_wait {
my ( $file, $lockfile, $lockfile_inode, $lockfile_mtime ) = ( $_[0], ( $_[0] =~ /^[><]*(.*)/ )[0] . '.lock' );
my ( $start_lockfile_inode, $fileuid, $locksize, $start_lockfile_mtime ) = ( stat($lockfile) )[ 1, 4, 7, 9 ];
return _create_lockfile($lockfile) if !defined $locksize;
my $waittime = _calculate_waittime_for_file($file);
$lockfile_inode = $start_lockfile_inode;
$lockfile_mtime = $start_lockfile_mtime;
my $lock_file_age;
my $seconds_waited_for_valid_lockfile = 0;
my $lock_is_our_uid = 0;
while (1) {
if ( defined $locksize ) {
$lock_file_age = ( time() - $lockfile_mtime );
if ( $lock_file_age > $waittime ) {
Cpanel::Debug::log_info("Stale lock file: $lockfile. Age is $lock_file_age (mtime=$start_lockfile_mtime) which is longer than waittime ($waittime)") if $verbose == 1;
return _overwrite_lockfile_if_inode_matches( $lockfile, $lockfile_inode );
}
elsif ( $locksize == 0 && $seconds_waited_for_valid_lockfile > $MAX_WAIT_FOR_WRITE_TO_LOCKFILE ) {
Cpanel::Debug::log_invalid("Invalid lockfile $lockfile detected (zero size) [UID]: $fileuid [MTIME]: $start_lockfile_mtime [ORIGINAL INODE]: $start_lockfile_inode [TESTED INODE]: $lockfile_inode");
return _overwrite_lockfile_if_inode_matches( $lockfile, $lockfile_inode );
}
if ( ( $lock_is_our_uid = ( $fileuid == $> ) ) || $> == 0 ) {
my ( $lock_pid, $lock_name, $lock_obj ) = _fetch_lockfile_info($lockfile);
if ( _is_valid_pid($lock_pid) ) {
if ( $lock_pid == $$ ) {
my ( $filesys_lock_ino, $filesys_lock_mtime ) = ( lstat($lockfile) )[ 1, 9 ];
Cpanel::Debug::log_warn("[$$] Double locking detected by self [LOCK_PATH]=[$lockfile] [LOCK_PID]=[$lock_pid] [LOCK_OBJ]=[$lock_obj] [LOCK_PROCESS]=[$lock_name] [ACTUAL_INODE]=[$filesys_lock_ino] [ACTUAL_MTIME]=[$filesys_lock_mtime]");
return ( 0, $DOUBLE_LOCK_DETECTED );
}
elsif ( !_pid_is_alive($lock_pid) ) {
return _overwrite_lockfile_if_inode_matches( $lockfile, $lockfile_inode );
}
else {
Cpanel::Debug::log_info("[$$] Waiting for lock on $file held by $lock_name with pid $lock_pid") if $verbose == 1;
}
}
else {
Cpanel::Debug::log_info("[$$] Waiting on invalid lock $lockfile for $waittime seconds") if $verbose == 1;
}
}
}
( $lockfile_inode, $fileuid, $locksize, $lockfile_mtime ) = ( stat($lockfile) )[ 1, 4, 7, 9 ];
if ( !defined $locksize ) {
return _create_lockfile($lockfile);
}
elsif ( ( $lockfile_inode && $lockfile_inode != $start_lockfile_inode ) || ( $lockfile_mtime && $lockfile_mtime != $start_lockfile_mtime ) ) {
$start_lockfile_inode = $lockfile_inode;
$start_lockfile_mtime = $lockfile_mtime;
$seconds_waited_for_valid_lockfile = 0;
next; # Do not sleep
}
Cpanel::TimeHiRes::sleep(0.6); # Since mtimes are granular to the secord we sleep slightly more then
$seconds_waited_for_valid_lockfile += 0.6;
}
}
sub _pid_is_alive {
my ($pid) = @_;
if ( kill( 0, $pid ) ) {
return 1;
}
return 0;
}
sub _calculate_waittime_for_file {
my ($file) = @_;
return $LOCK_WAIT_TIME if $LOCK_WAIT_TIME;
my $waittime = 60;
if ( -e $file ) {
$waittime = int( ( stat(_) )[7] / 10000 );
$waittime = $waittime > 350 ? 350 : $waittime < 60 ? 60 : $waittime; # waittime is always between 60 and 350 seconds
}
return $waittime;
}
sub safe_readwrite {
my ( $file, $code_ref ) = @_;
return if !defined $file || $file eq '' || ref $code_ref ne 'CODE';
my $lockfh;
if ( my $lockref = safeopen( $lockfh, '+<', $file ) ) {
my $rclog = $code_ref->(
$lockfh,
sub {
my $fh = shift;
my $newfh = safe_replace_content( $fh, $lockref, @_ );
$lockfh = $newfh;
return 1;
}
);
safeclose( $lockfh, $lockref );
if ( $rclog && $rclog ne '0E0' ) {
eval q{
require Cpanel::RcsRecord;
Cpanel::RcsRecord::rcsrecord( $file, $rclog );
};
}
return $rclog;
}
else {
return;
}
}
sub _fetch_lockfile_info {
my $lockfile = shift;
my ( $lock_pid, $lock_name );
if ( open my $lockfile_fh, '<', $lockfile ) {
local $/;
my ( $pid_line, $lock_name, $lock_obj ) = split( /\n/, readline($lockfile_fh), 3 );
chomp($lock_name);
($lock_pid) = $pid_line && ( $pid_line =~ m/(\d+)/ );
close $lockfile_fh;
return ( $lock_pid, $lock_name || 'unknown', $lock_obj || 'unknown' );
}
}
sub _is_valid_pid {
my $pid = shift;
return 0 unless defined $pid;
return ( $pid =~ /^\d+$/ ? 1 : 0 );
}
sub _getdir {
my $file = shift;
my @path = split( /\/+/, $file );
pop(@path);
return join( '/', @path ) || '.';
}
sub _create_lockfile {
my ($lockfile) = @_;
my $lock_fh = Symbol::gensym();
$MAGIC_FCNTL_VALUE ||= Cpanel::Fcntl::or_flags(qw( O_WRONLY O_EXCL O_CREAT O_NONBLOCK ));
if ( sysopen( $lock_fh, $lockfile, $MAGIC_FCNTL_VALUE, 0600 ) ) {
return ( 1, $lock_fh );
}
return ( 0, $! );
}
sub _overwrite_lockfile_if_inode_matches {
my ( $lockfile, $lockfile_inode ) = @_;
my $lock_fh = Symbol::gensym();
if ( sysopen( $lock_fh, $lockfile, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_NONBLOCK O_APPEND O_NOFOLLOW )), 0600 ) ) {
if ( ( stat($lock_fh) )[1] == $lockfile_inode ) {
truncate( $lock_fh, 0 );
return ( 1, $lock_fh );
}
}
close($lock_fh);
return ( 0, $! );
}
1;
} # --- END Cpanel/SafeFile.pm
{ # --- BEGIN Cpanel/SafeDir/MK.pm
package Cpanel::SafeDir::MK;
use strict;
# use Cpanel::Logger ();
use Errno ();
my $DEFAULT_PERMISSIONS = 0755;
sub safemkdir {
my $dir = shift;
my $mode = shift;
my $errors = shift;
my $created = shift; # aref, where to push paths of dirs created
if ( defined $mode ) {
if ( $mode eq '' ) {
$mode = undef;
}
elsif ( $mode =~ /^0/ ) {
if ( $mode !~ /^0?[0-7]{3,4}$/ ) {
$mode = $DEFAULT_PERMISSIONS;
}
else {
$mode = oct($mode);
}
}
elsif ( $mode !~ /\A\d+\z/ ) {
$mode = $DEFAULT_PERMISSIONS;
}
}
$dir =~ s|/{2,}|/|g;
my $default = '';
if ( $dir =~ m/^\// ) {
$default = '/';
}
elsif ( $dir eq '.' || $dir eq './' ) {
if ( !-l $dir && defined $mode ) {
return chmod $mode, $dir;
}
return 1;
}
else {
$dir =~ s/^\.\///;
}
if ( $dir =~ m/(?:^|\/)\.\.(?:\/|$)/ ) {
Cpanel::Logger::logger(
{
'message' => "Possible improper directory $dir specified",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors,
'backtrace' => 0,
}
);
my @dir_parts = split /\//, $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::Logger::logger(
{
'message' => "Will not proceed above first directory part $first",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors,
'backtrace' => 0,
}
);
return 0;
}
if ( $first eq $good_parts[$#good_parts] ) {
undef $first;
}
pop @good_parts;
next;
}
elsif ( $part =~ m/^\.+$/ ) {
Cpanel::Logger::logger(
{
'message' => "Total stupidity found in directory $dir",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors,
'backtrace' => 0,
}
);
return 0;
}
push @good_parts, $part;
if ( !$first ) { $first = $part }
}
$dir = $default . join '/', @good_parts;
if ( !$dir ) {
Cpanel::Logger::logger(
{
'message' => "Could not validate given directory",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors,
'backtrace' => 0,
}
);
return;
}
Cpanel::Logger::logger(
{
'message' => "Improper directory updated to $dir",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors
}
);
}
if ( -d $dir ) {
if ( !-l $dir && defined $mode ) {
return chmod $mode, $dir;
}
return 1;
}
elsif ( -e _ ) {
Cpanel::Logger::logger(
{
'message' => "$dir was expected to be a directory!",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors
}
);
$! = Errno::ENOTDIR();
return 0;
}
my @dir_parts = split /\//, $dir;
if ( scalar @dir_parts > 100 ) {
Cpanel::Logger::logger(
{
'message' => "Encountered excessive directory length. This should never happen.",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors
}
);
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::Logger::logger(
{
'message' => "mkdir $newdir failed: $!",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors
}
);
return;
}
}
elsif ( !$is_dir ) {
Cpanel::Logger::logger(
{
'message' => "Encountered non-directory $newdir in path of $dir: $!",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => $errors
}
);
$! = Errno::ENOTDIR();
last;
}
}
return $returnvalue;
}
1;
} # --- END Cpanel/SafeDir/MK.pm
{ # --- BEGIN Cpanel/FileUtils/TouchFile.pm
package Cpanel::FileUtils::TouchFile;
use strict;
my $logger;
our $VERSION = '1.3';
sub _log {
my ( $level, $msg ) = @_;
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
$logger->$level($msg);
return;
}
sub touchfile {
my ( $file, $verbose, $fail_ok ) = @_;
if ( !defined $file ) {
_log( 'warn', "touchfile called with undefined file" );
return;
}
my $mtime = -e $file ? ( stat _ )[9] : 0; # for warnings safe numeric comparison
my $now = time();
if ( $mtime && utime $now, $now, $file ) {
return 1;
}
my $mtime_after_utime = $mtime && ( stat $file )[9];
if ( $mtime == $mtime_after_utime ) {
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
}
}
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/Validate/FilesystemNodeName.pm
package Cpanel::Validate::FilesystemNodeName;
use strict;
use Try::Tiny;
# use Cpanel::Exception ();
my $MAX_LENGTH = 255;
sub is_valid {
my ($node) = @_;
my $err;
try {
validate_or_die($node);
}
catch {
$err = $_;
};
return $err ? 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 > $MAX_LENGTH ) {
die Cpanel::Exception::create( 'TooManyBytes', { value => $name, maxlength => $MAX_LENGTH } );
}
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 Cpanel::Fcntl ();
# use Cpanel::SafeFile ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Exception ();
our $VERSION = '1.7';
my $DEFAULT_CONTENT_TYPE = 'text/plain; charset=utf-8';
our $NOTIFY_INTERVAL_STORAGE_DIR = '/var/cpanel/notifications';
my $logger = Cpanel::Logger->new();
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};
}
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 ) {
$logger->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 = IO::Handle->new();
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 {
$logger->warn("Could not open $db_file: $!");
return;
}
if ( $notifications{$status} && ( ( $notifications{$status} + $interval ) > time() ) ) {
return 1;
}
return 0;
}
*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::SafeDir::MK::safemkdir( $NOTIFY_INTERVAL_STORAGE_DIR, '0700' );
if ( !-d $NOTIFY_INTERVAL_STORAGE_DIR ) {
$logger->warn("Failed to setup notifications directory: $NOTIFY_INTERVAL_STORAGE_DIR: $!");
return;
}
}
my %notifications;
my $nlock;
my $notify_db_fh = IO::Handle->new();
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 {
$logger->warn("Could not open $db_file: $!");
return;
}
return $notify;
}
1;
} # --- END Cpanel/Notify.pm
{ # --- BEGIN Cpanel/Autodie/Utils.pm
package Cpanel::Autodie::Utils;
use strict;
use warnings;
sub mkdir_list {
my (@args) = @_;
my $ret;
return CORE::mkdir( $args[0], $args[1] ) if @args > 1;
@args = ($_) if !@args;
return CORE::mkdir( $args[0] );
}
sub die_for_mkdir {
my (@args) = @_;
@args = ($_) if !@args;
die Cpanel::Exception::create( 'IO::DirectoryCreateError', { error => $!, path => $args[0], mask => $args[1] } );
}
1;
} # --- END Cpanel/Autodie/Utils.pm
{ # --- BEGIN Cpanel/Autodie.pm
package Cpanel::Autodie;
use strict;
use warnings;
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::Exception ();
# use Cpanel::Autodie::Fcntl ();
# use Cpanel::Autodie::Utils ();
{
no warnings 'once';
*fcntl = \&Cpanel::Autodie::Fcntl::fcntl;
}
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 ) {
die Cpanel::Exception::create( 'IO::ForkError', { error => $! } );
}
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 {
if ( $mode eq '|-' || $mode eq '-|' ) {
my $cmd = $expr;
if ( !@list ) {
($cmd) = ( $cmd =~ m<\A(\S+)> );
}
die Cpanel::Exception::create( 'IO::ExecError', { path => $cmd, error => $! } );
}
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]', [$!] );
}
die Cpanel::Exception::create( 'IO::FileOpenError', { mode => $mode, path => $expr, error => $! } );
};
}
sub sysopen { ## no critic(RequireArgUnpacking)
my @post_handle_args = ( @_[ 1 .. $#_ ] );
my ( $path, $mode, $perms ) = @post_handle_args;
local ( $!, $^E );
my $ret;
if ( @post_handle_args < 3 ) {
$ret = CORE::sysopen( $_[0], $path, $mode );
}
else {
$ret = CORE::sysopen( $_[0], $path, $mode, $perms );
}
if ( !$ret ) {
die Cpanel::Exception::create( 'IO::FileOpenError', { path => $path, mode => $mode, error => $!, permissions => $perms } );
}
return $ret;
}
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;
}
die Cpanel::Exception::create( 'IO::WriteError', { length => $length, error => $! } );
}
return $ret;
}
sub syswrite { ## no critic(RequireArgUnpacking)
my ( $fh, @length_offset ) = ( $_[0], @_[ 2 .. $#_ ] );
my ( $length, $offset ) = @length_offset;
local ( $!, $^E );
my $ret;
if ( @length_offset > 1 ) {
$ret = CORE::syswrite( $fh, $_[1], $length, $offset );
}
elsif (@length_offset) {
$ret = CORE::syswrite( $fh, $_[1], $length );
}
else {
$ret = CORE::syswrite( $fh, $_[1] );
}
if ( !defined $ret ) {
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;
}
die Cpanel::Exception::create( 'IO::WriteError', { error => $!, length => $length } );
}
return $ret;
}
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 ) {
die Cpanel::Exception::create( 'IO::ReadError', { error => $!, length => $length } );
}
return $ret;
}
sub sysread { ## no critic(RequireArgUnpacking)
my ( $fh, @length_offset ) = ( $_[0], @_[ 2 .. $#_ ] );
my ( $length, $offset ) = @length_offset;
local ( $!, $^E );
my $ret;
if ( @length_offset > 1 ) {
$ret = CORE::sysread( $fh, $_[1], $length, $offset );
}
else {
$ret = CORE::sysread( $fh, $_[1], $length );
}
if ( !defined $ret ) {
die Cpanel::Exception::create( 'IO::ReadError', { error => $!, length => $length } );
}
return $ret;
}
sub close {
my $fh = shift;
my $filename = shift;
local ( $!, $^E );
return ( $fh ? CORE::close($fh) : CORE::close() ) || do {
die Cpanel::Exception::create( 'IO::CloseError', { error => $!, filename => $filename } );
};
}
sub seek {
my ( $fh, $pos, $whence ) = @_;
local ( $!, $^E );
return CORE::seek( $fh, $pos, $whence ) || do {
die Cpanel::Exception::create( 'IO::FileSeekError', { path => $fh, error => $!, whence => $whence, position => $pos } );
};
}
sub sysseek {
my ( $fh, $pos, $whence ) = @_;
local ( $!, $^E );
return CORE::sysseek( $fh, $pos, $whence ) || do {
die Cpanel::Exception::create( 'IO::FileSeekError', { path => $fh, error => $!, whence => $whence, position => $pos } );
};
}
sub truncate {
my ( $fh_or_expr, $length ) = @_;
local ( $!, $^E );
return CORE::truncate( $fh_or_expr, $length ) || do {
die Cpanel::Exception::create( 'IO::FileTruncateError', { error => $!, length => $length } );
};
}
sub opendir { ##no critic qw(RequireArgUnpacking)
local ( $!, $^E );
return CORE::opendir( $_[0], $_[1] ) || do {
die Cpanel::Exception::create( 'IO::DirectoryOpenError', { path => $_[1], error => $! } );
};
}
sub rewinddir {
my ($dh) = @_;
local ( $!, $^E );
return CORE::rewinddir($dh) || do {
die Cpanel::Exception::create( 'IO::DirectoryRewindError', { error => $! } );
};
}
sub closedir {
my ($dh) = @_;
local ( $!, $^E );
return CORE::closedir($dh) || do {
die Cpanel::Exception::create( 'IO::DirectoryCloseError', { error => $! } );
};
}
sub stat {
my ($path_or_fh) = @_;
local ( $!, $^E );
my $ret = wantarray ? [ CORE::stat($path_or_fh) ] : CORE::stat($path_or_fh);
if ($!) {
if ( Cpanel::FHUtils::Tiny::is_a($path_or_fh) ) {
die Cpanel::Exception::create( 'IO::StatError', { error => $! } );
}
die Cpanel::Exception::create( 'IO::StatError', { error => $!, path => $path_or_fh } );
}
return wantarray ? @$ret : $ret;
}
sub lstat {
my ($path_or_fh) = @_;
local ( $!, $^E );
my $ret = wantarray ? [ CORE::lstat($path_or_fh) ] : CORE::lstat($path_or_fh);
if ($!) {
if ( Cpanel::FHUtils::Tiny::is_a($path_or_fh) ) {
die Cpanel::Exception::create( 'IO::StatError', { error => $! } );
}
die Cpanel::Exception::create( 'IO::StatError', { error => $!, path => $path_or_fh } );
}
return wantarray ? @$ret : $ret;
}
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 ( Cpanel::FHUtils::Tiny::is_a($target) ) {
die Cpanel::Exception::create( 'IO::ChmodError', { error => $!, permissions => $mode } );
}
die Cpanel::Exception::create( 'IO::ChmodError', { error => $!, permissions => $mode, path => $target } );
};
}
sub chown {
my ( $uid, $gid, $target, @too_many_args ) = @_;
die "Only one path at a time!" if @too_many_args;
local ( $!, $^E );
return CORE::chown( $uid, $gid, $target ) || do {
my $path = Cpanel::FHUtils::Tiny::is_a($target) ? undef : $target;
die Cpanel::Exception::create( 'IO::ChownError', { error => $!, uid => $uid, gid => $gid, path => $path } );
};
}
sub link {
my ( $old, $new ) = @_;
local ( $!, $^E );
return CORE::link( $old, $new ) || do {
die Cpanel::Exception::create( 'IO::LinkError', { error => $!, oldpath => $old, newpath => $new } );
};
}
sub symlink {
my ( $old, $new ) = @_;
local ( $!, $^E );
return CORE::symlink( $old, $new ) || do {
die Cpanel::Exception::create( 'IO::SymlinkCreateError', { error => $!, oldpath => $old, newpath => $new } );
};
}
sub readlink { ## no critic(RequireArgUnpacking)
my $path = @_ ? shift : $_;
local ( $!, $^E );
return CORE::readlink($path) || do {
die Cpanel::Exception::create( 'IO::SymlinkReadError', { error => $!, path => $path } );
};
}
sub rename {
my ( $old, $new ) = @_;
local ( $!, $^E );
return CORE::rename( $old, $new ) || do {
die Cpanel::Exception::create( 'IO::RenameError', { error => $!, oldpath => $old, newpath => $new } );
};
}
sub unlink {
my (@paths) = @_;
die "Only one path at a time!" if @paths > 1;
if ( !@paths ) {
@paths = ($_);
}
local ( $!, $^E );
return CORE::unlink(@paths) || do {
die Cpanel::Exception::create( 'IO::UnlinkError', { error => $!, path => \@paths } );
};
}
sub mkdir {
my (@args) = @_;
local ( $!, $^E );
my $ret = Cpanel::Autodie::Utils::mkdir_list(@args);
if ( !$ret ) {
Cpanel::Autodie::Utils::die_for_mkdir(@args);
}
return $ret;
}
sub rmdir {
my (@args) = @_;
die "Only one path at a time!" if @args > 1;
if ( !@args ) {
@args = ($_);
}
local ( $!, $^E );
return CORE::rmdir( $args[0] ) || do {
die Cpanel::Exception::create( 'IO::DirectoryDeleteError', { error => $!, path => $args[0] } );
};
}
sub pipe { ##no critic qw(RequireArgUnpacking)
local ( $!, $^E );
return CORE::pipe( $_[0], $_[1] ) || do {
die Cpanel::Exception::create( 'IO::PipeError', { error => $! } );
};
}
sub select { ##no critic qw(RequireArgUnpacking)
my ( $rbits_r, $wbits_r, $ebits_r, $timeout ) = ( \$_[0], \$_[1], \$_[2], $_[3] );
die "Need four args!" if @_ < 4;
local ( $!, $^E );
my ( $nfound, $timeleft ) = select( $$rbits_r, $$wbits_r, $$ebits_r, $timeout );
if ($!) {
die Cpanel::Exception::create( 'IO::SelectError', { error => $! } );
}
return wantarray ? ( $nfound, $timeleft ) : $nfound;
}
sub socket { ##no critic qw(RequireArgUnpacking)
my ( $domain, $type, $protocol ) = ( @_[ 1 .. 3 ] );
local ( $!, $^E );
return socket( $_[0], $domain, $type, $protocol ) || do {
die Cpanel::Exception::create( 'IO::SocketOpenError', { domain => $domain, type => $type, protocol => $protocol, error => $! } );
};
}
sub systell {
my ($fh) = @_;
return 0 + __PACKAGE__->can('sysseek')->( $fh, 0, 1 );
}
1;
} # --- END Cpanel/Autodie.pm
{ # --- BEGIN Cpanel/Hash.pm
package Cpanel::Hash;
use strict;
*get_fastest_hash = \&_fnv1a_32;
my $FNV1_32A_INIT = 0x811c9dc5;
my $FNV_32_PRIME = 0x01000193;
sub _fnv1a_32 {
my ($data_to_hash) = @_;
my $fnv32 = $FNV1_32A_INIT;
foreach my $c ( unpack( 'C*', $data_to_hash ) ) {
$fnv32 ^= $c;
$fnv32 *= $FNV_32_PRIME;
$fnv32 &= 0xffffffff;
}
return $fnv32;
}
1;
} # --- END Cpanel/Hash.pm
{ # --- BEGIN Cpanel/Readlink.pm
package Cpanel::Readlink;
use strict;
# use Cpanel::Autodie ();
# use Cpanel::FindBin ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::Exception ();
our $MAX_SYMLINK_DEPTH = 1024;
sub deep {
my ($link) = @_;
die Cpanel::Exception::create( 'MissingParameter', 'Provide a link path.' ) if !length $link;
return $link if !-l $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() . '/' . $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 $link;
}
sub _get_base_for {
my $basename = shift;
my @path = split( '/', $basename );
pop(@path);
return join( '/', @path );
}
sub _pwd {
my $bin = Cpanel::FindBin::findbin('pwd');
{
no warnings 'redefine';
*Cpanel::Readlink::_pwd = sub { return $bin; };
}
return $bin;
}
sub cwd {
my $cwd = Cpanel::SafeRun::Simple::saferun( _pwd() );
chomp $cwd;
return $cwd;
}
1;
} # --- END Cpanel/Readlink.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 DESTROY {
my ($self) = @_;
return if $$ != $self->{'pid'};
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/FileUtils/Write.pm
package Cpanel::FileUtils::Write;
use strict;
# use Cpanel::Fcntl ();
# use Cpanel::Readlink ();
# use Cpanel::Autodie ();
# use Cpanel::Exception ();
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::FileUtils::Open ();
# use Cpanel::Finally ();
our $MAX_TMPFILE_CREATE_ATTEMPTS = 1024;
my $DEFAULT_PERMS = 0600;
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 { ##no critic qw(RequireArgUnpacking)
_write_to_tmpfile( @_[ 0 .. 2 ], \&_write_finish );
return 1;
}
sub overwrite { ##no critic qw(RequireArgUnpacking)
_write_to_tmpfile( @_[ 0 .. 2 ], \&_overwrite_finish );
return 1;
}
sub _write_to_tmpfile { ##no critic qw(RequireArgUnpacking)
my ( $filename, $perms, $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 );
$filename = Cpanel::Readlink::deep($filename);
my $tmp_perms = defined $perms ? $perms : $DEFAULT_PERMS;
my ( $tmpfile, $attempts ) = ( '', 0 );
while (1) {
my ($rand) = ( rand(99999999) =~ m<([0-9]+)> ); #untaint
$tmpfile = "$filename.tmp.$rand";
last if Cpanel::FileUtils::Open::sysopen_with_real_perms(
$fh,
$tmpfile,
'O_WRONLY|O_CREAT|O_EXCL',
$tmp_perms,
);
if ( !$!{'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 {
Cpanel::Autodie::unlink($tmpfile) if !$tmpfile_is_renamed;
return;
}
);
Cpanel::Autodie::print( $fh, $_[1] );
Cpanel::Autodie::close( $fh, $tmpfile );
$tmpfile_is_renamed = $finish_cr->( $tmpfile, $filename );
return $tmpfile;
}
sub _write_finish {
my ( $tmpfile, $filename ) = @_;
Cpanel::Autodie::link( $tmpfile, $filename );
return 0;
}
sub _overwrite_finish {
my ( $tmpfile, $filename ) = @_;
return Cpanel::Autodie::rename( $tmpfile, $filename );
}
sub _old_writefile_please_do_not_use___the_stuff_above_is_better {
my ( $filename_or_fh, $contents, $perms, $no_overwrite ) = @_;
if ( !defined $filename_or_fh ) {
exists $INC{'Carp.pm'} ? Carp::confess("writefile called with undefined filename_or_fh") : die("writefile called with undefined filename_or_fh");
}
my $fh_type = ref $filename_or_fh;
if ( Cpanel::FHUtils::Tiny::is_a($filename_or_fh) ) {
seek( $filename_or_fh, 0, 0 );
if ( ref $contents eq 'CODE' ) {
if ( !$contents->($filename_or_fh) ) {
warn "Failed to execute coderef: $!";
return;
}
}
elsif ( !print {$filename_or_fh} ( ref $contents eq 'SCALAR' ? $$contents : $contents )
or !$filename_or_fh->flush() ) {
warn "Failed to write: $!";
return;
}
truncate( $filename_or_fh, tell($filename_or_fh) ); # fail ok
return 1;
}
elsif ($fh_type) {
exists $INC{'Carp.pm'} ? Carp::confess("writefile requires a filename or filehandle") : die("writefile requires a filename or filehandle");
}
else {
$filename_or_fh = Cpanel::Readlink::deep($filename_or_fh);
}
my $orig_umask;
if ( defined $perms ) {
$orig_umask = umask();
umask( $perms ^ 07777 );
}
my ( $tmpfile, $attempts, $fh ) = ( '', 0 );
while ( !$tmpfile
|| ( ++$attempts < $MAX_TMPFILE_CREATE_ATTEMPTS && !sysopen( $fh, $tmpfile, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_EXCL O_CREAT )), defined $perms ? 00777 : 00666 ) ) ) {
$fh = undef;
$tmpfile = $filename_or_fh . '.tmp.' . rand(99999999);
($tmpfile) = $tmpfile =~ /(.*)/; #untaint
}
umask($orig_umask) if defined $orig_umask;
return unless defined $fh;
if ( ref $contents eq 'CODE' ) {
if ( !$contents->($fh) ) {
warn "Failed to execute coderef: $!";
close $fh;
unlink($tmpfile);
return;
}
}
elsif ( !print {$fh} ( ref $contents eq 'SCALAR' ? $$contents : $contents ) or !close($fh) ) {
exists $INC{'Carp.pm'} ? Carp::cluck("Failed to write: $!") : warn "Failed to write: $!";
close $fh;
unlink($tmpfile);
return;
}
if ($no_overwrite) {
if ( link( $tmpfile, $filename_or_fh ) ) {
unlink($tmpfile);
return 1;
}
else {
unlink($tmpfile);
return 0;
}
}
return 1 if rename( $tmpfile, $filename_or_fh );
unlink($tmpfile);
return;
}
*writefile = \&_old_writefile_please_do_not_use___the_stuff_above_is_better;
1;
} # --- END Cpanel/FileUtils/Write.pm
{ # --- BEGIN Cpanel/FileUtils/Write/JSON/Lazy.pm
package Cpanel::FileUtils::Write::JSON::Lazy;
use strict;
# use Cpanel::FileUtils::Write ();
# use Cpanel::FHUtils::Tiny ();
sub write_file {
my ( $file_or_fh, $data, $perms ) = @_;
if ( exists $INC{'Cpanel/JSON.pm'} && exists $INC{'JSON/XS.pm'} ) { # need to check for both for updatenow.static
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,
'Cpanel::JSON'->can('Dump')->($data), #must be quoted or it ends up in the stash
$perms
);
}
return 0;
}
1;
} # --- END Cpanel/FileUtils/Write/JSON/Lazy.pm
{ # --- BEGIN Cpanel/AdminBin/Serializer/FailOK.pm
package Cpanel::AdminBin::Serializer::FailOK;
use strict;
# use Cpanel::LoadModule ();
my $LoadFile_code;
sub LoadModule {
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
Cpanel::LoadModule::load_perl_module('Cpanel::AdminBin::Serializer');
1;
};
if ( !$load_ok && !$ENV{'CPANEL_BASE_INSTALL'} && $^X =~ m{^/usr/local/cpanel} ) {
warn $@;
}
return $load_ok ? 1 : 0;
}
sub LoadFile {
my ( $file_or_fh, $path ) = @_;
return undef if !$INC{'Cpanel/AdminBin/Serializer.pm'} || !$INC{'Cpanel/JSON.pm'} || !$INC{'JSON/XS.pm'}; # Cpanel::AdminBin::Serializer can be loaded without JSON::XS in updatenow.static so we must check both
my $ref;
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
$LoadFile_code ||= 'Cpanel::AdminBin::Serializer'->can('LoadFile');
$ref = $LoadFile_code->( $file_or_fh, undef, $path ); # Cpanel::AdminBin::Serializer must be quoted to avoid bringing it in with the compiler
};
return $ref;
}
1;
} # --- END Cpanel/AdminBin/Serializer/FailOK.pm
{ # --- BEGIN Cpanel/Config/LoadConfig.pm
package Cpanel::Config::LoadConfig;
use strict;
use IO::Handle ();
# use Cpanel::Hash (); #checked for bloat 7/11/10 - jnk
# use Cpanel::SafeFile (); #checked for bloat 7/11/10 - jnk
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::AdminBin::Serializer::FailOK ();
my $logger;
my $PRODUCT_CONF_DIR = '/var/cpanel';
my %COMMON_CACHE_NAMES = (
':__^\s*[#;]____0__' => 'default_colon',
':\s+__^\s*[#;]____0__' => 'default_colon_any_space',
'=__^\s*[#;]____0__skip_readable_check_____1' => 'default_skip_readable',
'=__^\s*[#;]____0__' => 'default',
'\s*[:]\s*__^\s*[#;]____0__' => 'default_colon_before_after_space'
);
my $DEFAULT_DELIMITER = '=';
my $DEFAULT_COMMENT_REGEXP = '^\s*[#;]';
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{$_} ||= 0 for @BOOLEAN_OPTIONS;
return %opts;
}
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; $homedir = (Cpanel::PwCache::getpwuid($>))[7]; ';
}
$homedir ||= ( getpwuid($>) )[7];
($homedir) = $homedir =~ /(.*)/; #untaint
return ( $homedir, undef ) if $homedir =~ m{^/+$} || !-w $homedir;
$cache_dir = $homedir . '/.cpanel/caches/config';
}
return ( $homedir, $cache_dir );
}
sub loadConfig {
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 ( $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
)
};
my $is_root = ( $> == 0 ? 1 : 0 );
if ( !$file || $file =~ tr/\0// ) {
_do_logger( 'warn', 'loadConfig requires valid filename' );
return;
}
my $filesys_mtime;
if ( !$arg_ref->{'skip_readable_check'} ) {
return if ( !-e $file );
if ( !-r _ ) {
_do_logger( 'info', "Unable to read $file: $!" );
return;
}
$filesys_mtime = ( stat(_) )[9];
}
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;
if ( $INC{'Cpanel/JSON.pm'} && ( !defined $arg_ref || !ref $arg_ref || !exists $arg_ref->{'nocache'} && !$arg_ref->{'keep_locked_open'} ) ) {
my $safefile = $file;
$safefile =~ tr{/}{_};
my $stringified_args = join( '__', $delimiter, $comment, $regexp_to_preprune, $allow_undef_values, _sorted_hashref_txt($arg_ref) );
if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) {
print STDERR __PACKAGE__ . "::loadConfig stringified_args[$stringified_args]\n";
}
my $cache_key = $safefile . '___' . ( exists $COMMON_CACHE_NAMES{$stringified_args} ? $COMMON_CACHE_NAMES{$stringified_args} : Cpanel::Hash::get_fastest_hash($stringified_args) );
$cache_file = $cache_dir . '/' . $cache_key if defined $cache_dir;
$filesys_mtime ||= ( stat($file) )[9];
if ( $cache_file && open( my $cache_fh, '<', $cache_file ) ) { # ok if the file is not there
my ( $cache_filesys_mtime, $now, $cache_conf_ref ) = ( ( stat($cache_fh) )[9], 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 && $cache_filesys_mtime > $filesys_mtime && $cache_filesys_mtime <= $now ) {
if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) { print STDERR __PACKAGE__ . "::loadConfig using cache_file:$cache_file\n"; }
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);
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 wantarray ? %{$ref_to_return} : $ref_to_return;
}
}
else {
if ( ( $Cpanel::Debug::level || 0 ) >= 5 ) { print STDERR __PACKAGE__ . "::loadConfig NOT using cache_file:$cache_file\n"; }
}
close($cache_fh);
}
}
$conf_ref = {} if !$load_into_conf_ref;
my $conf_fh = IO::Handle->new();
my $conflock = Cpanel::SafeFile::safeopen( $conf_fh, ( $arg_ref->{'rw'} ? '+<' : '<' ), $file ) or do {
require Cpanel::Logger;
Cpanel::Logger::cplog( "Unable to open $file: $!", 'warn', __PACKAGE__ );
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 ( !$arg_ref || !$arg_ref->{'keep_locked_open'} ) {
Cpanel::SafeFile::safeclose( $conf_fh, $conflock );
}
if ( !$parse_ok ) {
require Cpanel::Logger;
Cpanel::Logger::cplog( "Unable to parse $file: $parsed", 'warn', __PACKAGE__ );
return;
}
@{$conf_ref}{ keys %$parsed } = values %$parsed;
if ($cache_file) {
my @dirs = ($cache_dir);
if ( !$is_root ) {
unshift @dirs, "$homedir/.cpanel", "$homedir/.cpanel/caches";
}
foreach my $dir (@dirs) {
($dir) = $dir =~ /(.*)/; #untaint
if ( !-d $dir ) {
mkdir( $dir, $CACHE_DIR_PERMS ) or do {
_do_logger( 'warn', "Failed to create dir “$dir”: $!" );
};
}
chmod( $CACHE_DIR_PERMS, $dir ) or do {
_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 ) {
print STDERR __PACKAGE__ . "::loadConfig [lazy write cache file] [$cache_file] wrote_ok:[$wrote_ok]\n";
}
}
if ( $arg_ref->{'keep_locked_open'} ) {
return $conf_ref, $conf_fh, $conflock;
}
return wantarray ? %{$conf_ref} : $conf_ref;
}
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 ) = @_;
%opts = _process_parse_args(%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 = {};
if ( !$limit && !$regexp_to_preprune && !$use_hash_of_arr_refs && length $delimiter ) {
local $/;
my $cfg_txt = readline($conf_fh);
my $parser_code;
my $key_value_text = $use_reverse ? '1,0' : '0,1';
my ( $k, $v );
if ($allow_undef_values) {
$parser_code = ' %{$conf_ref}=( %$conf_ref, (map { ' . ( $comment ? 'm{' . $comment . '} ? () : ' : q{} ) . '(split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . '] } split(/\r?\n/, $cfg_txt) ) ); ';
}
else {
if ($comment) {
$parser_code = ' %{$conf_ref}=( %$conf_ref, map { ' . 'if (m{' . $comment . '}) { (); } else { ' . '($k,$v) = (split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . ']; ' . 'defined($v) ? ($k,$v) : (); ' . '} } split(/\r?\n/, $cfg_txt ) )';
}
else {
$parser_code = ' %{$conf_ref}=( %$conf_ref, map { ' . '($k,$v) = (split(m/' . $delimiter . '/, $_, 2))[' . $key_value_text . ']; ' . 'defined($v) ? ($k,$v) : () ' . '} split(/\r?\n/, $cfg_txt ) )';
}
}
$parser_code .= "; 1";
eval($parser_code) or do {
_do_logger( 'panic', "Failed to parse :: $parser_code" );
return ( 0, "$@\n$parser_code" );
};
delete $conf_ref->{''} if !defined( $conf_ref->{''} );
}
else {
if ( ( $Cpanel::Debug::level || 0 ) > 4 ) {
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";
}
my @dconf = <$conf_fh>;
my $keys = 0;
my ( $name, $value );
my $parser_code_ref;
my $parser_code = '$parser_code_ref = sub {
LINELOOP:
foreach my $line (@dconf) {
$line =~ s/\r?\n\z//; ' . "\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"
. ( $regexp_to_preprune ? q{$line =~ s/$regexp_to_preprune//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; } ) . '
}
}; 1';
eval($parser_code) or do {
_do_logger( 'panic', "Failed to generate parser code :: $parser_code" );
return ( 0, "$@\n$parser_code" );
};
$parser_code_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 _sorted_hashref_txt {
my ($hashref) = @_;
return (
( scalar keys %$hashref )
? join(
'_____', map { $_, ( ref $hashref->{$_} eq 'HASH' ? _sorted_hashref_txt( $hashref->{$_} ) : ref $hashref->{$_} eq 'ARRAY' ? join( '_____', @{ $hashref->{$_} } ) : defined $hashref->{$_} ? $hashref->{$_} : '' ) }
sort keys %$hashref
)
: ''
); #sort is important for order;
}
sub default_product_dir {
$PRODUCT_CONF_DIR = shift if @_;
return $PRODUCT_CONF_DIR;
}
1;
} # --- END Cpanel/Config/LoadConfig.pm
{ # --- BEGIN Cpanel/ConfigFiles/Apache.pm
package Cpanel::ConfigFiles::Apache;
use strict;
# use Cpanel::Config::LoadConfig ();
my $multiton = {};
my $lazyfacade;
sub apache_paths_facade {
return $lazyfacade ||= Cpanel::ConfigFiles::Apache->new();
}
sub import {
my ( $class, $arg ) = @_;
if ( defined $arg ) {
if ( $arg eq 'apache_paths_facade' ) {
my $caller = caller;
no strict 'refs'; ## no critic(ProhibitNoStrict)
*{ $caller . "::apache_paths_facade" } = \&apache_paths_facade;
}
else {
die "$class does not import $arg\n";
}
}
return 1;
}
sub new {
my ( $class, $path ) = @_;
$path ||= '/etc/cpanel/ea4/paths.conf';
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) {
Cpanel::Config::LoadConfig::loadConfig( $path, $conf, '\s*=\s*', undef, '^\s*' );
}
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 {
my $self = shift;
my %newhash = %$self;
delete $newhash{_meta};
return \%newhash;
}
sub dir_base {
return shift->{'dir_base'};
}
sub dir_logs {
return shift->{'dir_logs'};
}
sub dir_domlogs {
return shift->{'dir_domlogs'};
}
sub dir_modules {
return shift->{'dir_modules'};
}
sub dir_run {
return shift->{'dir_run'};
}
sub dir_conf {
return shift->{'dir_conf'};
}
sub dir_conf_includes {
return shift->{'dir_conf_includes'};
}
sub dir_conf_userdata {
return shift->{'dir_conf_userdata'};
}
sub dir_docroot {
return shift->{'dir_docroot'};
}
sub file_access_log {
return shift->{'file_access_log'};
}
sub file_error_log {
return shift->{'file_error_log'};
}
sub file_conf {
return shift->{'file_conf'};
}
sub file_conf_mime_types {
return shift->{'file_conf_mime_types'};
}
sub file_conf_srm_conf {
return shift->{'file_conf_srm_conf'};
}
sub file_conf_php_conf {
return shift->{'file_conf_php_conf'};
}
sub bin_httpd {
return shift->{'bin_httpd'};
}
sub bin_apachectl {
return shift->{'bin_apachectl'};
}
sub bin_suexec {
return shift->{'bin_suexec'};
}
1;
} # --- END Cpanel/ConfigFiles/Apache.pm
{ # --- BEGIN Cpanel/ConfigFiles.pm
package Cpanel::ConfigFiles;
use strict;
our $VERSION = '1.4';
our $apache2_marker = '/var/cpanel/apache2';
our $apache2_srm = '/usr/local/apache2/conf/srm.conf';
our $default_srm = '/etc/httpd/conf/srm.conf';
our $apache2_mime = '/usr/local/apache2/conf/mime.types';
our $default_mime = '/etc/httpd/conf/mime.types';
our $cpanel_users = '/var/cpanel/users';
our $cpanel_users_cache = '/var/cpanel/users.cache';
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 $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 $PACKAGES_DIR = '/var/cpanel/packages';
our $FEATURES_DIR = '/var/cpanel/features';
our $BANDWIDTH_LIMIT_DIR = '/var/cpanel/bwlimited';
our $CUSTOM_PERL_MODULES_DIR = '/var/cpanel/perl';
our $QUOTA_CONF_FILE = '/etc/quota.conf';
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 $NAMESERVER_IPS_FILE = '/etc/nameserverips';
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 $USERBWLIMITS_FILE = '/etc/userbwlimits';
our $MAILIPS_FILE = '/etc/mailips';
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 $RECENT_RECIPIENT_MAIL_SERVER_IPS_FILE = '/etc/recent_recipient_mail_server_ips';
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 $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 @IP_ADDRESS_LIST_FILES = qw{ /etc/ips /etc/ips.dnsmaster /etc/ip.remotedns /etc/ips.remotedns };
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 $APACHE_LOGFILE_CLEANUP_QUEUE = '/var/cpanel/apache_logfile_cleanup.json';
sub stat_httpconf {
my $file = find_httpconf();
my @stat = stat(_);
return wantarray ? ( $file, \@stat ) : $file;
}
sub find_httpconf {
my $not_fatal = shift;
require Cpanel::ConfigFiles::Apache; # using Cpanel::LoadModule w/ add 450 to RSS which deviates from the intent of this being a lightweight way to know where all the config files are
my $httpd_conf_file = Cpanel::ConfigFiles::Apache::apache_paths_facade()->file_conf();
if ( -e $httpd_conf_file ) {
return $httpd_conf_file;
}
die "Unable to locate httpd.conf ($httpd_conf_file)" if !$not_fatal;
return;
}
sub find_httpdconf { goto &find_httpconf; }
sub stat_srmconf {
my $file = find_srmconf();
my @stat = stat(_);
return wantarray ? ( $file, \@stat ) : $file;
}
sub get_srmconf {
require Cpanel::ConfigFiles::Apache; # using Cpanel::LoadModule w/ add 450 to RSS which deviates from the intent of this being a lightweight way to know where all the config files are
my $apache_srm = Cpanel::ConfigFiles::Apache::apache_paths_facade()->file_conf_srm_conf();
return $apache_srm;
}
sub get_mimetypes {
require Cpanel::ConfigFiles::Apache; # using Cpanel::LoadModule w/ add 450 to RSS which deviates from the intent of this being a lightweight way to know where all the config files are
my $apache_mime = Cpanel::ConfigFiles::Apache::apache_paths_facade()->file_conf_mime_types();
return $apache_mime;
}
sub find_srmconf {
my $apache_srm = get_srmconf();
my ( @LOC, $loc );
if ( -e $apache2_marker ) {
@LOC = ( $apache2_srm, $default_srm );
}
else {
@LOC = ( $apache_srm, $default_srm );
}
foreach $loc (@LOC) {
if ( -e $loc ) {
return $loc;
}
}
return;
}
sub find_mimetypes {
my $apache_mime = get_mimetypes();
my ( @LOC, $loc );
if ( -e $apache2_marker ) {
@LOC = ( $apache2_mime, $default_mime );
}
else {
@LOC = ( $apache_mime, $default_mime );
}
foreach $loc (@LOC) {
if ( -e $loc ) {
return $loc;
}
}
return;
}
sub stat_mimetypes {
my $file = find_mimetypes();
my @stat = stat(_);
return wantarray ? ( $file, \@stat ) : $file;
}
1;
} # --- END Cpanel/ConfigFiles.pm
{ # --- BEGIN Cpanel/Bits.pm
package Cpanel::Bits;
my $bits;
sub setbits {
if ( !$bits ) { $bits = shift; }
}
sub getbits { $bits; }
1;
} # --- END Cpanel/Bits.pm
{ # --- BEGIN Cpanel/Config/LoadUserDomains.pm
package Cpanel::Config::LoadUserDomains;
use strict;
# use Cpanel::ConfigFiles ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Bits ();
sub loaduserdomains {
my $conf_ref = shift;
my $reverse = shift;
my $usearr = shift;
$conf_ref = Cpanel::Config::LoadConfig::loadConfig(
_userdomains(),
$conf_ref,
'\s*[:]\s*',
undef, 0, 0,
{
'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 = shift;
my $reverse = shift;
my $ignore_limit = shift;
$conf_ref = Cpanel::Config::LoadConfig::loadConfig(
( $reverse ? _domainusers() : _trueuserdomains() ),
$conf_ref,
'\s*[:]\s*',
undef, 0, 0,
{
'use_reverse' => 0,
'limit' => ( $ignore_limit ? 0 : Cpanel::Bits::getbits() )
}
);
if ( !defined($conf_ref) ) {
$conf_ref = {};
}
return wantarray ? %{$conf_ref} : $conf_ref;
}
sub counttrueuserdomains {
my $num_ud = 0;
if ( open( my $ud_fh, '<', _trueuserdomains() ) ) {
my $buffer;
while ( read( $ud_fh, $buffer, 65535 ) ) {
$num_ud += ( $buffer =~ tr/\n// );
}
close($ud_fh);
}
return $num_ud;
}
sub _userdomains {
$Cpanel::ConfigFiles::USERDOMAINS_FILE;
}
sub _domainusers {
$Cpanel::ConfigFiles::DOMAINUSERS_FILE;
}
sub _trueuserdomains {
$Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE;
}
1;
} # --- END Cpanel/Config/LoadUserDomains.pm
{ # --- BEGIN Cpanel/AcctUtils/DomainOwnerCache.pm
package Cpanel::AcctUtils::DomainOwnerCache;
our $CACHE_IS_SET = 0;
our %DOMAINOWNERCACHE;
sub cachedomainowners {
$CACHE_IS_SET = 1;
require Cpanel::Config::LoadUserDomains;
return Cpanel::Config::LoadUserDomains::loaduserdomains( \%DOMAINOWNERCACHE, 1 );
}
sub clearcache {
%DOMAINOWNERCACHE = ();
$CACHE_IS_SET = 0;
return 1;
}
*uncachedomainowners = \&clearcache;
1;
} # --- END Cpanel/AcctUtils/DomainOwnerCache.pm
{ # --- BEGIN Cpanel/IO.pm
package Cpanel::IO;
use strict;
sub read_bytes_to_end_of_line { ##no critic qw(RequireArgUnpacking)
my $buffer;
if ( read( $_[0], $buffer, $_[1] || 32768 ) ) {
my $next = readline( $_[0] );
$next = '' unless defined $next;
return $buffer . $next;
}
return undef;
}
1;
} # --- END Cpanel/IO.pm
{ # --- BEGIN Cpanel/FileLookup.pm
package Cpanel::FileLookup;
use strict;
# use Cpanel::IO ();
our ( %REVERSE_FILELOOKUPCACHE, %FILELOOKUPCACHE );
sub _filelookup {
my $file = shift;
if ( open my $file_fh, '<', $file ) {
my %OPTS = @_;
my $line;
if ( $OPTS{'initcache'} ) {
local $/;
delete @REVERSE_FILELOOKUPCACHE{ keys %REVERSE_FILELOOKUPCACHE };
delete @FILELOOKUPCACHE{ keys %FILELOOKUPCACHE };
foreach my $line ( split( /\n/, readline($file_fh) ) ) {
next if ( $line =~ m/^\s*#/ );
$line =~ s/[\r\n]//g;
my ( $key, $val ) = split( /:/, $line, 2 );
$val =~ s/\s+#.*$//g; # handle end of line comments
$key =~ s/^\s+//;
$key =~ s/\s+$//;
$val =~ s/^\s+//;
$val =~ s/\s+$//;
$key = lc $key;
$key =~ s/^www\.//;
$FILELOOKUPCACHE{$file}{$key} = $val;
if ( !$OPTS{'noreversecache'} ) {
$REVERSE_FILELOOKUPCACHE{$file}{ ( defined $val ? $val : q{} ) } = $key;
}
if ( !$OPTS{'nowwwcache'} ) {
$FILELOOKUPCACHE{$file}{ 'www.' . $key } = $val;
}
}
}
else {
my $key = $OPTS{'key'};
($key) = $key =~ /(.*)/; #untaint
$key =~ s/^www\.//;
my $field = 0; # fileloop currently always looks for the first key
my $match = qr/\n(?:[^:]+:){$field}(?:www\.)?\Q$key\E(?=[:\n]+)[^\n]*/s;
my $capture_match = qr/\n((?:[^:]+:){$field}(?:www\.)?\Q$key\E(?=[:\n]+)[^\n]*)/s;
my $block;
while ( !eof($file_fh) ) {
last if ( !defined( $block = Cpanel::IO::read_bytes_to_end_of_line( $file_fh, 65535 ) ) );
$block = "\n" . $block; # need a \n for our regex to match -- we use /s since is much faster then /m
if ( $block =~ $match && $block =~ $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+$//;
close $file_fh;
return $val;
}
}
}
close $file_fh;
}
return;
}
sub clearcache {
%REVERSE_FILELOOKUPCACHE = %FILELOOKUPCACHE = ();
}
1;
} # --- END Cpanel/FileLookup.pm
{ # --- BEGIN Cpanel/AcctUtils/DomainOwner/Tiny.pm
package Cpanel::AcctUtils::DomainOwner::Tiny;
use strict;
# use Cpanel::AcctUtils::DomainOwnerCache ();
# use Cpanel::ConfigFiles ();
# use Cpanel::FileLookup ();
sub getdomainowner {
my ( $domain, $opref ) = @_;
my $owner = _getdomainowner( $domain, $opref );
if ( $owner eq 'root' ) {
$owner = $opref->{'default'} if exists $opref->{'default'};
}
return $owner;
}
sub _getdomainowner {
my ( $domain, $opref ) = @_;
if ( $opref->{'cacheonly'} ) {
die "Cache has not been initialized!"
unless ( $Cpanel::AcctUtils::DomainOwnerCache::CACHE_IS_SET
|| exists $Cpanel::FileLookup::FILELOOKUPCACHE{$Cpanel::ConfigFiles::USERDOMAINS_FILE} );
}
die "Invalid domain “$domain”" if $domain =~ tr{/}{};
return 'root' if !length $domain;
if ( exists $Cpanel::AcctUtils::DomainOwnerCache::DOMAINOWNERCACHE{$domain} ) {
return $Cpanel::AcctUtils::DomainOwnerCache::DOMAINOWNERCACHE{$domain};
}
elsif ( $Cpanel::FileLookup::FILELOOKUPCACHE{$Cpanel::ConfigFiles::USERDOMAINS_FILE}{$domain} ) {
return $Cpanel::FileLookup::FILELOOKUPCACHE{$Cpanel::ConfigFiles::USERDOMAINS_FILE}{$domain};
}
if ( !$opref->{'cacheonly'} ) {
if ( $domain !~ tr{*}{} ) {
if ( my $uid = ( stat("$Cpanel::ConfigFiles::VALIASES_DIR/$domain") )[4] ) {
local $@;
eval 'require Cpanel::Config::LoadCpUserFile; require Cpanel::PwCache;'; ## no critic qw(ProhibitStringyEval) -- quoted eval to hide this from perlcc
if ( !$@ ) {
my $valias_user = ( 'Cpanel::PwCache'->can('getpwuid')->($uid) )[0];
if ( 'Cpanel::Config::LoadCpUserFile'->can('has_cpuser_file')->($valias_user) ) {
$Cpanel::FileLookup::FILELOOKUPCACHE{$Cpanel::ConfigFiles::USERDOMAINS_FILE}{$domain} = $valias_user;
return $valias_user;
}
}
}
}
my $name;
if ( !$opref->{'skiptruelookup'} ) {
$name = Cpanel::FileLookup::_filelookup( $Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE, 'key' => $domain );
}
if ( !$name ) {
$name = Cpanel::FileLookup::_filelookup( $Cpanel::ConfigFiles::USERDOMAINS_FILE, 'key' => $domain, 'noreversecache' => 1 );
}
return $name if $name;
}
if ( $> != 0 ) {
local $@;
eval 'require Cpanel::Config::LoadCpUserFile; require Cpanel::PwCache;'; ## no critic qw(ProhibitStringyEval) -- quoted eval to hide this from perlcc
if ( !$@ ) {
my $current_user = ( Cpanel::PwCache::getpwuid($>) )[0];
my $cpuser_ref = Cpanel::Config::LoadCpUserFile::loadcpuserfile($current_user);
if ( $cpuser_ref && ( $cpuser_ref->{'DOMAIN'} eq $domain || grep { $_ eq $domain } @{ $cpuser_ref->{'DOMAINS'} } ) ) {
return $current_user;
}
}
else {
die "Failed to load Cpanel::Config::LoadCpUserFile or Cpanel::PwCache: $@";
}
}
return 'root';
}
1;
} # --- END Cpanel/AcctUtils/DomainOwner/Tiny.pm
{ # --- BEGIN Cpanel/Reseller.pm
package Cpanel::Reseller;
use strict;
use Try::Tiny;
# use Cpanel::Autodie ();
# 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} );
if ( exists $RESELLER_PRIV_CACHE{$user} || exists $RESELLER_EXISTS_CACHE{$user} ) {
return ( ( $RESELLER_EXISTS_CACHE{$user} || scalar keys %{ $RESELLER_PRIV_CACHE{$user} } ) ? 1 : 0 );
}
_load_one_reseller($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;
}
my @limits = qw/demo disallow-shell/;
if ( exists $RESELLER_EXISTS_CACHE{$reseller} && !$RESELLER_EXISTS_CACHE{$reseller} ) {
return 0;
}
if ( exists $RESELLER_PRIV_CACHE{$reseller} && ref $RESELLER_PRIV_CACHE{$reseller} ) {
return ( ( grep { $priv eq $_ } @limits ) ? 0 : 1 ) if exists $RESELLER_PRIV_CACHE{$reseller}->{'all'};
return ( exists $RESELLER_PRIV_CACHE{$reseller}->{$priv} ? 1 : 0 );
}
_load_one_reseller($reseller);
if ( exists $RESELLER_PRIV_CACHE{$reseller} && ref $RESELLER_PRIV_CACHE{$reseller} ) {
return ( ( grep { $priv eq $_ } @limits ) ? 0 : 1 ) if exists $RESELLER_PRIV_CACHE{$reseller}->{'all'};
return ( exists $RESELLER_PRIV_CACHE{$reseller}->{$priv} ? 1 : 0 );
}
}
sub _load_one_reseller {
my ( $reseller, $quotedreseller, $line ) = ( $_[0], $_[0] . ':' );
my $res_fh;
try {
Cpanel::Autodie::open( $res_fh, '<', $Cpanel::ConfigFiles::RESELLERS_FILE );
}
catch {
Cpanel::Logger->new()->warn( $_->to_string() );
};
if ( fileno $res_fh ) {
while ( $line = readline $res_fh ) {
if ( index( $line, $quotedreseller ) == 0 ) { # $line =~ /^$quotedreseller/ ) {
close $res_fh;
chomp $line;
$RESELLER_PRIV_CACHE{$reseller} = { map { $_ => 1 } split( /\s*\,\s*/, ( split( /\s*:\s*/, $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;
}
delete @RESELLER_PRIV_CACHE{ keys %RESELLER_PRIV_CACHE };
if ( open my $resellers_fh, '<', $Cpanel::ConfigFiles::RESELLERS_FILE ) {
local $/;
foreach my $line ( split( m{\n}, readline($resellers_fh) ) ) {
my ( $reseller, $acl ) = split m{ \s* [:] \s* }xms, $line, 2;
next if ( !defined $reseller || $reseller eq '' || $reseller =~ /^\s*#/ || !defined $acl );
$RESELLER_PRIV_CACHE{$reseller} = { map { $_ => 1 } split m{ \s* [,] \s* }xms, $acl };
}
close $resellers_fh;
$reseller_cache_fully_loaded = 1;
}
else {
warn "Unable to open $Cpanel::ConfigFiles::RESELLERS_FILE: $!";
}
$RESELLER_EXISTS_CACHE{$_} = 1 for 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/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/JSON/FailOK.pm
package Cpanel::JSON::FailOK;
use strict;
# use Cpanel::LoadModule ();
my $LoadFile_code;
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
Cpanel::LoadModule::load_perl_module('Cpanel::JSON');
1;
};
if ( !$load_ok && !$ENV{'CPANEL_BASE_INSTALL'} && $^X =~ m{^/usr/local/cpanel} ) {
warn $@;
}
return $load_ok ? 1 : 0;
}
sub LoadFile {
my ( $file_or_fh, $path ) = @_;
return undef if !$INC{'Cpanel/JSON.pm'} || !$INC{'JSON/XS.pm'}; # Cpanel::JSON can be loaded without JSON::XS in updatenow.static so we must check both
my $ref;
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
$LoadFile_code ||= 'Cpanel::JSON'->can('LoadFile');
$ref = $LoadFile_code->( $file_or_fh, $path ); # Cpanel::JSON must be quoted to avoid bringing it in with the compiler
};
return $ref;
}
1;
} # --- END Cpanel/JSON/FailOK.pm
{ # --- BEGIN Cpanel/Config/Constants.pm
package Cpanel::Config::Constants;
our $DEFAULT_CPANEL_THEME = 'paper_lantern';
our $DEFAULT_CPANEL_MAILONLY_THEME = 'paper_lantern';
our $DEFAULT_WEBMAIL_THEME = 'paper_lantern';
our $DEFAULT_WEBMAIL_MAILONLY_THEME = 'paper_lantern';
our @DORMANT_SERVICES_LIST = qw(cpdavd cphulkd cpsrvd dnsadmin spamd);
1;
} # --- END Cpanel/Config/Constants.pm
{ # --- BEGIN Cpanel/Config/LoadCpUserFile.pm
package Cpanel::Config::LoadCpUserFile;
use strict;
use Try::Tiny;
# use Cpanel::DB::Utils ();
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
# use Cpanel::SafeFile (); #checked for bloat 7/11/10 - jnk
use IO::Handle ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::JSON::FailOK ();
# use Cpanel::Config::Constants ();
# use Cpanel::ConfigFiles ();
$Cpanel::Config::LoadCpUserFile::VERSION = '0.4'; # DO NOT CHANGE THIS FROM A DECIMAL
my %cpuser_defaults = (
'BWLIMIT' => 'unlimited',
'DEADDOMAINS' => undef,
'DEMO' => 0,
'DOMAIN' => '',
'DOMAINS' => undef,
'FEATURELIST' => 'default',
'HASCGI' => 0,
'HASDKIM' => 0,
'HASSPF' => 0,
'IP' => '127.0.0.1',
'MAXADDON' => 0,
'MAXFTP' => 'unlimited',
'MAXLST' => 'unlimited',
'MAXPARK' => 0,
'MAXPOP' => 'unlimited',
'MAXSQL' => 'unlimited',
'MAXSUB' => 'unlimited',
'OWNER' => 'root',
'PLAN' => 'undefined',
'RS' => '',
'STARTDATE' => '0000000000',
);
sub _cpuser_defaults {
return %cpuser_defaults;
}
my %should_never_be_on_disk = map { $_ => undef } qw(
DBOWNER
DOMAIN
DOMAINS
DEADDOMAINS
HOMEDIRLINKS
);
my $logger;
sub load_or_die {
my ($user) = @_;
my ( undef, undef, $cpuser ) = _load( $user, undef, if_missing => 'die' );
return $cpuser;
}
sub load_file {
my ($file) = @_;
my ( $lock_obj, $cpuser_fh ) = _open_cpuser_file( '<', $file );
my $cpuser_hr = _parse_cpuser_file($cpuser_fh);
local $!;
Cpanel::SafeFile::safeclose( $cpuser_fh, $lock_obj ) or do {
_logger()->warn("Failed to safeclose($file): $!");
};
return $cpuser_hr;
}
sub _open_cpuser_file {
my ( $mode, $file ) = @_;
local $!;
my $cpuser_fh = IO::Handle->new();
my $open_result = Cpanel::SafeFile::safeopen( $cpuser_fh, $mode, $file ) or do {
die Cpanel::Exception::create( 'IO::FileOpenError', { path => $file, error => $!, mode => $mode } );
};
return ( $open_result, $cpuser_fh );
}
sub _parse_cpuser_file {
my ($cpuser_fh) = @_;
my %cpuser = %cpuser_defaults;
my %DOMAIN_MAP;
my %DEAD_DOMAIN_MAP;
my %HOMEDIRLINKS_MAP;
local $!;
while (<$cpuser_fh>) {
next if m/^\s*#/;
chomp;
my ( $key, $value ) = split( /\s*=/, $_, 2 );
next if !defined $value || exists $should_never_be_on_disk{$key};
if ( $key eq 'DNS' ) {
$cpuser{'DOMAIN'} = lc $value;
}
elsif ( $key =~ m{ \A DNS \d+ \z }xms ) {
my $domain = lc $value;
if ( !exists $DOMAIN_MAP{$domain} && $domain ne $cpuser{'DOMAIN'} ) {
$DOMAIN_MAP{$domain} = undef;
}
}
elsif ( $key =~ m{ \A XDNS \d+ \z }xms ) {
my $domain = lc $value;
if ( !exists $DEAD_DOMAIN_MAP{$domain} && !exists $DOMAIN_MAP{$domain} && $domain ne $cpuser{'DOMAIN'} ) {
$DEAD_DOMAIN_MAP{$domain} = undef;
}
}
elsif ( $key =~ m{ \A HOMEDIRPATHS \d* \z }xms ) {
$HOMEDIRLINKS_MAP{$value} = undef;
}
else {
$cpuser{$key} = $value;
}
}
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'} ) {
Cpanel::LoadModule::load_perl_module('Cpanel::Conf');
my $cp_defaults = Cpanel::Conf->new();
$cpuser{'RS'} = $cp_defaults->cpanel_theme;
}
if ( !length $cpuser{'LOCALE'} ) {
if ( length $cpuser{'LANG'} ) {
Cpanel::LoadModule::load_perl_module('Cpanel::Locale::Utils::Legacy');
$cpuser{'LOCALE'} = Cpanel::Locale::Utils::Legacy::map_any_old_style_to_new_style( $cpuser{'LANG'} );
}
else {
try {
Cpanel::LoadModule::load_perl_module('Cpanel::Locale');
$cpuser{'LOCALE'} = Cpanel::Locale::get_server_locale();
}
catch {
_logger()->warn("Error loading Cpanel::Locale: $_");
};
$cpuser{'LOCALE'} ||= 'en';
if ( $cpuser{'LOCALE'} eq 'en' ) {
$cpuser{'LANG'} = 'english-utf8';
}
else {
Cpanel::LoadModule::load_perl_module('Cpanel::Locale::Utils::Legacy');
$cpuser{'LANG'} = Cpanel::Locale::Utils::Legacy::get_best_guess_of_legacy_from_locale( $cpuser{'LOCALE'}, 1 );
}
}
}
$cpuser{'DOMAINS'} = [ sort keys %DOMAIN_MAP ]; # Sorted here so they can be tested with Test::More::is_deeply
$cpuser{'DEADDOMAINS'} = [ sort keys %DEAD_DOMAIN_MAP ]; # Sorted here so they can be tested with Test::More::is_deeply
$cpuser{'HOMEDIRLINKS'} = [ sort keys %HOMEDIRLINKS_MAP ];
return \%cpuser;
}
sub _logger {
return $logger ||= do {
Cpanel::LoadModule::load_perl_module('Cpanel::Logger');
Cpanel::Logger->new();
};
}
sub load {
my ( $user, $opts ) = @_;
my ( undef, undef, $cpuser ) = _load( $user, $opts );
if ( !ref $cpuser ) {
_logger()->warn( "Failed to load cPanel user file for '" . ( $user || '' ) . "'" ) unless $opts->{'quiet'};
return wantarray ? () : {};
}
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 has_cpuser_file {
my ($user) = @_;
return unless defined $user and $user ne '' and $user !~ tr/\/\0//;
return -e "$Cpanel::ConfigFiles::cpanel_users/$user" && -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 _;
}
sub _load {
my ( $user, $load_opts_ref, %internal_opts ) = @_;
if ( !$user || $user =~ tr/\/\0// ) { #no eq '' needed as !$user covers this
_logger()->warn("Invalid username to loadcpuserfile.");
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 ( !defined $size && ( $internal_opts{'if_missing'} || q<> ) eq 'die' ) {
if ( $!{'ENOENT'} ) {
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( $mode, $user_file );
}
catch {
_logger()->warn($_);
};
return if !$lock_fh;
}
elsif ( !$size ) {
if ( $user eq 'cpanel' ) {
my $result = load_cpanel_user();
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 ) {
_logger()->debug("load cPanel user file [$user]");
}
if ($has_serializer) {
if ( open( my $cache_fh, '<', $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::JSON::FailOK::LoadFile($cache_fh);
close($cache_fh);
if ( $cpuser_ref && ref $cpuser_ref eq 'HASH' && keys %{$cpuser_ref} ) {
if ( $Cpanel::Debug::level && $Cpanel::Debug::level > 3 ) {
_logger()->debug("load cache hit user[$user] now[$now] mtime[$mtime] cache_mtime[$cache_mtime]");
}
$cpuser_ref->{'MTIME'} = $mtime;
if ( exists $cpuser_ref->{'__CACHE_DATA_VERSION'} && $cpuser_ref->{'__CACHE_DATA_VERSION'} == $Cpanel::Config::LoadCpUserFile::VERSION ) {
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 ) {
_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 ) {
_logger()->debug("load cache miss user[$user] now[$now] mtime[$mtime] cache_mtime[0]");
}
}
}
if ( !$lock_fh ) {
try {
( $lock_fh, $cpuser_fh ) = _open_cpuser_file( '<', $user_file );
}
catch {
_logger()->warn($_);
};
return if !$lock_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'} = $Cpanel::Config::LoadCpUserFile::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 {
Cpanel::SafeFile::safeclose( $cpuser_fh, $lock_fh );
$cpuser_fh = $lock_fh = undef;
}
return ( $cpuser_fh, $lock_fh, $cpuser_hr );
}
sub loadcpuserfile {
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;
}
}
1;
} # --- END Cpanel/Config/LoadCpUserFile.pm
{ # --- BEGIN Cpanel/Hulk/Constants.pm
package Cpanel::Hulk::Constants;
use strict;
# use Cpanel::Fcntl::Constants ();
*F_GETFL = \$Cpanel::Fcntl::Constants::F_GETFL;
*F_SETFL = \$Cpanel::Fcntl::Constants::F_SETFL;
*O_NONBLOCK = \$Cpanel::Fcntl::Constants::O_NONBLOCK;
our $EINTR = 4;
our $EPIPE = 32;
our $EINPROGRESS = 115;
our $ETIMEDOUT = 110;
our $EISCONN = 106;
our $ECONNRESET = 104;
our $EAGAIN = 11;
our $AF_INET = 2;
our $AF_UNIX = 1;
our $PROTO_IP = 0;
our $PROTO_ICMP = 1;
our $PROTO_TCP = 6;
our $SO_PEERCRED = 17;
our $SOL_SOCKET = 1;
our $SOCK_STREAM = 1;
our $TOKEN_SALT_BASE = '$6$';
our $SALT_LENGTH = 16;
our $TIME_BASE = 1410000000;
our $SIX_HOURS_IN_SECONDS = 21600;
1;
} # --- END Cpanel/Hulk/Constants.pm
{ # --- BEGIN Cpanel/Socket/Constants.pm
package Cpanel::Socket::Constants;
use strict;
our $AF_UNIX = 1;
our $AF_INET = 2;
our $AF_INET6 = 10;
1;
} # --- END Cpanel/Socket/Constants.pm
{ # --- BEGIN Cpanel/Socket/UNIX/Micro.pm
package Cpanel::Socket::UNIX::Micro;
use strict;
# use Cpanel::Socket::Constants ();
my $SUN_PATH_SIZE = 2;
my $SUN_FAMILY_SIZE = 108;
sub is_little_endian {
return ( unpack( 'c', pack( 's', 1 ) ) );
}
sub MSG_PEEK {
return 2;
}
sub micro_sockaddr_un {
my $usock = shift;
return pack(
_pack_template_AF_UNIX(),
$Cpanel::Socket::Constants::AF_UNIX,
$usock,
);
}
sub _pack_template_AF_UNIX {
my $sun_path_pack = 'I';
if ( $SUN_PATH_SIZE == 1 ) { $sun_path_pack = 'C' }
elsif ( $SUN_PATH_SIZE == 2 ) { $sun_path_pack = ( is_little_endian() ? 'v' : 'n' ) }
elsif ( $SUN_PATH_SIZE == 4 ) { $sun_path_pack = ( is_little_endian() ? 'V' : 'N' ) }
return qq<
$sun_path_pack
Z$SUN_FAMILY_SIZE
>;
}
sub unpack_sockaddr_un {
my ($sockaddr) = @_;
return ( unpack _pack_template_AF_UNIX(), $sockaddr )[1];
}
1;
} # --- END Cpanel/Socket/UNIX/Micro.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'}, () ) );
}
1;
} # --- END Cpanel/Pack.pm
{ # --- BEGIN Cpanel/NSCD.pm
package Cpanel::NSCD;
use strict;
# use Cpanel::FindBin ();
# use Cpanel::Hulk::Constants ();
# use Cpanel::SafeFile ();
# use Cpanel::Socket::UNIX::Micro ();
# use Cpanel::Pack ();
# use Cpanel::Autodie ();
use Try::Tiny;
our $VERSION = '1.4';
our $NSCD_CONFIG_FILE = '/etc/nscd.conf';
our $NSCD_SOCKET = '/var/run/nscd/socket';
our $CACHE_TTL = 600;
my $last_check_time = 0;
my $nscd_is_running_cache;
my $nscd_binary_missing = 0;
my $nscd_binary;
use constant NSCD_VERSION => 2;
use constant INVALIDATE => 10;
my @ALL_CACHES = ( 'group', 'passwd' );
my @REQUEST_TEMPLATE = (
'version' => 'L', #int32_t version; /* Version number of the daemon interface. */
'type' => 'L', #request_type type; /* Service requested. */
'key_len' => 'L', #int32_t key_len; /* Key length. */
'dbname' => 'Z*',
);
sub clear_cache {
my @CACHES = @_;
if ( !@CACHES ) {
@CACHES = @ALL_CACHES;
}
local $SIG{'PIPE'} = 'IGNORE';
foreach my $cache (@CACHES) {
next if !$cache;
my $socket;
socket( $socket, $Cpanel::Hulk::Constants::AF_UNIX, $Cpanel::Hulk::Constants::SOCK_STREAM, 0 );
my $usock = Cpanel::Socket::UNIX::Micro::micro_sockaddr_un($NSCD_SOCKET);
my $err;
my $pack = Cpanel::Pack->new( \@REQUEST_TEMPLATE );
try {
if ( connect( $socket, $usock ) ) {
my $msg = $pack->pack_from_hashref(
{
'version' => NSCD_VERSION,
'type' => INVALIDATE,
'key_len' => 1 + length $cache, #1 for the null byte
'dbname' => $cache,
}
);
Cpanel::Autodie::syswrite( $socket, $msg );
my $buffer = -1;
Cpanel::Autodie::sysread( $socket, $buffer, 16 );
my $status = unpack( 'L', $buffer );
if ($status) {
die "NSCD invalidate returned non-zero status: [$status]";
}
}
}
catch {
$err = $_;
local $@ = $err;
warn;
};
if ($err) {
my $nscd_binary = _get_nscd_binary_path() or return;
nscd_is_running() or return;
my $err;
try {
Cpanel::LoadModule::load_perl_module('Cpanel::SafeRun::Object');
'Cpanel::SafeRun::Object'->new_or_die(
program => $nscd_binary,
args => [ '--invalidate' => $cache ],
);
}
catch {
$err = $_;
local $@ = $err;
warn;
};
return 0 if $err;
}
}
return 1;
}
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;
socket( $socket, $Cpanel::Hulk::Constants::AF_UNIX, $Cpanel::Hulk::Constants::SOCK_STREAM, 0 );
my $usock = Cpanel::Socket::UNIX::Micro::micro_sockaddr_un($NSCD_SOCKET);
if ( connect( $socket, $usock ) ) {
return ( $nscd_is_running_cache = 1 );
}
return ( $nscd_is_running_cache = 0 );
}
sub _get_nscd_binary_path {
if ( !$nscd_binary ) {
return if $nscd_binary_missing;
$nscd_binary = Cpanel::FindBin::findbin( 'nscd', 'path' => [ '/usr/sbin', '/usr/local/sbin', '/usr/bin', '/usr/local/bin' ] );
if ( !$nscd_binary ) {
$nscd_binary_missing = 1;
return;
}
}
return $nscd_binary;
}
sub enable_logging_to_file {
my ( $logfile, $force ) = @_;
$logfile ||= '/var/log/nscd.log';
my $lock = Cpanel::SafeFile::safeopen( my $fh, '+<', $NSCD_CONFIG_FILE );
return 0 unless $lock;
my @lines = <$fh>;
my $ret = 0;
if ( $force || !grep { /^\s*logfile\s+\S+\b/ } @lines ) {
@lines = grep { !/^\s*(?:logfile|debug-level)\s+/ } @lines;
push @lines, "logfile $logfile\n";
push @lines, "debug-level 1";
seek( $fh, 0, 0 );
print {$fh} @lines;
truncate( $fh, tell($fh) );
$ret = 1;
}
Cpanel::SafeFile::safeclose( $fh, $lock );
return $ret;
}
sub disable_logging {
return enable_logging_to_file( '/dev/null', 1 );
}
1;
} # --- END Cpanel/NSCD.pm
{ # --- BEGIN Cpanel/PwCache.pm
package Cpanel::PwCache;
use strict;
# use Cpanel::SafeFile ();
# use Cpanel::Debug ();
# use Cpanel::IO ();
# use Cpanel::NSCD ();
use IO::Handle ();
# use Cpanel::JSON::FailOK ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
$Cpanel::PwCache::VERSION = '3.4';
my ( $system, $isopen, $pwcacheistied, $pwcache_inited, $MIN_FIELDS_FOR_VALID_ENTRY, $pwcache_has_uid_cache, $pwcache_ref, $getpwent_open_time, $pwdatafuncuid, $pwdatafunc, $pwcachetie, $skip_uid_cache, $getpwent_passwd_fh, @SHAREDPW ) = ( $^O, 0, 0, 0, 6 );
my %HOMEDIR_CACHE;
our $SYSTEM_CONF_DIR = '/etc';
my $PRODUCT_CONF_DIR = '/var/cpanel';
our ( $CASE_SENSITIVE, $CASE_INSENSITIVE ) = ( 0, 1 );
my @PW_ORDER = qw(
name
passwd
uid
gid
quota
comment
gcos
dir
shell
expire
);
my %PW_INDEX = map { $PW_ORDER[$_] => $_ } ( 0 .. $#PW_ORDER );
my $PWCACHE_IS_SAFE = 1;
sub confess { require Carp; return Carp::confess(@_) }
sub cluck { require Carp; return Carp::cluck(@_) }
sub istied { $pwcacheistied }
sub deinit { $pwcacheistied = 0; }
sub no_uid_cache { $skip_uid_cache = 1; }
sub uid_cache { $skip_uid_cache = 0; }
sub pwcheckos { return $system; }
*_getos = *pwcheckos;
sub init { ( $pwcachetie, $skip_uid_cache, $pwcacheistied ) = ( $_[0], $_[1], 1 ); }
sub validate {
my ( $pwkey, $record ) = @_;
if ( exists $record->{'contents'} && ref $record->{'contents'} ne 'ARRAY' && scalar @{ $record->{'contents'} } ) { return 0; }
my ( $stored_mtime, $hstored_mtime ) = ( $record->{'cachetime'}, $record->{'hcachetime'} );
my ( $passwdmtime, $hpasswdmtime ) = ( ( stat("$SYSTEM_CONF_DIR/passwd") )[9], ( -r "$SYSTEM_CONF_DIR/shadow" ? ( stat(_) )[9] : 0 ) );
Cpanel::Debug::log_debug( "called for record " . dump_rec($record) ) if ( $Cpanel::Debug::level > 3 );
if ( $hstored_mtime
&& $stored_mtime
&& $hpasswdmtime == $hstored_mtime
&& $passwdmtime == $stored_mtime ) {
if ( !$pwcache_ref->{$pwkey}->{'cachetime'}
|| $pwcache_ref->{$pwkey}->{'cachetime'} != $stored_mtime
|| $pwcache_ref->{$pwkey}->{'hcachetime'} != $hstored_mtime ) {
@{ $pwcache_ref->{$pwkey} }{ 'hcachetime', 'cachetime', 'contents' } = ( $hstored_mtime, $stored_mtime, $record->{'contents'} );
}
Cpanel::Debug::log_debug( 'returned 1 ' . dump_rec($record) ) if ( $Cpanel::Debug::level > 3 );
return 1;
}
if ( $Cpanel::Debug::level > 3 ) {
Cpanel::Debug::log_debug( "returned 0 " . dump_rec($record) );
Cpanel::Debug::log_debug("0 [ hstored_mtime = $hstored_mtime, hpasswdmtime = $hpasswdmtime ] [ stored_mtime = $stored_mtime, passwdmtime = $stored_mtime ]");
}
return 0;
}
sub load {
my $pwkey = shift;
my ( $field, $value ) = split( /:/, $pwkey, 2 );
my ( $passwdmtime, $hpasswdmtime ) = ( ( stat("$SYSTEM_CONF_DIR/passwd") )[9], ( -r "$SYSTEM_CONF_DIR/shadow" ? ( stat(_) )[9] : 0 ) );
Cpanel::Debug::log_debug("called for pwkey $pwkey") if ( $Cpanel::Debug::level > 3 );
my $pwdata = _getpwdata( $value, $field, $passwdmtime, $hpasswdmtime );
_cache_pwdata($pwdata) if $pwdata && @$pwdata;
return $pwcache_ref->{$pwkey};
}
sub _cache_pwdata {
my ($pwdata) = @_;
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;
}
sub load_cached {
my $pwkey = shift;
if ( exists $pwcache_ref->{$pwkey} ) {
my ( $passwdmtime, $hpasswdmtime ) = ( ( stat("$SYSTEM_CONF_DIR/passwd") )[9], ( -r "$SYSTEM_CONF_DIR/shadow" ? ( stat(_) )[9] : 0 ) );
if ( $pwcache_ref->{$pwkey}->{'hcachetime'} == $hpasswdmtime && $pwcache_ref->{$pwkey}->{'cachetime'} == $passwdmtime ) {
return $pwcache_ref->{$pwkey};
}
else {
delete $pwcache_ref->{$pwkey};
}
}
return;
}
sub pwmksafecache {
return if $PWCACHE_IS_SAFE;
foreach my $pwkey ( keys %{$pwcache_ref} ) {
${ $pwcache_ref->{$pwkey}->{'contents'} }[1] = 'x';
}
$PWCACHE_IS_SAFE = 1;
}
sub getpwent {
my ( $passwdmtime, $shadowmtime, $cryptpw ) = @_;
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::getpwent cannot be run under B::C (see case 162857)");
}
if ( !$isopen ) {
if ($getpwent_passwd_fh) { close($getpwent_passwd_fh); }
$getpwent_passwd_fh = IO::Handle->new();
open( $getpwent_passwd_fh, '<', "$SYSTEM_CONF_DIR/passwd" ) or do {
cluck("Unable to open $SYSTEM_CONF_DIR/passwd: $!");
return;
};
$getpwent_open_time = ( stat("$SYSTEM_CONF_DIR/passwd") )[9];
$shadowmtime = $passwdmtime = $getpwent_open_time;
$isopen = 1;
}
elsif ( !$passwdmtime || !$shadowmtime ) {
$shadowmtime = $passwdmtime = ( $getpwent_open_time ? $getpwent_open_time : ( stat("$SYSTEM_CONF_DIR/passwd") )[9] );
}
while ( my $passwd_line = readline($getpwent_passwd_fh) ) {
chomp $passwd_line;
@SHAREDPW = ( split( /:/, $passwd_line ), undef );
if ( scalar @SHAREDPW > 7 && $SHAREDPW[0] =~ m/^[A-Za-z0-9_]/ ) { # Check for valid lines and skip commented/invalid lines
return wantarray ? ( $SHAREDPW[0], ( $cryptpw ? $cryptpw : $SHAREDPW[1] ), $SHAREDPW[2], $SHAREDPW[3], '', '', $SHAREDPW[4], $SHAREDPW[5], $SHAREDPW[6], -1, -1, $passwdmtime, $shadowmtime ) : $SHAREDPW[0];
}
}
return;
}
sub getpwuid {
if ( defined $_[0] && !exists $pwcache_ref->{"2:$_[0]"} && $> != 0 && !$pwcacheistied && Cpanel::NSCD::nscd_is_running() ) {
return CORE::getpwuid( $_[0] ) if !wantarray;
my @ret = CORE::getpwuid( $_[0] );
return ( @ret, -1, -1, 0, 0 ) if @ret;
return;
}
if ( my $pwref = Cpanel::PwCache::_pwfunc( $_[0], 2 ) ) {
return wantarray ? @$pwref : $pwref->[0];
}
return; #important not to return 0
}
sub getpwnam {
if ( defined $_[0] && !exists $pwcache_ref->{"0:$_[0]"} && $> != 0 && !$pwcacheistied && Cpanel::NSCD::nscd_is_running() ) {
return CORE::getpwnam( $_[0] ) if !wantarray;
my @ret = CORE::getpwnam( $_[0] );
return ( @ret, -1, -1, 0, 0 ) if @ret;
return;
}
if ( my $pwref = Cpanel::PwCache::_pwfunc( $_[0], 0 ) ) {
return wantarray ? @$pwref : $pwref->[2];
}
return; #important not to return 0
}
*pwclearcache = \&clear_this_process_cache;
sub clear_this_process_cache {
$pwcache_inited = undef;
$pwcache_has_uid_cache = undef;
$pwcache_ref = {};
%HOMEDIR_CACHE = ();
}
sub clear_global_cache {
clear_this_process_cache();
Cpanel::NSCD::clear_cache();
}
sub setpwent {
if ($getpwent_passwd_fh) {
seek( $getpwent_passwd_fh, 0, 0 ) or return undef;
if ( eof $getpwent_passwd_fh ) {
$isopen = 0;
close $getpwent_passwd_fh or return undef;
undef $getpwent_passwd_fh;
}
}
return 1;
}
sub endpwent {
if ($getpwent_passwd_fh) {
close $getpwent_passwd_fh or return undef;
undef $getpwent_passwd_fh;
}
$isopen = 0;
return 1;
}
sub _readshadow {
my ( $value, $field, $passwdmtime, $shadowmtime ) = ( $_[0], ( $_[1] || 0 ), ( $_[2] || ( stat("$SYSTEM_CONF_DIR/passwd") )[9] ), ( $_[3] || ( stat("$SYSTEM_CONF_DIR/shadow") )[9] ) );
my @PW = Cpanel::PwCache::_readpasswd( $value, $field, $passwdmtime, $shadowmtime );
return if !@PW;
$value = $PW[0];
if ( open my $shadow_fh, '<', "$SYSTEM_CONF_DIR/shadow" ) {
if ( my @SH = _find_field_with_value_in_pw_file( $shadow_fh, 0, $value, 0 ) ) {
( $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;
$PWCACHE_IS_SAFE = 0;
return @PW;
}
}
else {
cluck("Unable to open $SYSTEM_CONF_DIR/shadow: $!");
}
cluck("Entry for $value missing in $SYSTEM_CONF_DIR/shadow");
return @PW;
}
sub _readpasswd {
my ( $value, $field, $passwdmtime, $shadowmtime, $block ) = ( $_[0], ( $_[1] || 0 ), ( $_[2] || ( stat("$SYSTEM_CONF_DIR/passwd") )[9] ), $_[3] );
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::_readpasswd cannot be run under B::C (see case 162857)");
}
if ( open( my $passwd_fh, '<', "$SYSTEM_CONF_DIR/passwd" ) ) {
if ( my @PW = _find_field_with_value_in_pw_file( $passwd_fh, $field, $value, 0 ) ) {
return ( $PW[0], $PW[1], $PW[2], $PW[3], '', '', $PW[4], $PW[5], $PW[6], -1, -1, $passwdmtime, ( $shadowmtime || $passwdmtime ) );
}
close($passwd_fh);
}
return;
}
sub _readmasterpasswd {
my ( $value, $field, $passwdmtime, $shadowmtime, @PW ) = ( $_[0], ( $_[1] || 0 ), ( $_[2] || ( stat("$SYSTEM_CONF_DIR/passwd") )[9] ), ( $_[3] || ( stat("$SYSTEM_CONF_DIR/master.passwd") )[9] ) );
if ( open my $master_fh, '<', "$SYSTEM_CONF_DIR/master.passwd" ) {
while ( my $line = <$master_fh> ) {
chomp $line;
my @PW = split( /:/, $line );
if ( @PW && defined( $PW[$field] ) && $PW[$field] eq $value ) {
close $master_fh;
$PWCACHE_IS_SAFE = 0;
return ( $PW[0], $PW[1], $PW[2], $PW[3], $PW[5], $PW[4], $PW[7], $PW[8], $PW[9], $PW[6], $PW[5], $passwdmtime, $shadowmtime );
}
}
close $master_fh;
}
else {
cluck("Unable to open $SYSTEM_CONF_DIR/master.passwd: $!");
}
return;
}
sub _pwfunc {
my ( $value, $field, $useipc, $pwkey ) = ( $_[0], ( $_[1] || 0 ), $_[2], $_[1] . ':' . ( $_[0] || 0 ) );
return if ( !defined $value || $value =~ tr/\0// || $pwkey =~ tr/\0// );
if ($pwcacheistied) {
Cpanel::Debug::log_debug("cache tie (tied) value[$value] field[$field]") if ( $Cpanel::Debug::level > 3 );
return ref $pwcachetie eq 'HASH' && ref $pwcachetie->{$pwkey} eq 'HASH' ? $pwcachetie->{$pwkey}->{'contents'} : undef;
}
my ( $passwdmtime, $hpasswdmtime ) = ( ( stat("$SYSTEM_CONF_DIR/passwd") )[9], ( -r "$SYSTEM_CONF_DIR/shadow" ? ( stat(_) )[9] : 0 ) );
if ( exists $pwcache_ref->{$pwkey} ) {
Cpanel::Debug::log_debug("exists in cache value[$value] field[$field]") if ( $Cpanel::Debug::level > 3 );
if ( $hpasswdmtime && ( $hpasswdmtime != $pwcache_ref->{$pwkey}->{'hcachetime'} )
|| ( $passwdmtime && $passwdmtime != $pwcache_ref->{$pwkey}->{'cachetime'} ) ) { #timewarp safe
$Cpanel::Debug::level > 3 && Cpanel::Debug::log_debug( "cache miss value[$value] field[$field] pwkey[$pwkey] " . qq{hpasswdmtime: $hpasswdmtime != $pwcache_ref->{$pwkey}->{hcachetime} } . qq{passwdmtime: $passwdmtime != $pwcache_ref->{$pwkey}->{cachetime} } );
if ( defined $pwcache_ref->{$pwkey} && defined $pwcache_ref->{$pwkey}->{'contents'} ) {
delete @$pwcache_ref{ keys %$pwcache_ref }; #nuke it as its no longer valid
}
}
elsif ( exists( $pwcache_ref->{$pwkey}->{'contents'} ) ) {
Cpanel::Debug::log_debug("cache hit value[$value] field[$field]") if ( $Cpanel::Debug::level > 3 );
return $pwcache_ref->{$pwkey}->{'contents'};
}
}
$Cpanel::Debug::level > 3 && Cpanel::Debug::log_debug("cache miss pwkey[$pwkey] value[$value] field[$field] passwdmtime[$passwdmtime] pwcacheistied[$pwcacheistied] hpasswdmtime[$hpasswdmtime]");
my $pwdata = _getpwdata( $value, $field, $passwdmtime, $hpasswdmtime );
_cache_pwdata($pwdata) if $pwdata && @$pwdata;
return $pwdata;
}
sub init_pwcache {
$PWCACHE_IS_SAFE = 0;
return _build_pwcache();
}
sub init_passwdless_pwcache {
return _build_pwcache( 'nopasswd' => 1 );
}
sub fetch_pwcache {
init_passwdless_pwcache() if !$pwcache_inited;
return [ map { $pwcache_ref->{$_}->{'contents'} } grep { substr( $_, 0, 1 ) eq '0' } keys %{$pwcache_ref} ];
}
sub _build_pwcache {
my %OPTS = @_;
my ( $cache_file, $passwdmtime, $cache_file_mtime, $epasswd_ref, $epasswd_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" . ( $skip_uid_cache ? '.nouids' : '' ) . '.cache';
}
elsif ( -r "$SYSTEM_CONF_DIR/shadow" ) {
$PWCACHE_IS_SAFE = 0;
$hpasswdmtime = ( stat(_) )[9];
$epasswd_file = "$SYSTEM_CONF_DIR/shadow";
$cache_file = "$SYSTEM_CONF_DIR/shadow" . ( $skip_uid_cache ? '.nouids' : '' ) . '.cache';
}
else {
$hpasswdmtime = 0;
}
if ( !$pwcacheistied && exists $INC{'Cpanel/JSON.pm'} ) {
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::_build_pwcache cannot be run under B::C (see case 162857)");
}
$cache_file_mtime = ( stat($cache_file) )[9] || 0;
if ( $cache_file_mtime > $hpasswdmtime && $cache_file_mtime > $passwdmtime ) {
if ( open( my $cache_fh, '<', $cache_file ) ) {
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
&& ( scalar keys %{$cache_ref} ) > 0
&& $cache_ref->{'0:root'}->{'hcachetime'} == $hpasswdmtime
&& $cache_ref->{'0:root'}->{'cachetime'} == $passwdmtime ) {
Cpanel::Debug::log_debug("[validated pwcache from $cache_file]") if ( $Cpanel::Debug::level > 3 );
my $num_keys = scalar keys %{$pwcache_ref};
if ($num_keys) {
if ( $num_keys > 10 ) {
%{$pwcache_ref} = ( %{$pwcache_ref}, %{$cache_ref} );
}
else {
my $original_pwcache_ref = $pwcache_ref;
$pwcache_ref = $cache_ref;
foreach my $key ( keys %{$original_pwcache_ref} ) {
$pwcache_ref->{$key} = $original_pwcache_ref->{$key};
}
}
}
else {
$pwcache_ref = $cache_ref;
}
$pwcache_inited = ( $OPTS{'nopasswd'} ? 1 : 2 );
return;
}
}
}
}
if ($epasswd_file) { $epasswd_ref = _load_pws($epasswd_file); }
$pwcache_inited = ( $OPTS{'nopasswd'} ? 1 : 2 );
$pwcache_has_uid_cache = ( $skip_uid_cache ? 0 : 1 );
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::_build_pwcache cannot be run under B::C (see case 162857)");
}
local $!;
if ( open( my $pwcache_passwd_fh, '<', "$SYSTEM_CONF_DIR/passwd" ) ) {
local $/;
$pwcache_ref = {};
foreach my $line ( split( /\n/, readline($pwcache_passwd_fh) ) ) {
my @fields = split( /:/, $line );
next unless scalar @fields >= $MIN_FIELDS_FOR_VALID_ENTRY && $fields[0] =~ m/^[A-Za-z0-9_]/;
my $data = {
'cachetime' => $passwdmtime,
'hcachetime' => $hpasswdmtime,
'contents' => [ $fields[0], ( exists $epasswd_ref->{ $fields[0] } ? $epasswd_ref->{ $fields[0] } : $fields[1] ), $fields[2], $fields[3], '', '', $fields[4], $fields[5], $fields[6], -1, -1, $passwdmtime, $hpasswdmtime ]
};
$pwcache_ref->{ '0:' . $fields[0] } = $data;
next if $skip_uid_cache || !defined $fields[2] || exists $pwcache_ref->{ '2:' . $fields[2] };
$pwcache_ref->{ '2:' . $fields[2] } = $data;
}
close($pwcache_passwd_fh);
}
else {
die "The system failed to read $SYSTEM_CONF_DIR/passwd because of an error: $!";
}
if ( !$pwcacheistied && exists $INC{'Cpanel/JSON.pm'} && ref $pwcache_ref ) {
Cpanel::FileUtils::Write::JSON::Lazy::write_file( $cache_file, $pwcache_ref, 0600 );
}
return 1;
}
sub pwcache_is_initted {
return ( $pwcache_inited ? $pwcache_inited : 0 );
}
sub _getpwdata {
my ( $value, $field, $passwdmtime, $shadowmtime ) = @_;
return if ( !defined $value || !defined $field || $value =~ tr/\0// );
my $myuid = $>;
Cpanel::Debug::log_debug("called for myuid[$myuid] value[$value] field[$field]") if ( $Cpanel::Debug::level > 3 );
if ( !$pwdatafunc || $myuid != $pwdatafuncuid ) {
$pwdatafuncuid = $myuid;
$pwdatafunc = ( -r "$SYSTEM_CONF_DIR/shadow" ? \&_readshadow : \&_readpasswd );
}
return [ $pwdatafunc->( $value, $field, $passwdmtime, $shadowmtime ) ];
}
sub _load_pws {
my $lookup_file = shift;
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::_load_pws cannot be run under B::C (see case 162857)");
}
my %PW;
if ( open my $lookup_fh, '<', $lookup_file ) {
local $/;
%PW = map { ( split( /:/, $_ ) )[ 0, 1 ] } split( /\n/, readline($lookup_fh) );
delete @PW{ '', grep( m/^#/, keys %PW ) };
close $lookup_fh;
}
return \%PW;
}
{
no warnings 'once';
*get_line_from_pwfile = \&_get_line_from_pwfile;
*get_keyvalue_from_pwfile = \&_get_keyvalue_from_pwfile;
}
sub _get_line_from_pwfile {
my ( $lookup_file, $lookup_key, $is_case_insensitive ) = @_;
my @PW;
if ( open my $lookup_fh, '<', $lookup_file ) {
@PW = _find_field_with_value_in_pw_file( $lookup_fh, 0, $lookup_key, $is_case_insensitive );
close $lookup_fh;
}
return \@PW;
}
sub _get_keyvalue_from_pwfile {
my ( $lookup_file, $key_position, $lookup_key, $is_case_insensitive ) = @_;
my $pwref = _get_line_from_pwfile( $lookup_file, $lookup_key, $is_case_insensitive );
if ( defined $pwref && @{$pwref} ) {
return $pwref->[$key_position];
}
return;
}
sub beginmatch {
return ( substr( $_[0], 0, length( $_[1] ) ) eq $_[1] ) ? 1 : 0;
}
sub dump_rec {
my $rec = shift;
if ( ref $rec eq 'HASH' ) {
my $buf;
foreach my $key ( sort keys %{$rec} ) {
if ( ref $rec->{$key} eq 'ARRAY' ) {
$buf .= "$key=" . join( ',', @{ $rec->{$key} } ) . "\t";
}
else {
$buf .= "$key=$rec->{$key}\t";
}
}
return $buf;
}
else {
return $rec;
}
}
sub get_gid_cacheref {
if ( $INC{'B/C.pm'} ) {
confess("Cpanel::PwCache::get_gid_cacheref cannot be run under B::C (see case 162857)");
}
my $grplock = Cpanel::SafeFile::safeopen( \*GRPFILE, '<', "$SYSTEM_CONF_DIR/group" );
return if !$grplock;
local $/;
my %GIDCACHE = map { $_ = [ split( /:/, $_ ) ]; defined $_->[2] ? ( $_->[2] => $_ ) : () } split( /\n/, readline( \*GRPFILE ) );
Cpanel::SafeFile::safeclose( \*GRPFILE, $grplock );
return \%GIDCACHE;
}
sub load_pw_cache_file {
my ( $file, $passwduid, $passwdmtime, $no_uidcheck, $keepforever ) = @_;
if ( !defined $passwduid || !defined $passwdmtime ) {
( $passwduid, $passwdmtime ) = ( stat($file) )[ 4, 9 ];
}
if ( !$INC{'Cpanel/JSON.pm'} || ( !$no_uidcheck && $passwduid != 0 ) || !$passwdmtime ) { return; }
my $pwdata_ref = Cpanel::JSON::FailOK::LoadFile($file);
if ( !$pwdata_ref || !ref $pwdata_ref ) { return; }
my $pwdata = ( ref $pwdata_ref eq 'ARRAY' ? $pwdata_ref : $pwdata_ref->{'contents'} );
if ( !$pwdata || ref $pwdata ne 'ARRAY' ) { return; }
_cache_pwdata($pwdata);
if ($keepforever) {
$pwdata->[11] = 2147483647;
$pwdata->[12] = 2147483647;
}
return $pwdata->[0];
}
sub invalidate {
my $keyname = shift;
if ( $keyname eq 'user' ) { $keyname = 0; }
elsif ( $keyname eq 'uid' ) { $keyname = 2; }
my $key = shift;
$keyname = int $keyname;
$key =~ s/\///g;
my $pwkey = $keyname . ':' . $key;
if ( exists $pwcache_ref->{$pwkey} ) {
delete $pwcache_ref->{$pwkey};
}
if ( $keyname == 0 ) {
unlink( $PRODUCT_CONF_DIR . '/@pwcache/' . $key );
}
unlink("$PRODUCT_CONF_DIR/pw.cache/$pwkey");
unlink(
"$SYSTEM_CONF_DIR/master.passwd.cache",
"$SYSTEM_CONF_DIR/master.passwd.nouids.cache",
"$SYSTEM_CONF_DIR/passwd.cache",
"$SYSTEM_CONF_DIR/passwd.nouids.cache",
"$SYSTEM_CONF_DIR/shadow.cache",
"$SYSTEM_CONF_DIR/shadow.nouids.cache",
);
}
sub getusername {
my $user = defined $_[0] ? $_[0] : $>;
return ( Cpanel::PwCache::getpwuid($user) )[0];
}
sub gethomedir {
if ( defined $_[0] ) {
return $HOMEDIR_CACHE{ $_[0] } if exists $HOMEDIR_CACHE{ $_[0] };
if ( $_[0] =~ /^[0-9]+$/ ) {
return ( $HOMEDIR_CACHE{ $_[0] } = ( Cpanel::PwCache::getpwuid( $_[0] ) )[7] );
}
else {
return ( $HOMEDIR_CACHE{ $_[0] } = ( Cpanel::PwCache::getpwnam( $_[0] ) )[7] );
}
}
else {
my $uid = $>;
return $HOMEDIR_CACHE{$uid} if exists $HOMEDIR_CACHE{$uid};
return ( $HOMEDIR_CACHE{$uid} = ( Cpanel::PwCache::getpwuid($uid) )[7] );
}
}
sub getshell {
return _get_sth_from_pw_for_user( 'shell', @_ );
}
sub getuid {
return _get_sth_from_pw_for_user( 'uid', @_ );
}
sub getgid {
return _get_sth_from_pw_for_user( 'gid', @_ );
}
sub _get_sth_from_pw_for_user {
my ( $what_to_get, $user ) = @_;
$user ||= $>;
if ( $user =~ m{\A[0-9]+\z} ) {
return scalar( ( Cpanel::PwCache::getpwuid($user) )[ $PW_INDEX{$what_to_get} ] );
}
return scalar( ( Cpanel::PwCache::getpwnam($user) )[ $PW_INDEX{$what_to_get} ] );
}
sub default_conf_dir {
$SYSTEM_CONF_DIR = shift if @_;
return $SYSTEM_CONF_DIR;
}
sub default_product_dir {
$PRODUCT_CONF_DIR = shift if @_;
return $PRODUCT_CONF_DIR;
}
sub _find_field_with_value_in_pw_file {
my ( $passwd_fh, $field, $value, $is_case_insensitive ) = @_;
my $match = $is_case_insensitive ? qr/\n(?:[^:\n]+:){$field}\Q$value\E(?=[:\n]+)[^\n]*/si : qr/\n(?:[^\n:]+:){$field}\Q$value\E(?=[:\n]+)[^\n]*/s;
my $capture_match = $is_case_insensitive ? qr/\n((?:[^:\n]+:){$field}\Q$value\E(?=[:\n]+)[^\n]*)/si : qr/\n((?:[^\n:]+:){$field}\Q$value\E(?=[:\n]+)[^\n]*)/;
my $block;
while ( !eof($passwd_fh) ) {
return if ( !defined( $block = Cpanel::IO::read_bytes_to_end_of_line( $passwd_fh, 65535 ) ) );
substr( $block, 0, 0, "\n" ); # Insert a \n at the beginning of the string without rebuidling it
if ( $block =~ $match && $block =~ $capture_match ) {
return split( ':', $1 );
}
}
return;
}
1;
} # --- END Cpanel/PwCache.pm
{ # --- BEGIN Cpanel/AcctUtils/Account.pm
package Cpanel::AcctUtils::Account;
use strict;
# use Cpanel::PwCache ();
sub accountexists {
( $_[0] && $_[0] !~ tr/\0// && ( ( Cpanel::PwCache::getpwnam( $_[0] ) )[0] || '' ) ne '' ) ? 1 : 0;
}
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.pm
package Cpanel::AcctUtils::Lookup;
use strict;
# use Cpanel::AcctUtils::DomainOwner ();
# use Cpanel::AcctUtils::Account ();
# use Cpanel::Exception ();
sub get_system_user { ##no critic qw(RequireArgUnpacking)
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)
if ( $_[0] =~ tr{/}{} ) {
die Cpanel::Exception::create( 'InvalidParameter', '“[_1]” is not a valid username because it contains a “[_2]” character.', [ $_[0], '/' ] );
}
return $_[0] if !is_strict_webmail_user( $_[0] );
my ($domain) = ( split( m{@}, $_[0], 2 ) )[1];
my $sysuser = Cpanel::AcctUtils::DomainOwner::getdomainowner( $domain, { 'skiptruelookup' => 1, 'default' => '' } );
if ( !length $sysuser ) {
die Cpanel::Exception::create( 'DomainDoesNotExist', 'The domain “[_1]” does not exist.', [$domain] );
}
return $sysuser;
}
sub is_webmail_user { ##no critic qw(RequireArgUnpacking)
return $_[0] =~ m{[+%:@]} ? 1 : 0;
}
sub is_strict_webmail_user { ##no critic qw(RequireArgUnpacking)
return $_[0] =~ tr{@}{} ? 1 : 0;
}
sub normalize_webmail_user {
my ($user) = @_;
return $user if $user =~ tr{@}{};
$user =~ s/[+%:]/@/;
return $user;
}
1;
} # --- END Cpanel/AcctUtils/Lookup.pm
{ # --- BEGIN Cpanel/AcctUtils/Owner.pm
package Cpanel::AcctUtils::Owner;
use strict;
# use Cpanel::FileLookup ();
# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::AcctUtils::DomainOwner ();
# use Cpanel::AcctUtils::Lookup ();
use Try::Tiny;
my $logger;
sub getdomainowner {
goto &Cpanel::AcctUtils::DomainOwner::getdomainowner;
}
sub getowner {
my ($user) = @_;
if ( length $user && ( $user eq 'root' || $user eq 'nobody' || $user eq 'cpanel' ) ) {
return 'root';
}
my $owner;
if ( !$user ) {
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
$logger->warn('No user specified');
return;
}
if ( $user =~ m{@} ) {
my $err;
try {
$user = Cpanel::AcctUtils::Lookup::get_system_user($user);
}
catch {
$err = $_;
};
return '' if !$user || $err;
}
if ( !exists $Cpanel::FileLookup::FILELOOKUPCACHE{'/etc/trueuserowners'} && !-r '/var/cpanel/users/' . $user && -r '/etc/trueuserowners' ) {
build_trueuserowners_cache();
}
if ( $Cpanel::FileLookup::FILELOOKUPCACHE{'/etc/trueuserowners'}{$user} ) {
return $Cpanel::FileLookup::FILELOOKUPCACHE{'/etc/trueuserowners'}{$user};
}
return 'root' unless Cpanel::Config::LoadCpUserFile::has_cpuser_file($user);
my $cpuser_ref = Cpanel::Config::LoadCpUserFile::loadcpuserfile($user);
return 'root' if ( !scalar keys %{$cpuser_ref} );
if ( exists $cpuser_ref->{'OWNER'} && $cpuser_ref->{'OWNER'} ) {
$owner = $cpuser_ref->{'OWNER'};
}
else {
$owner = 'root';
}
return $owner;
}
sub build_trueuserowners_cache {
Cpanel::FileLookup::_filelookup( '/etc/trueuserowners', 'initcache' => 1 );
}
1;
} # --- END Cpanel/AcctUtils/Owner.pm
{ # --- BEGIN Cpanel/AcctUtils/DomainOwner.pm
package Cpanel::AcctUtils::DomainOwner;
use strict;
# use Cpanel::AcctUtils::DomainOwner::Tiny ();
# use Cpanel::Reseller ();
# use Cpanel::AcctUtils::Owner ();
# use Cpanel::AcctUtils::DomainOwnerCache ();
# use Cpanel::ConfigFiles ();
# use Cpanel::FileLookup ();
*getdomainowner = \&Cpanel::AcctUtils::DomainOwner::Tiny::getdomainowner;
*clearcache = \&Cpanel::AcctUtils::DomainOwnerCache::clearcache;
sub getdomainownerBAMP {
my $domain = shift;
my $opref = shift;
my $owner = getdomainowner( $domain, $opref );
if ($owner) { return $owner; }
my @DNSPATH = split( /\./, lc($domain) );
my @SEARCHPATH = pop(@DNSPATH);
while ( $#DNSPATH > 0 ) {
unshift( @SEARCHPATH, pop(@DNSPATH) );
my $searchdomain = join( '.', @SEARCHPATH );
my $rootdomainowner = getdomainowner( $searchdomain, $opref );
if ($rootdomainowner) { return $rootdomainowner; }
}
return;
}
sub check_each_domain_level_for_ownership {
my ( $user, $domain ) = @_;
$domain =~ s/^www\.//g;
$domain =~ s/\///g;
Cpanel::AcctUtils::DomainOwnerCache::cachedomainowners();
my @DNSPATH = split( /\./, $domain );
my @SEARCHPATH = pop(@DNSPATH);
my $user_is_reseller;
while ( scalar @DNSPATH > 0 ) {
unshift( @SEARCHPATH, pop(@DNSPATH) );
my $searchdomain = join( '.', @SEARCHPATH );
my $rootdomainowner = getdomainowner( $searchdomain, { 'default' => '' } );
if ($rootdomainowner) {
if ( $rootdomainowner ne $user ) {
if ( !defined $user_is_reseller ) {
$user_is_reseller = Cpanel::Reseller::isreseller($user);
}
if ( !$user_is_reseller || Cpanel::AcctUtils::Owner::getowner($rootdomainowner) ne $user ) {
return ( 0, $searchdomain, $rootdomainowner );
}
}
}
elsif ( _zone_exists($searchdomain) ) {
return ( 0, $searchdomain );
}
}
return 1;
}
sub _zone_exists {
my ($zone) = @_;
if ( !$INC{'Cpanel/DnsUtils/AskDnsAdmin.pm'} ) {
local $@;
eval 'require Cpanel::DnsUtils::AskDnsAdmin;';
if ($@) { die "Failed to load Cpanel::DnsUtils::AskDnsAdmin: $@" }
}
return 'Cpanel::DnsUtils::AskDnsAdmin'->can('askdnsadmin')->( 'ZONEEXISTS', $Cpanel::DnsUtils::AskDnsAdmin::REMOTE_AND_LOCAL, $zone );
}
sub build_truedomain_cache {
return Cpanel::FileLookup::_filelookup( $Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE, 'initcache' => 1, @_ );
}
sub build_domain_cache {
return Cpanel::FileLookup::_filelookup( $Cpanel::ConfigFiles::USERDOMAINS_FILE, 'initcache' => 1, @_ );
}
my $locale;
sub _croak_maketext {
my (@text) = @_;
local $@;
eval 'require Cpanel::Locale; require Cpanel::Carp;'; ## no critic qw(ProhibitStringyEval) -- quoted eval to hide this from perlcc
if ($@) { die "Failed to load Cpanel::Locale or Cpanel::Carp: $@"; }
$locale ||= 'Cpanel::Locale'->get_handle();
die 'Cpanel::Carp'->can('safe_longmess')->( $locale->maketext(@text) );
}
sub is_domain_owned_by {
my ( $domain, $user ) = @_;
$domain or _croak_maketext('The domain ownership check failed because the caller did not specify a domain.');
$user or _croak_maketext('The domain ownership check failed because the caller did not specify a username or [asis,UID].');
if ( $user =~ /^[0-9]+$/ ) {
local $@;
eval 'require Cpanel::PwCache;'; ## no critic qw(ProhibitStringyEval) -- quoted eval to hide this from perlcc
if ($@) { die "Failed to load Cpanel::PwCache: $@" }
$user = ( 'Cpanel::PwCache'->can('getpwuid')->( int $user ) )[0];
$user or _croak_maketext('The domain ownership check failed because the system could not convert the [asis,UID] into a username.');
}
my $domainowner = getdomainowner( $domain, { default => '' } );
return 1 if $domainowner eq $user;
return 0;
}
1;
} # --- END Cpanel/AcctUtils/DomainOwner.pm
{ # --- BEGIN Cpanel/CPAN/MIME/Base64/Perl.pm
package Cpanel::CPAN::MIME::Base64::Perl;
use strict;
use vars qw(@ISA @EXPORT $VERSION);
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(encode_base64 decode_base64);
$VERSION = '1.00';
sub encode_base64 ($;$) {
if ( $] >= 5.006 ) {
require bytes;
if ( bytes::length( $_[0] ) > length( $_[0] )
|| ( $] >= 5.008 && $_[0] =~ /[^\0-\xFF]/ ) ) {
require Carp;
Carp::croak("The Base64 encoding is only defined for bytes");
}
}
use integer;
my $eol = $_[1];
$eol = "\n" unless defined $eol;
my $res = pack( "u", $_[0] );
$res =~ s/^.//mg;
$res =~ s/\n//g;
$res =~ tr|` -_|AA-Za-z0-9+/|; # `# help emacs
my $padding = ( 3 - length( $_[0] ) % 3 ) % 3;
$res =~ s/.{$padding}$/'=' x $padding/e if $padding;
if ( length $eol ) {
$res =~ s/(.{1,76})/$1$eol/g;
}
return $res;
}
sub decode_base64 ($) {
local ($^W) = 0; # unpack("u",...) gives bogus warning in 5.00[123]
use integer;
my $str = shift;
$str =~ tr|A-Za-z0-9+=/||cd; # remove non-base64 chars
if ( length($str) % 4 ) {
require Carp;
Carp::carp("Length of base64 data not a multiple of 4");
}
$str =~ s/=+$//; # remove padding
$str =~ tr|A-Za-z0-9+/| -_|; # convert to uuencoded format
return "" unless length $str;
my $uustr = '';
my ( $i, $l );
$l = length($str) - 60;
for ( $i = 0; $i <= $l; $i += 60 ) {
$uustr .= "M" . substr( $str, $i, 60 );
}
$str = substr( $str, $i );
if ( $str ne "" ) {
$uustr .= chr( 32 + length($str) * 3 / 4 ) . $str;
}
return unpack( "u", $uustr );
}
1;
} # --- END Cpanel/CPAN/MIME/Base64/Perl.pm
{ # --- BEGIN Cpanel/Utils.pm
package Cpanel::Utils;
sub destroy_this_sub {
no strict 'refs';
my $calling_func = ( caller(1) )[3];
my ( $root, $function ) = $calling_func =~ m/^(.*::)([^:]+)$/;
undef *{$calling_func};
delete ${"$root"}{$function};
}
1;
} # --- END Cpanel/Utils.pm
{ # --- BEGIN Cpanel/CPAN/URI/Escape.pm
package Cpanel::CPAN::URI::Escape;
use strict;
our ( @ISA, @EXPORT, @EXPORT_OK, $VERSION );
our %escapes;
# use Cpanel::Utils ();
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(uri_escape uri_unescape);
@EXPORT_OK = qw(%escapes uri_escape_utf8);
$VERSION = sprintf( "%d.%02d", q$Revision: 3.28 $ =~ /(\d+)\.(\d+)/ );
my %subst; # compiled patternes
sub _init {
return if (%escapes);
%escapes = map { chr($_) => sprintf( '%%%02x', $_ ) } ( 0 .. 255 );
}
sub fast_uri_escape {
_init();
no warnings 'redefine';
*fast_uri_escape = \&real_fast_uri_escape;
goto \&real_fast_uri_escape;
}
sub real_fast_uri_escape {
my $text = shift;
defined $text && $text =~ s/([^A-Za-z0-9\-_\.~])/$escapes{$1}/g ? $text : $text; #Its 2% faster with a value and 9% fast with undef on a single line
}
sub uri_escape {
_init();
Cpanel::Utils::destroy_this_sub();
*uri_escape = \&real_uri_escape;
goto \&real_uri_escape;
}
sub real_uri_escape {
my ( $text, $patn ) = @_;
return undef unless defined $text;
if ( defined $patn ) {
unless ( exists $subst{$patn} ) {
( my $tmp = $patn ) =~ s,/,\\/,g;
eval "\$subst{\$patn} = sub {\$_[0] =~ s/([$tmp])/\$escapes{\$1} || _fail_hi(\$1)/ge; }";
Carp::croak("uri_escape: $@") if $@;
}
&{ $subst{$patn} }($text);
}
else {
$text =~ s/([^A-Za-z0-9\-_\.~])/$escapes{$1} || _fail_hi($1)/ge;
}
$text;
}
sub _fail_hi {
my $chr = shift;
require Carp;
Carp::croak( sprintf "Can't escape \\x{%04X}, try uri_escape_utf8() instead", ord($chr) );
}
sub uri_escape_utf8 {
my $text = shift;
if ( $] < 5.008 ) {
$text =~ s/([^\0-\x7F])/do {my $o = ord($1); sprintf("%c%c", 0xc0 | ($o >> 6), 0x80 | ($o & 0x3f)) }/ge;
}
else {
utf8::encode($text);
}
return uri_escape( $text, @_ );
}
sub fast_uri_unescape {
my $str = shift;
$str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str;
$str;
}
sub uri_unescape {
my $str = shift;
if ( @_ && wantarray ) {
my @str = ( $str, @_ ); # need to copy
foreach (@str) {
s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
}
return @str;
}
$str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str;
$str;
}
1;
} # --- END Cpanel/CPAN/URI/Escape.pm
{ # --- BEGIN Cpanel/Encoder/URI.pm
package Cpanel::Encoder::URI;
use strict;
# use Cpanel::CPAN::URI::Escape ();
our $VERSION = '1.1';
our $URI_SAFE_CHARS = 'A-Za-z0-9\-_.!~*';
*uri_encode_str = *Cpanel::CPAN::URI::Escape::fast_uri_escape;
sub uri_decode_str {
my $str = shift;
if ( defined $str ) {
$str =~ tr/+/ /;
$str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
}
return $str;
}
sub uri_decode_str_nocopy { ##no critic qw(RequireArgUnpacking)
for ( $_[0] ) {
last if !defined;
tr/+/ /;
s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
}
return;
}
sub uri_encode_dirstr {
return join( '/', ( map uri_encode_str($_), split( m{/}, shift ) ) );
}
1;
} # --- END Cpanel/Encoder/URI.pm
{ # --- BEGIN Cpanel/Errno.pm
package Cpanel::Errno;
use strict;
use Errno ();
my %_err_name_cache;
sub get_name_for_errno_number {
my ($number) = @_;
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/ChildErrorStringifier.pm
package Cpanel::ChildErrorStringifier;
use strict;
# use Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase ();
# use Cpanel::Errno ();
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
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
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) = @_;
Cpanel::LoadModule::load_perl_module('Cpanel::Config::Constants::Perl');
return $Cpanel::Config::Constants::Perl::SIGNAL_NAME{ $self->signal_code() };
}
sub program {
my ($self) = @_;
return $self->{'_PROGRAM_NAME'} || undef;
}
sub autopsy {
my ($self) = @_;
return undef if !$self->CHILD_ERROR();
my ( $str, @args );
my $program = $self->program();
if ( $self->error_code() ) {
$str = $program ? $self->_PROGRAM_ERROR_PHRASE() : $self->_ERROR_PHRASE();
@args = (
$self->error_code(),
$self->_EXTRA_ERROR_PHRASE_ARGUMENTS(),
);
unshift @args, $program if $program;
}
elsif ( $self->signal_code() ) {
$str = $program ? $self->_PROGRAM_SIGNAL_PHRASE() : $self->_SIGNAL_PHRASE();
@args = (
$self->signal_name(),
$self->signal_code(),
$self->_EXTRA_SIGNAL_PHRASE_ARGUMENTS(),
);
unshift @args, $program if $program;
}
my @localize = ( [ $str, @args ] );
$self->_add_core_dump_to_phrase_if_needed( \@localize );
$self->_add_additional_phrases_to_autopsy( \@localize );
Cpanel::LoadModule::load_perl_module('Cpanel::Locale');
my $lh = 'Cpanel::Locale'->get_handle();
return join( ' ', map { $lh->makevar( @{$_} ); } @localize );
}
sub die_if_error {
my ($self) = @_;
if ( $self->signal_code() ) {
die 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() ) {
die Cpanel::Exception::create(
'ProcessFailed::Error',
{
process_name => $self->program(),
error_code => $self->error_code(),
$self->_extra_error_args_for_die_if_error(),
}
);
}
return $self;
}
sub _extra_error_args_for_die_if_error { }
sub _add_additional_phrases_to_autopsy { }
sub _add_core_dump_to_phrase_if_needed {
my ( $self, $localize_ref ) = @_;
if ( $self->dumped_core() ) {
push @{$localize_ref}, [ Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The process dumped a core file.') ];
}
return;
}
sub _ERROR_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The subprocess reported error number [numf,_1] when it ended.');
}
sub _PROGRAM_ERROR_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The subprocess “[_1]” reported error number [numf,_2] when it ended.');
}
sub _EXTRA_ERROR_PHRASE_ARGUMENTS { }
sub _SIGNAL_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The subprocess ended prematurely because it received the “[_1]” ([_2]) signal.');
}
sub _PROGRAM_SIGNAL_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The subprocess “[_1]” ended prematurely because it received the “[_2]” ([_3]) signal.');
}
*_EXTRA_SIGNAL_PHRASE_ARGUMENTS = \&_EXTRA_ERROR_PHRASE_ARGUMENTS;
1;
} # --- END Cpanel/ChildErrorStringifier.pm
{ # --- BEGIN Cpanel/ForkAsync.pm
package Cpanel::ForkAsync;
use strict;
# use Cpanel::Exception ();
my $DEFAULT_ERROR_CODE = 127; #EKEYEXPIRED
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 + $!;
warn $err;
print STDERR $err;
exit( $io_err || $DEFAULT_ERROR_CODE );
}
exit 0;
}
return $pid;
}
1;
} # --- END Cpanel/ForkAsync.pm
{ # --- BEGIN Cpanel/SafeStorable.pm
package Cpanel::SafeStorable;
use strict;
eval { local $SIG{__DIE__} = sub { warn "Storable is not available (attempting to ignore)."; }; require Storable; };
our $VERSION = '1.00';
sub nstore {
goto &Storable::nstore;
}
sub store {
goto &Storable::store;
}
sub store_fd {
goto &Storable::store_fd;
}
sub nstore_fd {
goto &Storable::nstore_fd;
}
sub freeze {
goto &Storable::freeze;
}
sub nfreeze {
goto &Storable::nfreeze;
}
sub dclone {
local $Storable::flags = 6;
goto &Storable::dclone;
}
sub lock_store {
goto &Storable::lock_store;
}
sub lock_nstore {
goto &Storable::lock_nstore;
}
sub file_magic {
goto &Storable::file_magic;
}
sub read_magic {
goto &Storable::read_magic;
}
sub thaw {
return Storable::thaw( $_[0], 0 );
}
sub retrieve {
return Storable::retrieve( $_[0], 0 );
}
sub fd_retrieve {
return Storable::fd_retrieve( $_[0], 0 );
}
sub lock_retrieve {
return Storable::lock_retrieve( $_[0], 0 );
}
sub retrieve_fd {
goto &fd_retrieve;
}
1;
} # --- END Cpanel/SafeStorable.pm
{ # --- BEGIN Cpanel/ForkSync.pm
package Cpanel::ForkSync;
use strict;
# use Cpanel::ChildErrorStringifier();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::ChildErrorStringifier); }
use Try::Tiny;
use IO::Handle ();
# use Cpanel::ForkAsync ();
# use Cpanel::Logger ();
# use Cpanel::SafeStorable ();
my $logger;
sub new {
my ( $class, $code, @args ) = @_;
local $SIG{'CHLD'} = 'DEFAULT';
my ( $PR, $CW, $RC ) = ( IO::Handle->new(), IO::Handle->new() );
pipe( $PR, $CW ) or do {
$logger ||= Cpanel::Logger->new();
$logger->die("Failed to pipe(): $!");
};
$CW->autoflush();
my $pid = Cpanel::ForkAsync::do_in_child(
sub {
close $PR or die "close() on parent reader in child failed: $!";
my ( $err, $ret );
try {
$ret = { '_return' => [ $code->(@args) ] }; # if we die/exit here, storable is going to be corrupted
}
catch {
$err = $_;
$ret = { '_return' => undef, '_exception' => Cpanel::Exception::get_string($_) };
};
Storable::nstore_fd( $ret, $CW );
close $CW or die "close() on child writer in child failed: $!";
die $err if $err;
return;
}
);
close $CW or warn "Parent failed to close child-write: $!";
local $@;
eval { local $SIG{__DIE__}; local $SIG{__WARN__}; $RC = Cpanel::SafeStorable::fd_retrieve($PR); };
my $retrieve_err = $@;
close $PR or warn "Parent failed to close parent-read: $!";
local $?;
waitpid( $pid, 0 );
my $self = {
_CHILD_ERROR => $?,
_pid => $pid,
_retrieve_err => $retrieve_err,
_return => $RC->{'_return'},
_exception => $RC->{'_exception'},
};
return bless $self, $class;
}
sub exception {
my ($self) = @_;
return $self->{'_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(); #legacy compatibility
return undef if $run->retrieve_error() || !defined $run->return() || $run->CHILD_ERROR();
return wantarray ? @{ $run->return() } : $run->return()->[-1];
}
1;
} # --- END Cpanel/ForkSync.pm
{ # --- BEGIN Cpanel/UTF8/Strict.pm
package Cpanel::UTF8::Strict;
use strict;
my $ucs_7fffffff = "\xfd\xbf\xbf\xbf\xbf\xbf";
sub decode { ## no critic qw(RequireArgUnpacking)
utf8::decode( $_[0] ) or do {
die sprintf "Invalid UTF-8 in string: “%s”", _escape_8bit_for_reading( $_[0] );
};
return $_[0];
}
sub _escape_8bit_for_reading {
my ($readable) = @_;
$readable =~ s<\\><\\\\>g;
$readable =~ s<([\x{80}-\x{ff}])><sprintf '\x{%x}', ord $1>eg;
return $readable;
}
1;
} # --- END Cpanel/UTF8/Strict.pm
{ # --- BEGIN Cpanel/Email/Object.pm
package Cpanel::Email::Object;
use strict;
# use Cpanel::CPAN::MIME::Base64::Perl ();
# use Cpanel::Autodie ();
# use Cpanel::Encoder::URI ();
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::ForkSync ();
# use Cpanel::LoadModule ();
# use Cpanel::UTF8::Strict ();
my $CHUNK_SIZE = 2**15;
my $CHUNK_SIZE_FOR_BASE64 = 60 * 57;
my $DEFAULT_CONTENT_TYPE = 'text/plain; charset="utf-8"';
sub new {
my ( $class, %opts ) = @_;
_validate_opts( \%opts );
for (qw( subject from )) {
$opts{$_} = q<> if !defined $opts{$_};
}
my $self = { _opts => \%opts };
return bless $self, $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'} } ),
);
if ( length $self->{'_opts'}{'from'} ) {
$headers_to_encode{'From'} = $self->{'_opts'}{'from'};
}
if ( length $self->{'_opts'}{'subject'} ) {
$headers_to_encode{'Subject'} = $self->{'_opts'}{'subject'};
}
if ( $self->{'_opts'}{'x_headers'} ) {
my $xh_hr = $self->{'_opts'}{'x_headers'};
@headers_to_encode{ map { "X-$_" } keys %$xh_hr } = values %$xh_hr;
}
my %encoded_headers;
{
local $INC{'MIME/Base64.pm'} = __FILE__ if !$INC{'MIME/Base64.pm'};
local *MIME::Base64::encode_base64 = \&Cpanel::CPAN::MIME::Base64::Perl::encode_base64 if !MIME::Base64->can('encode_base64');
eval {
Cpanel::LoadModule::load_perl_module('Email::MIME::Encode');
%encoded_headers = map { $_ => Email::MIME::Encode::maybe_mime_encode_header( $_, Cpanel::UTF8::Strict::decode( $headers_to_encode{$_} ), 'UTF-8' ) } keys %headers_to_encode;
};
if ($@) {
%encoded_headers = map { $_ => Cpanel::UTF8::Strict::decode( $headers_to_encode{$_} ) } keys %headers_to_encode;
}
}
my @headers = map { "$_: $encoded_headers{$_}" } 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 _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'} ) {
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, Cpanel::CPAN::MIME::Base64::Perl::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, Cpanel::CPAN::MIME::Base64::Perl::encode_base64($buffer) );
}
}
return;
}
sub _print_body_part {
my ( $self, $wfh, $body_key, $content_type ) = @_;
my $body_sr = $self->{'_opts'}{$body_key};
Cpanel::Autodie::print( $wfh, "Content-Type: $content_type; charset=utf-8\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;
if ($has_text) {
if ($has_html) {
my $boundary = $self->_make_boundary('alternative');
$self->_print_mime_header_if_needed($wfh);
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, $buffer );
}
}
else {
Cpanel::Autodie::print( $wfh, $$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/JSON.pm
package Cpanel::JSON;
use strict;
# use Cpanel::Fcntl::Constants ();
# use Cpanel::FHUtils::Tiny ();
eval { local $SIG{__DIE__} = sub { warn "JSON\:\:XS is not available (attempting to ignore)."; }; require 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 _create_new_json_object {
if ( $INC{'B/C.pm'} ) {
eval 'require Cpanel::Carp;' or die $@; # hidden from perlcc
die 'Cpanel::Carp'->can('safe_longmess')->("_create_new_json_object cannot be run under B::C (SEGV)");
}
if ( !$copied_boolean ) {
*Types::Serialiser::Boolean:: = *JSON::PP::Boolean::;
$copied_boolean = 1;
}
return JSON::XS->new()->shrink(1)->allow_nonref(1)->convert_blessed(1);
}
sub _create_json_object {
return ( $XS_ConvertBlessed_obj ||= _create_new_json_object() );
}
sub pretty_dump {
return _create_new_json_object()->pretty(1)->encode( $_[0] );
}
sub canonical_dump {
return _create_new_json_object()->canonical(1)->encode( $_[0] );
}
sub Dump {
if ( !$XS_ConvertBlessed_obj ) { _create_json_object(); }
return $XS_ConvertBlessed_obj->encode( $_[0] );
}
sub Load {
if ( !$XS_ConvertBlessed_obj ) { _create_json_object(); }
$_[0] .= '' if $] < 5.008;
my $decoded;
local $@;
eval { $decoded = $XS_ConvertBlessed_obj->decode( $_[0] ); };
_throw_json_error( $@, $_[1] ) if $@;
return $decoded;
}
sub LoadRelaxed {
if ( !$XS_RelaxedConvertBlessed_obj ) { $XS_RelaxedConvertBlessed_obj = _create_new_json_object()->relaxed(1); }
my $decoded;
local $@;
eval { $decoded = $XS_RelaxedConvertBlessed_obj->decode( $_[0] ); };
_throw_json_error( $@, $_[1] ) if $@;
return $decoded;
}
sub _throw_json_error {
my ( $exception, $path ) = @_;
local $@;
eval 'require Cpanel::Exception;' if !$INC{'Cpanel/Exception.pm'};
die $exception if $@;
die 'Cpanel::Exception'->can('create')->( 'JSONParseError', { 'error' => $exception, 'path' => $path } );
}
sub LoadNoSetUTF8 {
if ( !$XS_NoSetUTF8ConvertBlessed_obj ) {
$XS_NoSetUTF8ConvertBlessed_obj = _create_new_json_object();
if ( $XS_NoSetUTF8ConvertBlessed_obj->can('no_set_utf8') ) {
$XS_NoSetUTF8ConvertBlessed_obj->no_set_utf8(1);
}
else {
warn "JSON::XS is missing the no_set_utf8 flag";
}
}
my $decoded;
local $@;
eval { $decoded = $XS_NoSetUTF8ConvertBlessed_obj->decode( $_[0] ); };
_throw_json_error( $@, $_[1] ) if $@;
return $decoded;
}
sub LoadNoSetUTF8Relaxed {
if ( !$XS_NoSetUTF8RelaxedConvertBlessed_obj ) {
$XS_NoSetUTF8RelaxedConvertBlessed_obj = _create_new_json_object();
if ( $XS_NoSetUTF8RelaxedConvertBlessed_obj->can('no_set_utf8') ) {
$XS_NoSetUTF8RelaxedConvertBlessed_obj->no_set_utf8(1);
}
else {
warn "JSON::XS is missing the no_set_utf8 flag";
}
$XS_NoSetUTF8RelaxedConvertBlessed_obj->relaxed(1);
}
my $decoded;
local $@;
eval { $decoded = $XS_NoSetUTF8RelaxedConvertBlessed_obj->decode( $_[0] ); };
_throw_json_error( $@, $_[1] ) if $@;
return $decoded;
}
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 _LoadFile {
my ( $file, $max, $decode_utf8, $path, $relaxed ) = @_;
my $str_r;
if ( Cpanel::FHUtils::Tiny::is_a($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 _ ) {
eval 'require Cpanel::Carp;' or die $@; #hidden from perlcc
die 'Cpanel::Carp'->can('safe_longmess')->("“$file” is non-existent or empty.");
}
open( my $fh, '<', $file ) or die "Cannot read from “$file”: $!";
local $!;
$str_r = \do { local $/; <$fh> };
warn "Error reading from “$file”: $!" if $! && !( $!{EBADF} && $] < 5.010 );
close $fh or warn "close($file) failed: $!";
}
if ( $decode_utf8 && $decode_utf8 == $DECODE_UTF8 ) {
Cpanel::UTF8::Strict::decode($$str_r);
return LoadNoSetUTF8Relaxed( $$str_r, $path || $file ) if $relaxed;
return LoadNoSetUTF8( $$str_r, $path || $file );
}
return LoadRelaxed( $$str_r, $path || $file ) if $relaxed;
return Load( $$str_r, $path || $file );
}
sub SafeDump {
my $raw_json = Dump( $_[0] );
$raw_json =~ s{\/}{\\/}g;
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: $!" if $!;
}
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] );
}
sub _suitable_for_dumping {
my $item = shift;
my $reftype = ref $item;
return 1 if !defined $item;
return 1 if $reftype eq "";
return 1 if $reftype =~ /\A(ARRAY|HASH)\z/;
return 1 if $reftype =~ /\A(SCALAR|(JSON::(XS|PP)|Types::Serialiser)::Boolean)\z/ && $$item =~ /\A[01]\z/;
return 0;
}
sub sanitize_for_dumping {
my $item = shift;
my $reftype = ref $item;
if ( !defined $item || $reftype eq "" ) {
return $item;
}
elsif ( $reftype =~ /\A(SCALAR|(JSON::(XS|PP)|Types::Serialiser)::Boolean)\z/ && $$item =~ /\A[01]\z/ ) {
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 stricture isn't suitable for dumping.";
}
}
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;
}
1;
} # --- END Cpanel/JSON.pm
{ # --- BEGIN Cpanel/Transaction/File/Read/JSON.pm
package Cpanel::Transaction::File::Read::JSON;
use strict;
# use Cpanel::Autodie ();
# use Cpanel::JSON ();
sub _init_data {
my ( $self, %opts ) = @_;
return \undef if -z $self->{'_fh'};
my $txt;
Cpanel::Autodie::read( $self->{'_fh'}, $txt, -s _ );
my $load = Cpanel::JSON::Load($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 Try::Tiny;
# use Cpanel::Autodie ();
# 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 ( !-e $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 }, $class;
}
sub _init_data_with_catch {
my ( $self, %opts ) = @_;
my $data;
try {
$data = $self->_init_data(%opts);
}
catch {
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 {
my ($self) = @_;
return $self->{'_data'};
}
sub get_original_mtime {
my ($self) = @_;
return $self->{'_original_mtime'};
}
sub path_is_newer {
my ($self) = @_;
return ( Cpanel::Autodie::stat( $self->{'_path'} ) )[9] != $self->{'_original_mtime'} ? 1 : 0;
}
*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/IteratorBase.pm
package Cpanel::FileUtils::Read::IteratorBase;
use strict;
use Try::Tiny;
# use Cpanel::Exception ();
sub new {
my ( $class, $fh, $todo_cr ) = @_;
my $self = bless {
_fh => $fh,
_todo_cr => $todo_cr,
}, $class;
return $self->_run();
}
sub get_iteration_index {
my ($self) = @_;
return ${ $self->{'_iteration_index_sr'} };
}
sub stop {
my ($self) = @_;
die Cpanel::FileUtils::Read::IteratorBase::_STOP->new();
}
sub _run_try_catch {
my ( $self, $try_cr ) = @_;
local $!;
try { $try_cr->() }
catch {
die $_ if !UNIVERSAL::isa( $_, __PACKAGE__ . '::_STOP' );
};
if ($!) {
die Cpanel::Exception::create( $self->_READ_ERROR_EXCEPTION_CLASS(), { path => '?', error => $! } );
}
return 1;
}
package Cpanel::FileUtils::Read::IteratorBase::_STOP;
sub new {
my ($class) = @_;
my $scalar;
my $self = \$scalar;
return bless $self, $class;
}
1;
} # --- END Cpanel/FileUtils/Read/IteratorBase.pm
{ # --- BEGIN Cpanel/FileUtils/Read/DirectoryNodeIterator.pm
package Cpanel::FileUtils::Read::DirectoryNodeIterator;
use strict;
use Try::Tiny;
# use Cpanel::FileUtils::Read::IteratorBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::FileUtils::Read::IteratorBase); }
use Errno;
sub _run {
my ($self) = @_;
my $fh = $self->{'_fh'};
my $todo_cr = $self->{'_todo_cr'};
my $iteration_index = 0;
$self->{'_iteration_index_sr'} = \$iteration_index;
$self->_run_try_catch(
sub {
local $_;
while ( $_ = readdir $fh ) {
next if $_ eq '.' || $_ eq '..';
local $!;
$todo_cr->($self);
$iteration_index++;
}
if ( $! == Errno::EBADF() && $^V lt v5.20 ) {
$! = 0;
}
}
);
return 1;
}
sub _READ_ERROR_EXCEPTION_CLASS {
return 'IO::DirectoryReadError';
}
1;
} # --- END Cpanel/FileUtils/Read/DirectoryNodeIterator.pm
{ # --- BEGIN Cpanel/FileUtils/Read.pm
package Cpanel::FileUtils::Read;
use strict;
use Try::Tiny;
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
# use Cpanel::FileUtils::Read::DirectoryNodeIterator ();
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 {
my ( $path, $todo_cr ) = @_;
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 },
);
}
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 ( $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 Cpanel::LoadModule ();
# use Cpanel::Transaction::File::JSONReader ();
# 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 exists $data->{$app}{$event};
return $data->{$app}{'*'};
}
sub get_application_importance {
my ( $self, $app ) = @_;
return $self->get_event_importance( $app, '*' );
}
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 ) = map { $NAME_TO_NUMBER{$_} } qw( High Medium Low );
my %default = (
'Accounts' => $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,
'ChangePassword::ResetRequest' => $low_importance,
'Check' => $low_importance,
'Check::Biglog' => $high_importance,
'Check::CpanelRPMs' => $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::PopBeforeSMTPEnabled' => $medium_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,
'CloudLinux' => $medium_importance,
'Config' => $high_importance,
'ConvertAddon' => $high_importance,
'DigestAuth' => $medium_importance,
'DnsAdmin' => $medium_importance,
'DnsAdmin::ClusterError' => $medium_importance,
'DnsAdmin::UnreachablePeer' => $high_importance,
'EasyApache' => $high_importance,
'Horde' => $low_importance,
'Greylist' => $low_importance,
'ImportMyDNSdb' => $low_importance,
'ImportMyDNSdb::Failure' => $high_importance,
'ImportMyDNSdb::InProgress' => $low_importance,
'ImportMyDNSdb::Success' => $low_importance,
'Install' => $low_importance,
'Install::ClamavConnector' => $high_importance,
'Install::Horde' => $medium_importance,
'Install::PackageExtension' => $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::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,
'cpbackup' => $medium_importance,
'cpbackupdisabled' => $high_importance,
'iContact' => $medium_importance,
'installbandwidth' => $high_importance,
'killacct' => $low_importance,
'migrate_branding' => $low_importance,
'newmailcgi' => $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/Sys/Uname.pm
package Cpanel::Sys::Uname;
use strict;
# use Cpanel::OSSys::Bits ();
our $SYS_UNAME = Cpanel::OSSys::Bits::getbits() == 64 ? 63 : 122;
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 ) {
my @UNAME = unpack( $UNAME_UNPACK_TEMPLATE, $uname );
my $bits = Cpanel::OSSys::Bits::getbits();
if ( $bits == 32 && index( $UNAME[4], '64' ) > -1 ) {
$UNAME[4] = 'i686'; #virtualized in the wrong basesystem
}
return @UNAME;
}
else {
die "The uname() system call failed because of an error: $!";
}
return;
}
1;
} # --- END Cpanel/Sys/Uname.pm
{ # --- BEGIN Cpanel/LoadFile.pm
package Cpanel::LoadFile;
use strict;
use warnings;
use Try::Tiny;
use Errno ();
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
# use Cpanel::Fcntl ();
# use Cpanel::Fcntl::Constants ();
my $READ_CHUNK = 1 << 16; #65536
my $Errno_EINTR = Errno::EINTR();
sub loadfileasarrayref {
my $fileref = _load_file( shift, { 'array_ref' => 1 } );
if ( ref $fileref eq 'ARRAY' ) { return $fileref; }
return;
}
sub loadbinfile {
my $fileref = _load_file( shift, { 'binmode' => 1 } );
if ( ref $fileref eq 'SCALAR' ) { return $$fileref; }
return;
}
sub loadfile_to_fh {
my $fh = shift;
my $fileref = _load_file(shift);
if ( ref $fileref eq 'SCALAR' ) {
print {$fh} $$fileref;
}
}
sub slurpfile { goto &loadfile_to_fh; }
sub loadfile {
my $fileref = _load_file(@_);
if ( ref $fileref eq 'SCALAR' ) { return $$fileref; }
return;
}
sub loadfile_r {
my ( $file, $arg_ref ) = @_;
if ( !$arg_ref->{'skip_exists_check'} ) { return if !-f $file }
if ( open my $lf_fh, '<', $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 {
local $/;
$data = readline $lf_fh;
close $lf_fh;
return \$data;
}
}
else {
return;
}
}
*_load_file = \&loadfile_r;
sub load_userfile_as_root {
die 'load_userfile_as_root have been superseded by using Cpanel::AccessIds::ReducedPrivileges::call_as_user and Cpanel::LoadFile::load($file, 0, MAX_LENGTH);';
}
sub _open {
my ($path) = @_;
local $!;
open my $fh, '<', $path or do {
if ( $!{'ENOENT'} ) {
die Cpanel::Exception::create( 'IO::FileNotFound', { path => $path, error => $! } );
}
die Cpanel::Exception::create( 'IO::FileOpenError', { path => $path, error => $!, mode => '<' } );
};
return $fh;
}
sub _do_if_exists {
my ( $todo_cr, @args ) = @_;
my $ret;
try {
$ret = $todo_cr->(@args);
}
catch {
if ( !try { $_->isa('Cpanel::Exception::IO::FileNotFound') } ) {
local $@ = $_;
die;
}
};
return $ret;
}
sub load_if_exists {
my (@args) = @_;
return _do_if_exists( \&load, @args );
}
sub load_r_if_exists {
my (@args) = @_;
return _do_if_exists( \&load_r, @args );
}
sub load {
my ( $path, $offset, $length ) = @_;
return ${ load_r( $path, $offset, $length ) };
}
sub load_r {
my ( $path, $offset, $length ) = @_;
my $fh = _open($path);
local $!;
my $file_size = -f $fh && -s _;
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 ) {
if ($file_size) {
_read_fast( $fh, $data, $file_size );
}
else {
1 while _read_fast( $fh, $data, $READ_CHUNK, length $data );
}
}
else {
my $togo = $length;
my $bytes_read;
while ( $bytes_read = _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 _read_fast { ##no critic qw(RequireArgUnpacking)
my $ret;
{
$ret = @_ > 3 ? sysread( $_[0], $_[1], $_[2], $_[3] ) : sysread( $_[0], $_[1], $_[2] );
redo if !$ret && $! == $Errno_EINTR;
}
return $ret;
}
1;
} # --- END Cpanel/LoadFile.pm
{ # --- BEGIN Cpanel/Hostname.pm
package Cpanel::Hostname;
use strict;
# use Cpanel::Sys::Uname ();
our $VERSION = 1.6;
our $hostname;
sub gethostname {
if ( $INC{'Cpanel/Sys/Hostname.pm'} ) {
goto &Cpanel::Sys::Hostname::gethostname;
}
if ($hostname) { return $hostname; }
if ( $^O =~ /linux/i ) {
my @uname = Cpanel::Sys::Uname::get_uname_cached();
if ( $uname[1] ) {
$hostname = $uname[1];
$hostname =~ tr{A-Z}{a-z}; # hostnames must be lowercase (see Cpanel::Sys::Hostname::make_hostname_lowercase)
return $hostname;
}
if ( -r '/proc/sys/kernel/hostname' ) {
require Cpanel::LoadFile;
chomp( $hostname = Cpanel::LoadFile::loadfile( '/proc/sys/kernel/hostname', { 'skip_exists_check' => 1 } ) );
$hostname =~ s/[\r\n]//g; # chomp is not enough
}
}
if ( !$hostname ) {
chomp( $hostname = `/usr/local/cpanel/bin/hostname` );
$hostname =~ s/[\r\n]//g; # chomp is not enough
}
if ( !$hostname ) {
eval 'require Cpanel::Sys::Hostname; local $SIG{__DIE__}; local $SIG{__WARN__}; $hostname = Cpanel::Sys::Hostname::gethostname();';
}
$hostname =~ tr{A-Z}{a-z}; # hostnames must be lowercase (see Cpanel::Sys::Hostname::make_hostname_lowercase)
return $hostname;
}
sub shorthostname {
return ( split( /\./, ( gethostname() || '' ) ) )[0];
}
1;
} # --- END Cpanel/Hostname.pm
{ # --- BEGIN Cpanel/StringFunc/Case.pm
package Cpanel::StringFunc::Case;
use strict;
our $VERSION = '1.2';
sub ToUpper {
( local $_ = $_[0] ) =~ tr/[a-z]/[A-Z]/; # avoid altering $_[0] by making a copy
return $_;
}
sub ToLower {
( local $_ = $_[0] ) =~ tr/[A-Z]/[a-z]/; # avoid altering $_[0] by making a copy
return $_;
}
1;
} # --- END Cpanel/StringFunc/Case.pm
{ # --- BEGIN Cpanel/StringFunc/Trim.pm
package Cpanel::StringFunc::Trim;
use strict;
$Cpanel::StringFunc::Trim::VERSION = '1.02';
my %entities = ( #Just some of the most common ones, of course
'ldquo' => q{"},
'rdguo' => q{"},
'lsquo' => q{`},
'rsquo' => q{'},
'laquo' => q{"},
'raquo' => q{"},
'lsaquo' => q{'},
'rsaquo' => q{'},
'lt' => '<',
'gt' => '>',
'amp' => '&',
'bull' => '*',
'trade' => '(TM)',
'copy' => '(C)',
'reg' => '(R)',
'mdash' => '---',
'ndash' => '--',
'nbsp' => ' ',
'sup2' => '(2)',
'sup3' => '(3)',
'frac14' => '1/4',
'frac12' => '1/2',
'frac34' => '3/4',
);
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 ( substr( $str, 0, length($totrim) ) eq $totrim ) {
return substr( $str, length($totrim) );
}
return $str;
}
sub ws_trim {
my ($this) = @_;
my $fix = ref $this eq 'SCALAR' ? $this : \$this;
${$fix} =~ s/^\s+//;
${$fix} =~ s/\s+$//;
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;
}
sub trim_html {
my $this = shift;
my $string = ref $this eq 'SCALAR' ? $this : \$this;
if ( ${$string} !~ tr/<>// ) { # If there is no html, we return ASIS
${$string} = _replace_html_entities( ${$string} );
return ${$string};
}
${$string} =~ s{<script.*?>.*?</script\s*>}{}msig;
my $stream = ${$string};
my ( $html_tag, $data_before_tag );
my $in_pre = 0;
my $filtered_output = '';
while ( $stream =~ m/(\<[^\>\<]+\>?)/ ) {
$html_tag = $1;
$data_before_tag = substr( substr( $stream, 0, $+[0], '' ), 0, -1 * length($html_tag) );
if ($in_pre) {
$filtered_output .= $data_before_tag;
}
else {
$data_before_tag =~ s{[\r\n]}{ }g;
$data_before_tag =~ s{\s+}{ }g;
$data_before_tag =~ s{\A\s+}{}g;
$data_before_tag =~ s{\s+\z}{}g;
$filtered_output .= $data_before_tag;
}
if ( $html_tag =~ m{^<\s*pre[^a-z]}i ) { $in_pre = 1; }
elsif ( $html_tag =~ m{^<\s*\/\s*pre[^a-z]}i ) { $in_pre = 0; }
elsif ( $html_tag =~ /<\s*[p|br][^a-z]/i ) { $filtered_output .= "\n"; }
elsif ( $html_tag =~ /<\s*blockquote[^a-z]/i ) { $filtered_output .= "\t"; }
elsif ( $html_tag =~ /<\s*\/\s*blockquote[^a-z]/i ) { $filtered_output .= "\n"; }
}
if ( pos $stream ) {
substr( $stream, 0, pos($stream), '' );
}
if ($stream) {
if ($in_pre) {
$filtered_output .= $stream;
}
else {
$stream =~ s{[\r\n]}{ }g;
$stream =~ s{\s+}{ }g;
$stream =~ s{\A\s+}{}g;
$stream =~ s{\s+\z}{}g;
$filtered_output .= $stream;
}
}
${$string} = $filtered_output;
${$string} =~ s/<[^>]+>//g;
${$string} = _replace_html_entities( ${$string} );
return ${$string};
}
sub _replace_html_entities {
my $arg = shift;
my $string = ref $arg eq "SCALAR" ? $arg : \$arg;
${$string} =~ s/(&(\w+);)/ $entities{ lc $2 } || $1 /ieg;
return ${$string};
}
1;
} # --- END Cpanel/StringFunc/Trim.pm
{ # --- BEGIN Cpanel/Validate/EmailLocalPart.pm
package Cpanel::Validate::EmailLocalPart;
use strict; #not for production -- passes
# use Cpanel::StringFunc::Case ();
# use Cpanel::StringFunc::Trim ();
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);
@reserved_localparts{@reserved_localparts_list} = (1) x scalar @reserved_localparts_list;
{
no warnings 'redefine';
*_init = sub { };
}
}
sub is_valid {
return defined $_[0] && $_[0] =~ /^[a-zA-Z0-9!#\$\-=?^_{}~]+(?:\.[a-zA-Z0-9!#\$\-=?^_{}~]+)*$/;
}
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); # To match usage in addpop
return $name;
}
sub get_name_and_domain {
my ($name) = @_;
return unless defined $name;
return split( /@/, $name, 2 );
}
sub scrub {
my ($name) = @_;
return unless defined $name;
$name = normalize($name);
$name =~ tr/^a-zA-Z0-9!#\$\-=?^_{}~.//cd;
$name =~ s/\.\.+/./g;
return if 0 == length $name;
return $name;
}
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.pm
package Cpanel::WildcardDomain;
use strict;
our $PREFIX = '_wildcard_';
my $old_prefix = 'wildcard_safe';
sub encode_wildcard_domain {
return $_[0] if index( $_[0], '*' ) == -1;
my ($domain) = @_;
$domain =~ s/^\*\./$PREFIX./;
return $domain;
}
sub encode_legacy_wildcard_domain {
return $_[0] if index( $_[0], '*' ) == -1;
my ($domain) = @_;
$domain =~ s{\A\*\.}{$old_prefix\.};
return $domain;
}
sub decode_wildcard_domain {
return $_[0] if index( $_[0], '_' ) == -1;
my ($domain) = @_;
$domain =~ s/^(?:$PREFIX|$old_prefix)\./*./;
return $domain;
}
sub strip_wildcard {
my ($domain) = @_;
$domain =~ s{\A(?:\*|$PREFIX|$old_prefix)\.}{};
return $domain;
}
sub is_wildcard_domain {
return ( index( $_[0], '*.' ) == 0 ? 1 : 0 );
}
sub safe_domain {
my $domain = shift;
return unless defined $domain;
return encode_wildcard_domain($domain) if is_wildcard_domain($domain);
return $domain;
}
sub wildcard_domains_match {
my ( $domain_1, $domain_2 ) = @_;
return 1 if $domain_1 eq $domain_2;
return 0 if ( $domain_1 =~ tr/\.// ) != ( $domain_2 =~ tr/\.// );
if ( substr( $domain_1, 0, 2 ) eq '*.' ) {
return 1 if substr( $domain_1, 1 ) eq substr( $domain_2, index( $domain_2, '.' ) );
}
elsif ( substr( $domain_2, 0, 2 ) eq '*.' ) {
return 1 if substr( $domain_2, 1 ) eq substr( $domain_1, index( $domain_1, '.' ) );
}
return 0;
}
1; # Magic true value required at end of module
} # --- END Cpanel/WildcardDomain.pm
{ # --- BEGIN Cpanel/Validate/EmailCpanel.pm
package Cpanel::Validate::EmailCpanel;
# use Cpanel::StringFunc::Case ();
# use Cpanel::StringFunc::Trim ();
# use Cpanel::Validate::EmailLocalPart ();
# use Cpanel::WildcardDomain ();
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 normalize {
my ($name) = @_;
return unless defined $name;
$name =~ s/\0//g;
$name = Cpanel::StringFunc::Trim::ws_trim($name);
my ( $local, $domain ) = get_name_and_domain($name);
return $name unless defined $local and defined $domain;
$local = Cpanel::Validate::EmailLocalPart::normalize($local);
$domain = Cpanel::StringFunc::Case::ToLower($domain);
return "$local\@$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::is_wildcard_domain($domain);
return scalar $domain =~ m/^[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?(?:\.[\da-zA-Z](?:[-\da-zA-Z]*[\da-zA-Z])?)*$/;
}
sub scrub {
my ($name) = @_;
return unless defined $name;
$name = normalize($name);
my ( $user, $domain ) = get_name_and_domain($name);
return unless defined $user and defined $domain;
$user = Cpanel::Validate::EmailLocalPart::scrub($user);
$domain = Cpanel::StringFunc::Case::ToLower($domain);
$domain =~ tr/a-z0-9\-.//cd;
$domain =~ s/\.+/./g;
return "$user\@$domain";
}
1;
} # --- END Cpanel/Validate/EmailCpanel.pm
{ # --- BEGIN Cpanel/Validate/IP.pm
package Cpanel::Validate::IP;
use strict;
sub is_valid_ipv4 { ##no critic qw(RequireArgUnpacking)
return unless $_[0]; # False scalars are never an _[0].
my @segments = split /\./, $_[0], -1;
return if ( !length $segments[3] || $segments[3] =~ tr/0-9//c || $segments[3] > 255 );
return if ( !length $segments[2] || $segments[2] =~ tr/0-9//c || $segments[2] > 255 );
return if ( !length $segments[1] || $segments[1] =~ tr/0-9//c || $segments[1] > 255 );
return if ( !length $segments[0] || !$segments[0] || $segments[0] =~ tr/0-9//c || $segments[0] > 255 );
return 4 == scalar @segments;
}
sub is_valid_cidr4 {
my ($ip) = @_;
return unless defined $ip && $ip;
my ( $ip4, $mask ) = split /\//, $ip;
return if !defined $mask || !length $mask || $mask =~ m/[^0-9]/;
return is_valid_ipv4($ip4) && 0 < $mask && $mask <= 32;
}
sub is_valid_ipv6 {
my ($ip) = @_;
return unless defined $ip && $ip;
return if $ip =~ /^:[^:]/ || $ip =~ /[^:]:$/; # 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 ( $seg[-1] =~ tr/.// ) {
return unless 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 unless $mask =~ m/\A\d+\z/;
return is_valid_ipv6($ip6) && 0 < $mask && $mask <= 128;
}
sub is_valid_ip {
return unless defined $_[0];
return $_[0] =~ tr/:// ? is_valid_ipv6(@_) : is_valid_ipv4(@_);
}
sub ip_version {
return 4 if 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{/}{} ? is_valid_cidr4(@_) : is_valid_ipv4(@_);
}
1;
} # --- END Cpanel/Validate/IP.pm
{ # --- BEGIN Cpanel/Validate/Domain/Tiny.pm
package Cpanel::Validate::Domain::Tiny;
use strict;
# use Cpanel::Logger ();
# use Cpanel::Validate::IP ();
my $logger;
sub validdomainname {
my ( $domainname, $quiet ) = @_;
if ( Cpanel::Validate::IP::is_valid_ip($domainname) ) {
$logger ||= Cpanel::Logger->new();
$logger->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 ) {
$logger ||= Cpanel::Logger->new();
$logger->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 ) {
$logger ||= Cpanel::Logger->new();
$logger->warn( $domainname . ' domain name must have a valid TLD label' ) if !$quiet;
return wantarray ? ( 0, 'domain name must have a valid TLD label' ) : 0;
}
my $label_regex1 = qr{
\A
[a-z0-9]
[a-z0-9-]*
[a-z0-9]
\z
}xmsi;
my $label_regex2 = qr{
\A
[a-z0-9]
\z
}xmsi;
my @namearray = split( /\./, $domainname );
if ( scalar @namearray < 2 ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("invalid domain name $domainname") if !$quiet;
return wantarray ? ( 0, "invalid domain name $domainname" ) : 0;
}
LABELS_LOOP:
foreach my $label (@namearray) {
if ( length($label) < 64
&& length($label) > 0
&& ( $label =~ $label_regex1 || $label =~ $label_regex2 ) ) {
next LABELS_LOOP;
}
$logger ||= Cpanel::Logger->new();
$logger->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/Encoder/Punycode.pm
package Cpanel::Encoder::Punycode;
our $VERSION = '1.0';
# use Cpanel::LoadModule ();
sub _idn_to_ascii ($;$$) {
Cpanel::LoadModule::load_perl_module('Net::LibIDN');
my $coderef = 'Net::LibIDN'->can('idn_to_ascii');
no warnings 'redefine';
*_idn_to_ascii = $coderef;
return $coderef->(@_);
}
sub _idn_to_unicode ($;$$) {
Cpanel::LoadModule::load_perl_module('Net::LibIDN');
my $coderef = 'Net::LibIDN'->can('idn_to_unicode');
no warnings 'redefine';
*_idn_to_unicode = $coderef;
return $coderef->(@_);
}
sub punycode_encode_str {
my ($string) = $_[0];
if ( $string =~ m/\@/ ) {
my ( $nam, $dom ) = split( /@/, $string, 2 );
return _idn_to_ascii( $nam, 'utf-8' ) . '@' . _idn_to_ascii( $dom, 'utf-8' );
}
return _idn_to_ascii( $string, 'utf-8' );
}
sub punycode_decode_str {
my ($string) = $_[0];
if ( $string =~ m/\@/ ) {
my ( $nam, $dom ) = split( /@/, $string, 2 );
return _idn_to_unicode( $nam, 'utf-8' ) . '@' . _idn_to_unicode( $dom, 'utf-8' );
}
return _idn_to_unicode( $string, 'utf-8' );
}
1;
} # --- END Cpanel/Encoder/Punycode.pm
{ # --- BEGIN Cpanel/Validate/Hostname.pm
package Cpanel::Validate::Hostname;
our $VERSION = 1.0;
sub is_valid {
my $domain = shift;
if ( $domain =~ m/\s+/ ) {
return;
}
if ( $domain =~ m/[.]{2,}/ ) {
return;
}
if ( $domain =~ m/[.]$/ ) {
return;
}
if ( $domain =~ m/[-](?=[.]|\z)/ ) {
return;
}
if ( length $domain > 255 ) {
return;
}
if ( $domain =~ /^(?:[a-z0-9][a-z0-9\-]*\.){2,}[a-z0-9][a-z0-9\-]*$/i ) {
return 1;
}
return;
}
1;
} # --- END Cpanel/Validate/Hostname.pm
{ # --- BEGIN Cpanel/Sys/Hostname.pm
package Cpanel::Sys::Hostname;
use strict;
our $VERSION = 1.2;
# use Cpanel::Sys::Uname ();
our $cachedhostname = '';
my $logger;
sub validhostname {
require Cpanel::Validate::Hostname;
goto \&Cpanel::Validate::Hostname::is_valid;
}
sub gethostname {
my $nocache = shift || 0;
if ( !$nocache && $cachedhostname ne '' ) { return $cachedhostname }
my $hostname = _gethostname();
if ( defined($hostname) && $hostname ne '' ) {
$hostname =~ tr{A-Z}{a-z}; # hostnames must be lowercase (see Cpanel::Sys::Hostname::make_hostname_lowercase)
$cachedhostname = $hostname;
}
return $hostname;
}
sub _gethostname {
my $hostname;
my @uname = Cpanel::Sys::Uname::get_uname_cached();
if ( $uname[1] ) {
$hostname = $uname[1];
$hostname =~ tr{A-Z}{a-z}; # hostnames must be lowercase (see Cpanel::Sys::Hostname::make_hostname_lowercase)
return $hostname;
}
if ( $^O =~ /linux/i ) {
require Cpanel::LoadFile;
chomp( $hostname = Cpanel::LoadFile::loadfile( '/proc/sys/kernel/hostname', { 'skip_exists_check' => 1 } ) );
$hostname =~ tr{A-Z}{a-z}; # hostnames must be lowercase (see Cpanel::Sys::Hostname::make_hostname_lowercase)
if ($hostname) { return $hostname; }
}
_logger()->warn('Unable to determine correct hostname');
return;
}
sub shorthostname {
my $hostname = gethostname() || return;
my $shorthost = ( split( /\./, $hostname ) )[0];
return $shorthost;
}
sub _replace_file_content {
my ( $conf_file, $coderef ) = @_;
if ( -f $conf_file && open my $fh, '+<', $conf_file ) {
local $/;
local $_ = <$fh>;
local $SIG{'__DIE__'} = 'DEFAULT'; # protection from global sigDIE handler.
eval {
$coderef->();
seek( $fh, 0, 0 );
print $fh $_;
truncate( $fh, tell($fh) );
1;
} or do {
_logger()->warn("Failed to update '$conf_file': $@");
return;
};
}
else {
_logger()->warn("Unable to change current host name in '$conf_file'");
return;
}
return 1;
}
sub _set_host_name_in_config_file {
my ( $new_host_name, $os ) = @_;
$os ||= Cpanel::Sys::GetOS::getos();
if ( $os !~ m/^(?:centos|cloudlinux|redhat|amazon)$/i ) {
_logger()->warn("Unrecognized os '$os', cannot update host name");
return;
}
return _replace_file_content(
'/etc/sysconfig/network',
sub {
unless (s/^\s*HOSTNAME\s*=.*?$/HOSTNAME=$new_host_name/m) {
$_ .= "HOSTNAME=$new_host_name\n";
}
}
);
}
sub make_hostname_lowercase {
if ( $< != 0 ) {
_logger()->warn("Only root can change the host name");
return;
}
my $hostname = _gethostname();
if ( !defined $hostname || !length $hostname ) {
_logger()->warn("Unable to retrieve current hostname");
return;
}
return 1 unless $hostname =~ tr/A-Z/a-z/;
if ( _set_host_name_in_config_file($hostname) ) {
Cpanel::SafeRun::Simple::saferun( 'hostname', $hostname );
}
$cachedhostname = '';
return 1;
}
sub _logger {
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
return $logger;
}
1;
} # --- END Cpanel/Sys/Hostname.pm
{ # --- BEGIN Cpanel/Validate/Domain.pm
package Cpanel::Validate::Domain;
use strict;
our $VERSION = '1.0';
# use Cpanel::Encoder::Punycode ();
# use Cpanel::Exception ();
# use Cpanel::Logger ();
# use Cpanel::StringFunc::Case ();
# use Cpanel::StringFunc::Trim ();
# use Cpanel::Sys::Hostname ();
# use Cpanel::Validate::Domain::Tiny ();
my $logger;
*validdomainname = \&Cpanel::Validate::Domain::Tiny::validdomainname;
sub valid_wild_domainname {
my ( $domain, $quiet ) = @_;
return validdomainname( $domain, $quiet ) unless $domain =~ /^\*\./;
return validdomainname( substr( $domain, 2 ), $quiet );
}
sub valid_wild_domainname_or_die {
my ($domain) = @_;
my ( $ok, $why ) = valid_wild_domainname( $domain, 1 ); #1 to make it not log->warn
if ( !$ok ) {
die Cpanel::Exception::create( 'DomainNameNotRfcCompliant', { given => $domain, why => $why } );
}
return 1;
}
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 'darkorb.net'
|| $_[0] =~ m/\.(?:cpanel\.net|darkorb\.net)$/i;
}
sub is_disallowed_domain {
return $_[0] eq 'ruby-on-rails.db'
|| $_[0] eq 'ruby-on-rails-rewrites.db';
}
sub has_disallowed_tld {
return $_[0] =~ m/\.(?:cache|yaml|stor|json|bkup2?|offset)$/i;
}
sub is_valid_cpanel_domain { ##no critic qw(RequireArgUnpacking)
my $domain = $_[0];
my $quiet = 1;
my ( $result, $reason ) = 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 ( scalar @_ >= 2 ) {
$_[1] = $reason;
}
return $result;
}
sub validwildcarddomain {
my ($domainname) = @_;
return validdomainname($domainname) if $domainname !~ m/\*/;
if ( is_valid_wildcard_domain($domainname) ) {
$domainname =~ s/\*/a/g; #replace * with a for validdomainname to understand this
return 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 normalize {
my ( $domain, $quiet ) = @_;
if ( !defined $domain ) {
return;
}
$quiet ||= 0;
$domain = _just_normalize($domain);
if ( !$quiet && !validdomainname($domain) ) {
my $logger = Cpanel::Logger->new();
$logger->info("Invalid domain $domain specified.");
}
return $domain;
}
sub normalize_wildcard {
my ($domain) = @_;
die "Domain is missing!" if !length $domain;
return _just_normalize($domain);
}
sub _just_normalize {
my ($domain) = @_;
$domain = Cpanel::StringFunc::Case::ToLower( Cpanel::StringFunc::Trim::ws_trim($domain) );
return Cpanel::Encoder::Punycode::punycode_encode_str($domain);
}
sub normalize_to_root_domain {
my ($domain) = @_;
return undef unless defined $domain;
$domain = normalize($domain);
$domain =~ s/\*\.?//;
$domain =~ s/^www\.//g;
return $domain;
}
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) ) {
die Cpanel::Exception::create( 'InvalidParameter', 'The username validation routine received an empty username.' );
}
if ( length($full_username) > 254 ) {
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 ) {
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) ) {
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) ) {
die Cpanel::Exception::create( 'InvalidParameter', 'The domain “[_1]” for user “[_2]” is invalid.', [ $domain, $full_username ] );
}
}
else {
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 or !length $full_username ) {
die Cpanel::Exception::create( 'InvalidParameter', 'You must specify a username.' );
}
my ($local_part) = split /\@/, $full_username, 2;
if ( $local_part !~ m{^[a-zA-Z0-9.\-_]*$} ) { # allow empty since the VirtualUsername validation will catch that
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/Env.pm
package Cpanel::Env;
use strict;
our $VERSION = '1.6';
my %SAFE_ENV_VARS;
sub _populate_safe_env_vars {
%SAFE_ENV_VARS = map { $_ => undef } (
'ALLUSERSPROFILE',
'APPDATA',
'CLIENTNAME',
'COMMONPROGRAMFILES',
'COMPUTERNAME',
'COMSPEC',
'CPANEL_IS_CRON', # Denotes that one of the parent procs is upcp
'CPANEL_BASE_INSTALL', # Used to indicate new install process
'DOCUMENT_ROOT',
'FP_NO_HOST_CHECK',
'HOMEDRIVE',
'HOMEPATH',
'LOGONSERVER',
'NEWWHMUPDATE',
'NUMBER_OF_PROCESSORS',
'OPENSSL_NO_DEFAULT_ZLIB', # Case 63084
'OS',
'PATH',
'PATHEXT',
'PROCESSOR_ARCHITECTURE',
'PROCESSOR_IDENTIFIER',
'PROCESSOR_LEVEL',
'PROCESSOR_REVISION',
'PROGRAMFILES',
'PROMPT',
'SERVER_SOFTWARE',
'SESSIONNAME',
'SSH_CLIENT',
'SYSTEMDRIVE',
'SYSTEMROOT',
'TEMP',
'TERM',
'TMP',
'UPDATENOW_NO_RETRY',
'UPDATENOW_PRESERVE_FAILED_FILES',
'USERDOMAIN',
'USERNAME',
'USERPROFILE',
'WINDIR',
);
return;
}
sub clean_env {
my (@args) = @_;
my @old_safe_env_vars = %SAFE_ENV_VARS;
_populate_safe_env_vars();
cleanenv(@args);
%SAFE_ENV_VARS = @old_safe_env_vars;
return;
}
sub cleanenv {
my %OPTS = @_;
_populate_safe_env_vars() if !%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 set_safe_path {
$ENV{'PATH'} = '/usr/local/jdk/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/lib/courier-imap/sbin:/usr/lib/courier-imap/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';
}
1;
} # --- END Cpanel/Env.pm
{ # --- BEGIN Cpanel/ReadMultipleFH.pm
package Cpanel::ReadMultipleFH;
use strict;
# use Cpanel::FHUtils::Blocking ();
my $CHUNK_SIZE = 2 << 16;
my $DEFAULT_TIMEOUT = 600; #10 minutes
my $DEFAULT_READ_TIMEOUT = 0;
sub new {
my ( $class, %opts ) = @_;
my %fh_buffer;
my %output;
my @fhs = @{ $opts{'filehandles'} };
my $read_input = '';
my $read_output = '';
my %fhmap;
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 ( UNIVERSAL::isa( $fh_buf_ar->[1], 'SCALAR' ) ) {
$fh_buffer{$fh} = $fh_buf_ar->[1];
}
else {
my $buf = q{};
$fh_buffer{$fh} = \$buf;
if ( UNIVERSAL::isa( $fh_buf_ar->[1], 'GLOB' ) ) {
$output{$fh} = $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;
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 ( keys %fhmap ) {
next if !vec( $read_output, $fileno, 1 ); # data ready on fileno
my $fh = $fhmap{$fileno};
sysread( $fh, ${ $fh_buffer{$fh} }, $CHUNK_SIZE, length ${ $fh_buffer{$fh} } ) or do {
if ($!) {
warn "read from child failed: $!";
}
delete $fhmap{$fileno};
vec( $read_input, $fileno, 1 ) = 0;
$finished = !( scalar keys %fhmap );
next;
};
if ( $output{$fh} ) {
print { $output{$fh} } substr( ${ $fh_buffer{$fh} }, 0, length ${ $fh_buffer{$fh} }, q<> );
}
}
}
$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 );
if ( ( !$read_timeout || $overall_time_left <= $read_timeout ) ) {
return $overall_time_left;
}
else {
return $read_timeout;
}
}
sub get_buffer {
my ( $self, $fh ) = @_;
return $self->{'_fh_buffer'}{$fh};
}
sub did_finish {
my ($self) = @_;
return $self->{'_finished'} ? 1 : 0;
}
sub timed_out {
my ($self) = @_;
return defined $self->{'_timed_out'} ? $self->{'_timed_out'} : 0;
}
1;
} # --- END Cpanel/ReadMultipleFH.pm
{ # --- BEGIN Cpanel/Kill/Single.pm
package Cpanel::Kill::Single;
use strict;
# use Cpanel::TimeHiRes ();
our $SAFEKILL_TIMEOUT = 10; # in seconds;
sub safekill_single_pid {
my ( $pid, $timeout ) = @_;
kill 'TERM', $pid;
$timeout ||= $SAFEKILL_TIMEOUT;
my $start = Cpanel::TimeHiRes::time();
my $end = $start + $timeout;
my $ret;
local $?;
while ( Cpanel::TimeHiRes::time() < $end ) {
my $kill = kill( 0, $pid );
if ( $kill <= 0 ) { # 'ZERO' does not work under perl 5.6
if ( waitpid( $pid, 0 ) ) {
$ret = $? if !defined $ret && $? != -1;
}
return $ret;
}
elsif ( Cpanel::TimeHiRes::time() < $start + 1 ) {
waitpid( $pid, 1 ); # in case its a child of us and in zombie state
$ret = $? if !defined $ret && $? != -1;
Cpanel::TimeHiRes::sleep(0.1);
}
else {
waitpid( $pid, 1 ); # in case its a child of us and in zombie state
$ret = $? if !defined $ret && $? != -1;
Cpanel::TimeHiRes::sleep(1);
}
}
kill 'KILL', $pid;
waitpid( $pid, 0 ); # in case its a child of us and in zombie state
$ret = $? if !defined $ret && $? != -1;
return $ret;
}
1;
} # --- END Cpanel/Kill/Single.pm
{ # --- BEGIN Cpanel/SafeRun/Object.pm
package Cpanel::SafeRun::Object;
use strict;
# use Cpanel::ChildErrorStringifier();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::ChildErrorStringifier); }
use Try::Tiny;
use IO::Handle ();
# use Cpanel::Carp ();
# use Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase ();
# use Cpanel::Env ();
# use Cpanel::Exception ();
# use Cpanel::ForkAsync ();
# use Cpanel::PwCache ();
# use Cpanel::ReadMultipleFH ();
# use Cpanel::Kill::Single ();
my $CHUNK_SIZE = 2 << 16;
my $DEFAULT_TIMEOUT = 3600; # 1 hour
my $DEFAULT_READ_TIMEOUT = 0;
sub new {
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;
}
my $args_ar = $OPTS{'args'} || [];
die "“args” must be an arrayref" if defined $args_ar && ref $args_ar ne 'ARRAY';
my $pump_stdin_filehandle_into_child;
my ( %parent_read_fh, %child_write_fh );
my %custom_output_filehandle;
for my $handle_name (qw(stdout stderr)) {
my $custom_fh = 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) {
$child_write_fh{$handle_name} = $OPTS{$handle_name};
}
else {
$parent_read_fh{$handle_name} = IO::Handle->new();
$child_write_fh{$handle_name} = IO::Handle->new();
pipe $parent_read_fh{$handle_name}, $child_write_fh{$handle_name} or die Cpanel::Exception::create( 'IO::PipeError', { error => $! } );
}
}
my ( $child_reads, $parent_writes );
local $!;
if ( !$OPTS{'stdin'} ) {
open $child_reads, '<', '/dev/null' or die "open(<, /dev/null) failed: $!";
}
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 ) {
pipe( $child_reads, $parent_writes ) or die "pipe() failed: $!";
}
my $self = {
_program => $OPTS{'program'},
_args => $OPTS{'args'},
};
bless $self, $class;
local $SIG{'CHLD'} = 'DEFAULT';
$self->{'_child_pid'} = Cpanel::ForkAsync::do_in_child(
sub {
$SIG{'__DIE__'} = 'DEFAULT';
for ( values %parent_read_fh ) {
close $_ or die "close() 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)
}
Cpanel::Env::clean_env();
if ( $OPTS{'before_exec'} ) {
$OPTS{'before_exec'}->();
}
my ( $user, $homedir ) = ( Cpanel::PwCache::getpwuid($>) )[ 0, 7 ];
die "Invalid EUID: $>" if !$user || !$homedir;
$ENV{'HOME'} = $homedir if !defined $ENV{'HOME'};
$ENV{'USER'} = $user if !defined $ENV{'USER'};
$ENV{'TMP'} = "$homedir/tmp" if !defined $ENV{'TMP'};
$ENV{'TEMP'} = "$homedir/tmp" if !defined $ENV{'TEMP'};
exec( { $OPTS{'program'} } $OPTS{'program'}, @$args_ar ) or die "exec($OPTS{'program'}) failed: $!";
}
);
if ( $OPTS{'after_fork'} ) {
$OPTS{'after_fork'}->( $self->{'_child_pid'} );
}
close $child_reads or die "close() failed: $!";
for my $handle_name (qw(stdout stderr)) {
if ( $parent_read_fh{$handle_name} ) {
close $child_write_fh{$handle_name} or die "close() failed: $!";
}
}
if ($parent_writes) {
if ($pump_stdin_filehandle_into_child) {
my $buffer;
local $!;
while ( read $OPTS{'stdin'}, $buffer, $CHUNK_SIZE ) {
print {$parent_writes} $buffer or die $self->_write_error( \$buffer, "$!" );
}
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", "$!" ] );
}
}
elsif ( ref $OPTS{'stdin'} eq 'CODE' ) {
$OPTS{'stdin'}->($parent_writes);
}
else {
my $to_print_r = ( ref $OPTS{'stdin'} eq 'SCALAR' ) ? $OPTS{'stdin'} : \$OPTS{'stdin'};
if ( length $$to_print_r ) {
print {$parent_writes} $$to_print_r or die $self->_write_error( $to_print_r, "$!" );
}
}
close $parent_writes or die "close() failed: $!";
}
my $reader;
my $err_obj;
my @filehandles = map { $parent_read_fh{$_} ? [ $parent_read_fh{$_}, $OPTS{$_} ] : () } qw( stdout stderr );
if (@filehandles) {
try {
$reader = Cpanel::ReadMultipleFH->new(
filehandles => \@filehandles,
timeout => $OPTS{'timeout'},
read_timeout => $OPTS{'read_timeout'},
);
}
catch {
$err_obj = $_;
};
}
for ( values %parent_read_fh ) {
close $_ or warn "close() 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();
}
for my $handle_name (qw(stdout stderr)) {
$self->{"_$handle_name"} = $parent_read_fh{$handle_name} && $reader->get_buffer( $parent_read_fh{$handle_name} );
}
}
if ( !defined $self->{'_CHILD_ERROR'} ) {
local $?;
waitpid( $self->{'_child_pid'}, 0 );
$self->{'_CHILD_ERROR'} = $?;
}
return $self;
}
sub new_or_die {
my ( $class, @args ) = @_;
return $class->new(@args)->die_if_error();
}
sub _extra_error_args_for_die_if_error {
my ($self) = @_;
return (
stdout => $self->stdout(),
stderr => $self->stderr(),
);
}
sub _safe_kill_child {
my ($self) = @_;
return Cpanel::Kill::Single::safekill_single_pid( $self->{'_child_pid'}, 1 ); # One second to die
}
sub stdout_r {
my ($self) = @_;
die Cpanel::Carp::safe_longmess("STDOUT output went to filehandle!") if !$self->{'_stdout'};
return $self->{'_stdout'};
}
sub _add_additional_phrases_to_autopsy {
my ( $self, $localize_ref ) = @_;
$self->SUPER::_add_additional_phrases_to_autopsy($localize_ref);
if ( $self->timed_out() ) {
push @{$localize_ref}, [ Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The process was aborted because it reached the timeout of [quant,_1,second,seconds].'), $self->timed_out() ];
}
return;
}
sub stdout {
my ($self) = @_;
return ${ $self->stdout_r() };
}
sub stderr_r {
my ($self) = @_;
die Cpanel::Carp::safe_longmess("STDERR output went to filehandle!") if !$self->{'_stderr'};
return $self->{'_stderr'};
}
sub stderr {
my ($self) = @_;
return ${ $self->stderr_r() };
}
sub child_pid {
my ($self) = @_;
return $self->{'_child_pid'};
}
sub timed_out {
my ($self) = @_;
return $self->{'_timed_out_after'};
}
sub program {
my ($self) = @_;
return $self->{'_program'};
}
sub _PROGRAM_ERROR_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The “[_1]” command (process [_3]) reported error number [numf,_2] when it ended.');
}
sub _EXTRA_ERROR_PHRASE_ARGUMENTS {
my ($self) = @_;
return (
$self->{'_child_pid'},
);
}
sub _SIGNAL_PHRASE {
return Cpanel::CPAN::Locale::Maketext::Utils::MarkPhrase::translatable('The “[_3]” command (process [_4]) ended prematurely because it received the “[_1]” ([_2]) signal.');
}
*_EXTRA_SIGNAL_PHRASE_ARGUMENTS = \&_EXTRA_ERROR_PHRASE_ARGUMENTS;
sub _write_error {
my ( $self, $buffer_sr, $OS_ERROR ) = @_;
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), "$self->{'_program'} @{$self->{'_args'}}", $OS_ERROR ] );
}
1;
} # --- END Cpanel/SafeRun/Object.pm
{ # --- BEGIN Cpanel/LoginDefs.pm
package Cpanel::LoginDefs;
use strict;
use IO::Handle ();
# use Cpanel::Exception ();
our $logindefs = q{/etc/login.defs};
{
my $_cache = {};
sub get_uid_min {
return _get_cache( 'UID_MIN', 500 );
}
sub get_uid_max {
return _get_cache( 'UID_MAX', 60000 );
}
sub get_gid_min {
return _get_cache( 'GID_MIN', 500 );
}
sub get_gid_max {
return _get_cache( 'GID_MAX', 60000 );
}
sub get_sys_uid_min {
return _get_cache( 'SYS_UID_MIN', 201 );
}
sub get_sys_uid_max {
return _get_cache( 'SYS_UID_MAX', get_uid_min() - 1 );
}
sub get_sys_gid_min {
return _get_cache( 'SYS_GID_MIN', 201 );
}
sub get_sys_gid_max {
return _get_cache( 'SYS_GID_MAX', get_gid_min() - 1 );
}
sub _get_cache {
my ( $k, $default ) = @_;
return $_cache->{$k} if defined $_cache->{$k};
$_cache->{$k} = int( get_value_for($k) || 0 ) || $default;
return $_cache->{$k};
}
sub _clear_cache {
$_cache = {};
return;
}
}
sub get_value_for {
my $want = shift or return;
my $fh = IO::Handle->new;
open( $fh, '<', $logindefs )
or die Cpanel::Exception::create( 'IO::FileReadError', { path => $logindefs, error => $! } );
while ( my $line = <$fh> ) {
chomp $line;
$line =~ s/^\s+|\s+$//g;
next if $line =~ m/^#/;
next if length($line) == 0;
my ( $key, $value ) = split( /\s+/, $line );
if ( $key && $key eq $want ) {
close($fh);
return $value;
}
}
close($fh);
return;
}
1;
} # --- END Cpanel/LoginDefs.pm
{ # --- BEGIN Cpanel/Config/LoadWwwAcctConf.pm
package Cpanel::Config::LoadWwwAcctConf;
use strict;
# use Cpanel::Logger ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::SafeFile ();
# use Cpanel::Debug ();
# use Cpanel::LoginDefs ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# 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'} && !grep( /:nostorable/, @_ ) ) {
Cpanel::JSON::FailOK::LoadJSONModule();
}
if ( $INC{'Cpanel/JSON.pm'} ) {
$has_serializer = 1;
}
my @imports = grep( !/:nostorable/, @_ );
Exporter::import( $this, @imports );
}
sub loadwwwacctconf {
if ( $INC{'Cpanel/JSON.pm'} ) { $has_serializer = 1; } #something else loaded it
my $filesys_mtime = ( 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";
if ($has_serializer) {
my $cache_file;
my $cache_filesys_mtime;
my $have_valid_cache = 1;
if ( $> == 0 && -r $wwwacctconfshadow_cache ) {
$cache_filesys_mtime = ( stat(_) )[9]; #shadow cache's mtime
my $shadow_file_mtime = ( 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 ( -r $wwwacctconf_cache && !( $> == 0 && -r $wwwacctconfshadow ) ) {
$cache_filesys_mtime = ( stat $wwwacctconf_cache )[9]; #regular cache's mtime
$cache_file = $wwwacctconf_cache;
}
else {
$have_valid_cache = undef;
}
my $now = 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 ( -r $wwwacctconfshadow ) { 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 ( $> == 0 && $has_serializer ) {
$can_write_cache = 1;
}
my %CONF = (
'ADDR' => undef,
'CONTACTEMAIL' => undef,
'DEFMOD' => undef,
'ETHDEV' => undef,
'HOST' => undef,
'NS' => undef,
'NS2' => undef,
);
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{'HOMEDIR'} =~ s{/+$}{} if defined $CONF{'HOMEDIR'}; # Remove trailing slashes
if ($can_write_cache) {
my $cache_file = $configfile . '.cache';
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/iContact/Email.pm
package Cpanel::iContact::Email;
use strict;
use Try::Tiny;
# use Cpanel::Email::Object ();
# use Cpanel::Exception ();
# use Cpanel::Logger ();
# use Cpanel::Autodie ();
# use Cpanel::SafeRun::Object ();
our $DEFAULT_CONTENT_TYPE = 'text/plain';
sub write_email_to_fh {
my ( $sendmail_fh, %OPTS ) = @_;
_convert_attach_files_to_attachments( \%OPTS );
my $email = Cpanel::Email::Object->new(%OPTS);
try {
$email->print($sendmail_fh);
}
catch {
my $err = $_;
my $err_str = Cpanel::Exception::get_string($err);
Cpanel::Logger->new()->warn("Error while writing email: $err_str");
};
return;
}
sub _convert_attach_files_to_attachments {
my ($email_args_hr) = @_;
for my $file ( @{ $email_args_hr->{'attach_files'} } ) {
my $attachment_hr;
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::Logger->new()->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::Logger->new()->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/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/NAT/Object.pm
package Cpanel::NAT::Object;
use strict;
use warnings;
# use Cpanel::Logger ();
# use Cpanel::Validate::IP ();
my $logger = Cpanel::Logger->new();
sub new {
my ( $class, $file ) = @_;
my $self = {
'cpnat_file' => $file || '/var/cpanel/cpnat',
'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->{'cpnat_ordered'} = $self->_create_ordered_list($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'};
}
sub get_public_ip {
my ( $self, $local_ip ) = @_;
return $local_ip unless $local_ip;
return $local_ip if !$self->{'file_read'};
return $local_ip if !$self->{'cpnat_data'}->{$local_ip};
return $self->_get_public_ip($local_ip);
}
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'};
my %reverse_cpnat = reverse %{ $self->{'cpnat_data'} };
return $public_ip if !$reverse_cpnat{$public_ip};
my $local_ip = $reverse_cpnat{$public_ip};
return $local_ip;
}
sub _parse_nat_file {
my ( $self, $nat_data ) = @_;
return if !$nat_data;
my $cpnat_hash = {};
my @file = split /\n/, $nat_data;
foreach my $line (@file) {
my ( $local, $public ) = split /\s+/, $line;
if ( !$public ) {
push @{ $self->{'only_local_ip'} }, $local;
next;
}
if ( !Cpanel::Validate::IP::is_valid_ipv4($local)
&& !Cpanel::Validate::IP::is_valid_ipv4($public) ) {
$logger->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 @{ $group_hash->{$key} }, [ $local, $public ];
push @$order, $key if !grep { $_ eq $key } @$order;
}
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 {
my $local_ip = shift;
return cpnat()->get_public_ip($local_ip);
}
sub get_local_ip {
my $public_ip = shift;
return cpnat()->get_local_ip($public_ip);
}
sub get_public_ip_raw {
my $local_ip = shift;
return cpnat()->get_public_ip_raw($local_ip);
}
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/IP/Collapse.pm
package Cpanel::IP::Collapse;
sub collapse {
my ($ip) = @_;
if ( substr( $ip, 0, 30 ) eq '0000:0000:0000:0000:0000:ffff:' ) {
substr( $ip, 0, 30, '' );
$ip =~ tr/://d;
$ip = join( '.', unpack( 'C8', pack 'H8', $ip ) );
}
$ip;
}
1;
} # --- END Cpanel/IP/Collapse.pm
{ # --- BEGIN Cpanel/IP/Match.pm
package Cpanel::IP::Match;
use strict;
# use Cpanel::IP::Convert ();
*ip_in_prefix = \&ip_is_in_range; #legacy
our %range_cache;
our %ip_bin_cache;
sub ip_is_in_range {
my ( $ip, $range ) = @_;
return 0 unless defined $range && length($range);
my $ip_bin = ( $ip_bin_cache{$ip} ||= Cpanel::IP::Convert::ip2binary_string( Cpanel::IP::Convert::expand_ip( $ip, 6 ) ) );
my ( $range_firstip_bin, $range_lastip_bin ) = @{ ( $range_cache{$range} ||= [ Cpanel::IP::Convert::first_last_ip_in_range($range) ] ) };
return ( ip_binary_string_is_gteq( $ip_bin, $range_firstip_bin ) && ip_binary_string_is_gteq( $range_lastip_bin, $ip_bin ) ? 1 : 0 );
}
sub ips_are_equal {
my ( $first_ip, $second_ip ) = @_;
my $first_ip_bin = Cpanel::IP::Convert::ip2binary_string( Cpanel::IP::Convert::expand_ip( $first_ip, 6 ) );
my $second_ip_bin = Cpanel::IP::Convert::ip2binary_string( Cpanel::IP::Convert::expand_ip( $second_ip, 6 ) );
return 1 if $first_ip_bin eq $second_ip_bin;
return 0;
}
sub ip_binary_string_is_gteq { ##no critic qw(RequireArgUnpacking)
length $_[0] == length $_[1] or die "ip_binary_string_is_gteq can only compare strings of equal length";
return ( $_[0] eq $_[1] || $_[0] gt $_[1] ) ? 1 : 0;
}
1;
} # --- END Cpanel/IP/Match.pm
{ # --- BEGIN Cpanel/Validate/IP/Expand.pm
package Cpanel::Validate::IP::Expand;
use strict;
# use Cpanel::Validate::IP ();
sub normalize_ipv4 {
my $ip = shift;
return unless Cpanel::Validate::IP::is_valid_ipv4($ip);
return join '.', map { $_ + 1 - 1 } split /\./, $ip;
}
sub expand_ipv6 {
my $ip = shift;
return unless Cpanel::Validate::IP::is_valid_ipv6($ip);
my @seg = split /:/, $ip, -1;
$seg[0] = '0000' if !length $seg[0];
$seg[-1] = '0000' if !length $seg[-1];
my $ipv4;
my $embedded_v4 = 0;
if ( $seg[-1] =~ tr{.}{} && Cpanel::Validate::IP::is_valid_ipv4( $seg[-1] ) ) {
my @ipv4 = split /\./, normalize_ipv4( pop @seg );
push @seg, sprintf( '%04x', ( $ipv4[0] << 8 ) + $ipv4[1] );
push @seg, 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) + $embedded_v4 <= 8 ) {
push @exp, '0000';
}
}
else {
push @exp, sprintf( '%04x', hex $seg );
}
}
push @exp, $ipv4 if $embedded_v4;
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+([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 {
my $ip = shift;
return unless defined $ip;
return $ip =~ tr/:// ? normalize_ipv6($ip) : normalize_ipv4($ip);
}
sub expand_ip {
my $ip = shift;
return unless defined $ip;
return $ip =~ tr/:// ? expand_ipv6($ip) : normalize_ipv4($ip);
}
1;
} # --- END Cpanel/Validate/IP/Expand.pm
{ # --- BEGIN Cpanel/IP/Convert.pm
package Cpanel::IP::Convert;
use strict;
# use Cpanel::IP::Collapse ();
# use Cpanel::IP::Match ();
# use Cpanel::Validate::IP ();
# use Cpanel::Validate::IP::Expand ();
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 ip2bin16 {
my ($ip) = @_;
$ip = '::' if !defined $ip or !$ip;
$ip = expand_ip( $ip, 6 );
$ip =~ s/://g;
return pack( 'H32', $ip );
}
sub binip_to_human_readable_ip {
my ($binip) = @_;
return '' unless defined $binip;
if ( length $binip == 16 ) {
return Cpanel::IP::Collapse::collapse( join( ':', unpack( 'H4H4H4H4H4H4H4H4', $binip ) ) );
}
else {
return Cpanel::IP::Collapse::collapse( join( '.', unpack( 'C4C4C4C4', $binip ) ) );
}
}
sub normalize_human_readable_ip {
my ($ip) = @_;
return Cpanel::IP::Convert::binip_to_human_readable_ip( Cpanel::IP::Convert::ip2bin16($ip) );
}
sub expand_ip {
my ( $ip, $version ) = @_;
$ip =~ s/\s//g if defined $ip;
if ( defined $version && $version eq 6 && Cpanel::Validate::IP::is_valid_ipv4($ip) ) {
$ip = "::ffff:$ip";
}
elsif ( !Cpanel::Validate::IP::is_valid_ip($ip) ) {
if ( defined $version && $version eq 6 || $ip =~ m/:/ ) {
return '0000:0000:0000:0000:0000:0000:0000:0000';
}
else {
return '0.0.0.0';
}
}
return Cpanel::Validate::IP::Expand::expand_ip($ip);
}
sub ip_range_to_start_end_address {
my ($ip) = @_;
my ( $start_address, $end_address );
if ( !defined $ip ) {
return;
}
elsif ( $ip =~ m{/} && Cpanel::Validate::IP::is_valid_ip_cidr_or_prefix($ip) ) {
my ( $range_firstip_binary_string, $range_lastip_binary_string ) = first_last_ip_in_range($ip);
$start_address = pack( 'B128', $range_firstip_binary_string );
$end_address = pack( 'B128', $range_lastip_binary_string );
}
elsif ( $ip =~ m{-} ) {
my ( $human_start_address, $human_end_address ) = split( m{\s*-\s*}, $ip, 2 );
if ( Cpanel::Validate::IP::is_valid_ip_cidr_or_prefix($human_start_address) && Cpanel::Validate::IP::is_valid_ip_cidr_or_prefix($human_end_address) ) {
$start_address = ip2bin16($human_start_address);
$end_address = ip2bin16($human_end_address);
}
}
elsif ( Cpanel::Validate::IP::is_valid_ip_cidr_or_prefix($ip) ) {
$start_address = $end_address = ip2bin16($ip);
}
else {
return;
}
return if !length $start_address || !length $end_address;
if ( $start_address ne $end_address && Cpanel::IP::Match::ip_binary_string_is_gteq( unpack( 'B128', $start_address ), unpack( 'B128', $end_address ) ) ) {
return ( $end_address, $start_address ); # fix order
}
return ( $start_address, $end_address );
}
sub start_end_address_to_cidr {
my ( $low, $high ) = @_;
my $mask_length;
my ( $low_bin, $high_bin ) = map { Cpanel::IP::Convert::ip2binary_string($_) } ( $low, $high );
if ( length($low_bin) != length($high_bin) ) {
die "Unmatched low/high IP address lengths: [$low] [$high]";
}
$low_bin =~ m<(0+)\z> or die "low should have at least one trailing 0!";
my $low_zeros_count = length $1;
$high_bin =~ m<(1+)\z> or die "high ($high, $high_bin) should have at least one trailing 1!";
my $high_ones_count = length $1;
if ( $low_zeros_count < $high_ones_count ) {
$mask_length = $low_zeros_count;
}
else {
$mask_length = $high_ones_count;
}
$mask_length = length($low_bin) - $mask_length;
return "$low/$mask_length";
}
sub wildcard_address_to_range {
my ($partial_ip) = @_;
my @partial_quad = split( m{\.}, $partial_ip );
foreach my $quad (@partial_quad) {
if ( $quad !~ m{^[0-9]+$} || $quad < 0 || $quad > 255 ) {
return;
}
}
if ( !scalar @partial_quad || scalar @partial_quad > 4 ) { return; }
while ( scalar @partial_quad < 4 ) { push @partial_quad, undef; }
return ( join( '.', map { defined $_ ? $_ : 0 } @partial_quad ), join( '.', map { defined $_ ? $_ : 255 } @partial_quad ) );
}
sub implied_range_to_full_range {
my ( $partial_ip, $template ) = @_;
my @partial_quad = split( m{\.}, $partial_ip );
return $partial_ip if !length $partial_ip || !length $template;
my @template_quad = split( m{\.}, $template );
if ( scalar @partial_quad == scalar @template_quad || scalar @partial_quad == 4 || !scalar @template_quad ) {
return $partial_ip;
}
splice( @template_quad, -1 * scalar @partial_quad );
return join( '.', @template_quad, @partial_quad );
}
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/Convert.pm
{ # --- BEGIN Cpanel/Linux/Netlink.pm
package Cpanel::Linux::Netlink;
use strict;
use constant DEBUG => 0;
# use Cpanel::Pack ();
my $NETLINK_READ_SIZE = 262144; # Maximum size of netlink message
our $PF_NETLINK = 16;
our $AF_INET = 2;
our $AF_INET6 = 10;
our $NLMSG_ERROR = 0x2;
our $NLMSG_DONE = 0x3;
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;
our $SOCK_DGRAM = 2;
our $TCPDIAG_GETSOCK = 18;
our $INET_DIAG_NOCOOKIE = 0xFFFFFFFF;
our $PACK_TEMPLATE_U32 = 'L';
our $U32_BYTES_LENGTH = 4;
our $PACK_TEMPLATE_U16 = 'S';
our $U16_BYTES_LENGTH = 2;
our $PACK_TEMPLATE_U8 = 'C';
our $U8_BYTES_LENGTH = 1;
our $PACK_TEMPLATE_BE16 = 'n';
our $PACK_TEMPLATE_BE32 = 'N';
my $NLMSG_HEADER_PACK_OBJ;
my $NLMSG_HEADER_PACK_OBJ_SIZE;
my @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
);
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) {
eval 'require Data::Dumper;';
print STDERR "[request]:" . 'Data::Dumper'->can('Dumper')->($message_ref);
}
printf STDERR "Send %v02x\n", $packed_nlmsg if DEBUG;
send( $sock, $packed_nlmsg, 0 ) or die "send: $!";
my ( $header_hr, $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;
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) {
$header_hr = $NLMSG_HEADER_PACK_OBJ->unpack_to_hashref( substr( $packed_response, 0, $header_pack_size, q<> ) );
my $nlmsg_length = $header_hr->{'nlmsg_length'};
print STDERR "Received message with size: [$nlmsg_length]\n" if DEBUG;
last PARSE_LOOP if !$nlmsg_length || length $packed_response < $nlmsg_length - $NLMSG_HEADER_PACK_OBJ_SIZE;
if ( $header_hr->{'nlmsg_type'} == $NLMSG_ERROR ) {
eval 'require Data::Dumper;';
WARN( "Error while reading netlink: " . 'Data::Dumper'->can('Dumper')->($header_hr) );
last READ_LOOP;
}
my $main_msg = substr( $packed_response, 0, $recv_pack_size, '' );
$message_hr = $recv_pack_obj->unpack_to_hashref($main_msg);
if (DEBUG) {
eval 'require Data::Dumper;';
printf STDERR "Received %v02x\n", $main_msg;
print STDERR "[response]:" . 'Data::Dumper'->can('Dumper')->( $header_hr, $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_indicates_finished_reading($header_hr);
$msgcount++;
}
}
$parser->( $msgcount, $message_hr ) if $parser && $header_hr->{'nlmsg_type'};
return 1;
}
sub WARN {
my (@msg) = @_;
return warn(@msg);
}
my @INET_DIAG_SOCKID_TEMPLATE = (
'idiag_sport' => $PACK_TEMPLATE_BE16, #__be16 idiag_sport;
'idiag_dport' => $PACK_TEMPLATE_BE16, #__be16 idiag_dport;
'idiag_src_0' => $PACK_TEMPLATE_BE32, #__be32 idiag_src[0];
'idiag_src_1' => $PACK_TEMPLATE_BE32, #__be32 idiag_src[1];
'idiag_src_2' => $PACK_TEMPLATE_BE32, #__be32 idiag_src[2];
'idiag_src_3' => $PACK_TEMPLATE_BE32, #__be32 idiag_src[3];
'idiag_dst_0' => $PACK_TEMPLATE_BE32, #__be32 idiag_dst[0];
'idiag_dst_1' => $PACK_TEMPLATE_BE32, #__be32 idiag_dst[1];
'idiag_dst_2' => $PACK_TEMPLATE_BE32, #__be32 idiag_dst[2];
'idiag_dst_3' => $PACK_TEMPLATE_BE32, #__be32 idiag_dst[3];
'idiag_if' => $PACK_TEMPLATE_U32, #__u32 idiag_if;
'idiag_cookie_0' => $PACK_TEMPLATE_U32, #__u32 idiag_cookie[0];
'idiag_cookie_1' => $PACK_TEMPLATE_U32, #__u32 idiag_cookie[1];
);
my $INET_DIAG_MSG_PACK_OBJ;
my @INET_DIAG_MSG_TEMPLATE = (
'idiag_family' => $PACK_TEMPLATE_U8, # __u8 idiag_family; /* Family of addresses. */
'idiag_state' => $PACK_TEMPLATE_U8, # __u8 idiag_state;
'idiag_timer' => $PACK_TEMPLATE_U8, # __u8 idiag_timer;
'idiag_retrans' => $PACK_TEMPLATE_U8, # __u8 idiag_retrans;
@INET_DIAG_SOCKID_TEMPLATE, # inet_diag_sockid
'idiag_expires' => $PACK_TEMPLATE_U32, #__u32 idiag_expires;
'idiag_rqueue' => $PACK_TEMPLATE_U32, #__u32 idiag_rqueue;
'idiag_wqueue' => $PACK_TEMPLATE_U32, #__u32 idiag_wqueue;
'idiag_uid' => $PACK_TEMPLATE_U32, #__u32 idiag_uid;
'idiag_inode' => $PACK_TEMPLATE_U32 #__u32 idiag_inode;
);
my $INET_DIAG_REQ_PACK_OBJ;
my @INET_DIAG_REQ_TEMPLATE = (
'idiag_family' => $PACK_TEMPLATE_U8, # __u8 idiag_family; /* Family of addresses. */
'idiag_src_len' => $PACK_TEMPLATE_U8, # __u8 idiag_src_len;
'idiag_dst_len' => $PACK_TEMPLATE_U8, # __u8 idiag_dst_len;
'idiag_ext' => $PACK_TEMPLATE_U8, # __u8 idiag_ext; /* Query extended information */
@INET_DIAG_SOCKID_TEMPLATE, #inet_diag_sockid
'idiag_states' => $PACK_TEMPLATE_U32, #__u32 idiag_states; /* States to dump */
'idiag_dbs' => $PACK_TEMPLATE_U32 #__u32 idiag_dbs; /* Tables to dump (NI) */
);
sub connection_lookup {
my ( $remote_address, $remote_port, $local_address, $local_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 ( $remote_address =~ tr/:// ) {
require Cpanel::IP::Convert; # 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::Convert::expand_ip($remote_address) ) );
( $idiag_src_0, $idiag_src_1, $idiag_src_2, $idiag_src_3 ) = unpack( 'N4', pack( 'n8', split /:/, Cpanel::IP::Convert::expand_ip($local_address) ) );
$idiag_family = $AF_INET6;
}
else {
my $u32_remote_address = unpack( 'N', pack( 'C4', split( /\D/, $remote_address, 4 ) ) );
my $u32_local_address = unpack( 'N', pack( 'C4', split( /\D/, $local_address, 4 ) ) );
$idiag_dst_0 = $u32_local_address;
$idiag_src_0 = $u32_remote_address;
$idiag_family = $AF_INET;
}
die "'peerport' is required" if !defined $local_port;
die "'sockport' is required" if !defined $remote_port;
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' => $local_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' => $remote_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;
}
);
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 {
my ($header_hr) = @_;
return 0 if !length $header_hr->{'nlmsg_type'};
return 1 if $header_hr->{'nlmsg_type'} == $NLMSG_ERROR;
return 1 if ( $header_hr->{'nlmsg_flags'} & $NLM_F_MULTI && $header_hr->{'nlmsg_type'} == $NLMSG_DONE );
return 1 if !( $header_hr->{'nlmsg_flags'} & $NLM_F_MULTI );
return 0;
}
1;
} # --- END Cpanel/Linux/Netlink.pm
{ # --- BEGIN Cpanel/Linux/RtNetlink.pm
package Cpanel::Linux::RtNetlink;
use strict;
use warnings;
# use Cpanel::Linux::Netlink ();
# use Cpanel::Pack ();
# use Cpanel::Socket::Constants ();
use constant DEBUG => 0;
use constant IFA_ADDRESS => 1;
use constant IFA_LOCAL => 2;
use constant IFA_LABEL => 3;
use constant IFA_CACHEINFO => 6;
use constant IFLA_IFNAME => 4;
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 RTATTR_TEMPLATE => 'S a*';
my $INFINITY_LIFE_TIME = 4294967295;
my $RTNETLINK_READ_SIZE = 262144; # was 4096
my $NETLINK_ROUTE_SOCKET = 0;
my $RTM_GETLINK = 18;
my $RTM_GETADDR = 22;
my $PF_NETLINK = 16;
my $IFINFOMSG_PACK_OBJ;
my @IFINFOMSG_TEMPLATE = ( #struct ifinfomsg
'ifi_family' => 'C', # unsigned char ifi_family;
'__ifi_pad' => 'C', # unsigned char __ifi_pad;
'ifi_type' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U16, # unsigned short ifi_type; /* ARPHRD_* */
'ifi_index' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32, # int ifi_index; /* Link index */
'ifi_flags' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32, # unsigned ifi_flags; /* IFF_* flags */
'ifi_change' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32 # unsigned ifi_change; /* IFF_* change mask */
);
my $IFA_CACHEINFO_PACK_OBJ;
my @IFA_CACHEINFO_TEMPLATE = ( #struct ifa_cacheinfo
'ifa_prefered' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32, # __u32 ifa_prefered; # See: https://en,wiktionary,org/wiki/prefered -- It is mispelled upstream
'ifa_valid' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32, # __u32 ifa_valid;
'cstamp' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32, # __u32 cstamp; /* created timestamp, hundredths of seconds */
'tstamp' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32 # __u32 tstamp; /* updated timestamp, hundredths of seconds */
);
my $IFADDRMSG_PACK_OBJ;
my @IFADDRMSG_TEMPLATE = ( # struct ifaddrmsg
'ifa_family' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U8, # __u8 ifa_family;
'ifa_prefixlen' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U8, # __u8 ifa_prefixlen; /* The prefix length */
'ifa_flags' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U8, # __u8 ifa_flags; /* Flags */
'ifa_scope' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U8, # __u8 ifa_scope; /* Address scope */
'ifa_index' => $Cpanel::Linux::Netlink::PACK_TEMPLATE_U32 # __u32 ifa_index; /* Link index */
);
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($address_family);
my $addresses = _get_interface_addresses( $socket, $address_family );
my $interfaces = _get_interfaces( $socket, $address_family );
foreach my $address ( sort { $a->{'scope'} <=> $b->{'scope'} } @{$addresses} ) { # Prefer the largest global scope
return ( $interfaces->[ $address->{'ifindex'} - 1 ], $address->{'ip'} );
}
return;
}
sub get_addresses_by_interface {
my ($address_family) = @_;
$address_family = _address_family_string_to_number($address_family);
my $socket = _make_netlink_socket($address_family);
my $addresses = _get_interface_addresses( $socket, $address_family );
my $interfaces = _get_interfaces( $socket, $address_family );
my %ifcount;
my %combined;
foreach my $address ( @{$addresses} ) {
next if $address->{'scope'} != 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), $address_family );
}
sub get_interface_addresses {
my ($address_family) = @_;
$address_family = _address_family_string_to_number($address_family);
return _get_interface_addresses( _make_netlink_socket($address_family), $address_family );
}
sub _get_interfaces {
my ( $sock, $address_family ) = @_;
my @interfaces;
$IFINFOMSG_PACK_OBJ ||= Cpanel::Pack->new( \@IFINFOMSG_TEMPLATE );
Cpanel::Linux::Netlink::netlink_transaction(
'header' => [
'nlmsg_flags' => $Cpanel::Linux::Netlink::NLM_F_ROOT | $Cpanel::Linux::Netlink::NLM_F_MATCH,
'nlmsg_type' => $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 == IFA_LABEL ) {
$interfaces[ $nl_response_hr->{'ifi_index'} - 1 ] = unpack( 'A*', $value );
}
elsif (DEBUG) {
warn "Unknown rta_type: [$rta_type]";
}
},
),
);
return \@interfaces;
}
sub _make_payload_parser {
my ($for_each_rtmsg_cr) = @_;
return sub {
my ( $nl_msgcount, $nlresponse_hr, $payload_sr ) = ( $_[0], $_[1], \$_[2] );
RTATTR_LOOP:
while ( length $$payload_sr ) {
my $rta_length = unpack(
$Cpanel::Linux::Netlink::PACK_TEMPLATE_U16, # unsigned short rta_len
substr( $$payload_sr, 0, $Cpanel::Linux::Netlink::U16_BYTES_LENGTH, '' ),
);
last RTATTR_LOOP if !$rta_length; # unsigned short rta_len;
$for_each_rtmsg_cr->(
$nl_msgcount,
$nlresponse_hr,
unpack(
RTATTR_TEMPLATE,
substr( $$payload_sr, 0, $rta_length - $Cpanel::Linux::Netlink::U16_BYTES_LENGTH, '' ),
),
);
}
};
}
sub _get_interface_addresses {
my ( $sock, $address_family ) = @_;
my @addresses;
$IFADDRMSG_PACK_OBJ ||= Cpanel::Pack->new( \@IFADDRMSG_TEMPLATE );
$IFA_CACHEINFO_PACK_OBJ ||= Cpanel::Pack->new( \@IFA_CACHEINFO_TEMPLATE );
Cpanel::Linux::Netlink::netlink_transaction(
'header' => [
'nlmsg_type' => $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' };
$addresses[$msgcount]->{'ip'} = ( $address_family == $Cpanel::Linux::Netlink::AF_INET6 ) ? join( ":", unpack( "H4H4H4H4H4H4H4H4", $value ) ) : join( '.', unpack( 'C4', $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'} = unpack( 'A*', $value );
}
elsif (DEBUG) {
warn "Unknown rta_type: [$rta_type]";
}
},
),
);
return \@addresses;
}
sub _make_netlink_socket {
my $address_family = shift || $Cpanel::Linux::Netlink::AF_INET;
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 {
my ($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'} };
}
1;
} # --- END Cpanel/Linux/RtNetlink.pm
{ # --- BEGIN Cpanel/CachedCommand/Utils.pm
package Cpanel::CachedCommand::Utils;
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 =~ s/\//_/g;
$file =~ /(.*)/;
$file = $1;
my $datastore_dir = _get_datastore_dir();
$datastore_dir =~ /(.*)/;
$datastore_dir = $1; #untaint
return $datastore_dir . '/' . $file;
}
sub _get_datastore_dir {
my $myuid = $>;
if ( defined $cached_datastore_dir && length $cached_datastore_dir > 1 && $myuid == $cached_datastore_myuid ) {
return $cached_datastore_dir;
}
if ( $> != 0 && defined $Cpanel::homedir && $Cpanel::homedir ) { #issafe
$cached_datastore_dir = $Cpanel::homedir;
$cached_datastore_dir =~ /(.*)/; #untaint
$cached_datastore_dir = $1;
}
else {
require Cpanel::PwCache;
$cached_datastore_dir = Cpanel::PwCache::gethomedir();
$cached_datastore_dir =~ /(.*)/; #untaint
$cached_datastore_dir = $1;
}
if ( !-e $cached_datastore_dir . '/.cpanel/datastore' ) {
if ( !-e $cached_datastore_dir . '/.cpanel' ) {
mkdir $cached_datastore_dir . '/.cpanel', 0700;
}
mkdir $cached_datastore_dir . '/.cpanel/datastore', 0700;
}
$cached_datastore_myuid = $myuid;
$cached_datastore_dir .= '/.cpanel/datastore';
return $cached_datastore_dir;
}
sub clearcache {
$cached_datastore_dir = undef;
$cached_datastore_myuid = undef;
}
1;
} # --- END Cpanel/CachedCommand/Utils.pm
{ # --- BEGIN Cpanel/IP/Loopback.pm
package Cpanel::IP::Loopback;
sub is_loopback {
return (
length $_[0]
&& (
$_[0] eq 'localhost' #
|| $_[0] eq 'localhost.localdomain' #
|| $_[0] eq '0000:0000:0000:0000:0000:0000:0000:0001' #
|| $_[0] =~ m/^0000:0000:0000:0000:0000:ffff:7f/ # ipv4 inside of ipv6 match 127.*
|| $_[0] =~ m/^::ffff:127\./ # ipv4 inside of ipv6 match 127.*
|| $_[0] =~ m/^127\./ # ipv4 needs to match 127.*
|| $_[0] eq '0:0:0:0:0:0:0:1' #
|| $_[0] eq ':1' #
|| $_[0] eq '::1' #
|| $_[0] eq '(null)' #
|| $_[0] eq '(null):0000:0000:0000:0000:0000:0000:0000' #
|| $_[0] eq '0000:0000:0000:0000:0000:0000:0000:0000' #
|| $_[0] eq '0.0.0.0'
) #
) ? 1 : 0;
}
1;
} # --- END Cpanel/IP/Loopback.pm
{ # --- BEGIN Cpanel/IP/Configured.pm
package Cpanel::IP::Configured;
use strict;
# use Cpanel::Linux::RtNetlink ();
# use Cpanel::CachedCommand::Utils ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::IP::Loopback ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::JSON::FailOK ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::PwCache ();
use Errno qw[EDQUOT];
use Try::Tiny;
our $VERSION = '1.6';
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 ) {
my $ips = Cpanel::Linux::RtNetlink::get_interface_addresses('AF_INET');
foreach my $ip ( map { $_->{'ip'} } @{$ips} ) {
if ( !Cpanel::IP::Loopback::is_loopback($ip) ) {
push @$configuredips, $ip;
}
}
if ( Cpanel::PwCache::getusername() ne 'nobody' ) {
try {
Cpanel::FileUtils::Write::JSON::Lazy::write_file( $iplist_cachefile, $configuredips, 0644 );
}
catch {
my $err = $_;
if ( try { $err->get('error') == EDQUOT } ) {
_logger()->warn( Cpanel::Exception::get_string($err) );
}
else {
local $@ = $err;
die;
}
};
}
}
$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/LocalCheck.pm
package Cpanel::IP::LocalCheck;
use strict;
use warnings;
# use Cpanel::IP::Configured ();
# use Cpanel::IP::Loopback ();
# use Cpanel::NAT ();
sub ip_is_on_local_server {
my ($ip) = @_;
return 0 if !$ip; #TODO: In 11.56, make this die().
return 1 if Cpanel::IP::Loopback::is_loopback($ip);
my @configured_ips = Cpanel::IP::Configured::getconfiguredips();
return 1 if grep { $_ eq $ip } @configured_ips;
my $local_ip = Cpanel::NAT::get_local_ip($ip);
return 1 if grep { $_ eq $local_ip } @configured_ips;
return 0;
}
1;
} # --- END Cpanel/IP/LocalCheck.pm
{ # --- BEGIN Cpanel/Caller.pm
package Cpanel::Caller;
use strict;
my %PROPERTY_INDEX;
BEGIN {
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 );
}
sub _get {
my ( $property, $frames_back_count ) = @_;
$frames_back_count ||= 0;
$frames_back_count += 2;
return ( caller $frames_back_count )[ $PROPERTY_INDEX{$property} ];
}
sub evaltext { return _get( 'evaltext', @_ ) } ##no critic qw(RequireArgUnpacking)
sub filename { return _get( 'filename', @_ ) } ##no critic qw(RequireArgUnpacking)
sub hasargs { return _get( 'hasargs', @_ ) } ##no critic qw(RequireArgUnpacking)
sub hinthash { return _get( 'hinthash', @_ ) } ##no critic qw(RequireArgUnpacking)
sub is_require { return _get( 'is_require', @_ ) } ##no critic qw(RequireArgUnpacking)
sub line { return _get( 'line', @_ ) } ##no critic qw(RequireArgUnpacking)
sub package { return _get( 'package', @_ ) } ##no critic qw(RequireArgUnpacking)
sub subroutine { return _get( 'subroutine', @_ ) } ##no critic qw(RequireArgUnpacking)
sub wantarray { return _get( 'wantarray', @_ ) } ##no critic qw(RequireArgUnpacking)
1;
} # --- END Cpanel/Caller.pm
{ # --- BEGIN Cpanel/Context.pm
package Cpanel::Context;
use strict;
# use Cpanel::Caller ();
# use Cpanel::Exception ();
sub must_be_list { ##no critic qw(RequireArgUnpacking)
if ( !Cpanel::Caller::wantarray(1) ) {
my $msg = Cpanel::Caller::subroutine(1);
$msg .= $_[0] if defined $_[0];
_die_context( 'list', $msg );
}
return 1;
}
sub must_not_be_scalar {
my ($message) = @_;
my $wa = Cpanel::Caller::wantarray(1);
if ( !$wa && defined $wa ) {
_die_context( 'list or void', $message );
}
return 1;
}
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/GlobalCache.pm
package Cpanel::GlobalCache;
# use Cpanel::JSON::FailOK ();
# use Cpanel::LoadModule ();
my $GCACHEref = {};
our $PRODUCT_CONF_DIR = '/var/cpanel';
sub load_cache {
my ($cachename) = @_;
if ( open( my $cache_fh, '<', "$PRODUCT_CONF_DIR/globalcache/$cachename.cache" ) ) {
$GCACHEref->{$cachename} ||= {};
my $cache_ref = $GCACHEref->{$cachename};
Cpanel::LoadModule::loadmodule('JSON');
if ( $cache_ref->{'data'} = Cpanel::JSON::FailOK::LoadFile($cache_fh) ) {
$cache_ref->{'mtime'} = ( stat($cache_fh) )[9];
}
close($cache_fh);
}
}
sub cachedmcommand {
my $cachename = shift;
Cpanel::LoadModule::loadmodule('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 {
my $cachename = shift;
Cpanel::LoadModule::loadmodule('CachedCommand');
Cpanel::LoadModule::loadmodule('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;
}
Cpanel::LoadModule::loadmodule('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 = {};
}
sub default_product_dir {
$PRODUCT_CONF_DIR = shift if @_;
return $PRODUCT_CONF_DIR;
}
1;
} # --- END Cpanel/GlobalCache.pm
{ # --- BEGIN Cpanel/DIp/MainIP.pm
package Cpanel::DIp::MainIP;
use strict;
use Carp ();
# use Cpanel::CachedCommand ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::LoadWwwAcctConf ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::GlobalCache ();
# use Cpanel::IP::Configured ();
# use Cpanel::IP::Loopback ();
# use Cpanel::JSON ();
# use Cpanel::JSON::FailOK ();
# use Cpanel::LoadFile ();
# use Cpanel::Logger ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::Validate::IP ();
our $VERSION = '1.4';
*clear_configured_ips_cache = \&Cpanel::IP::Configured::clear_configured_ips_cache;
*getconfiguredips = \&Cpanel::IP::Configured::getconfiguredips;
my $PRODUCT_CONF_DIR = '/var/cpanel';
my $SYSTEM_CONF_DIR = '/etc';
my $SYSTEM_SBIN_DIR = '/sbin';
my $cachedmainip = q{};
my $cachedserverip = q{};
sub getmainip {
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::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" ) {
my $logger = Cpanel::Logger->new();
$logger->warn("Working ip binary required to determine IP address. Please check the permissions of $SYSTEM_SBIN_DIR/ip");
return;
}
if ($addr) {
my @IPS = getconfiguredips();
if ( grep( /^\Q$addr\E$/, @IPS ) ) {
$cachedmainip = $addr;
return $addr;
}
}
my $mainserverip = getmainserverip();
$cachedmainip = $mainserverip;
return $mainserverip;
}
sub getmainserverip {
return $cachedserverip if ( $cachedserverip ne '' );
my $oldmainip = Cpanel::LoadFile::loadfile("$PRODUCT_CONF_DIR/mainip");
if ($oldmainip) {
$oldmainip =~ s/^\s+//g;
$oldmainip =~ s/\s+$//g;
$cachedserverip = $oldmainip;
return $oldmainip;
}
my $logger = Cpanel::Logger->new();
my $system = $^O;
my $addr = q{};
my $ethdev = q{};
my $wwwaccthash_ref = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
if ( exists $wwwaccthash_ref->{'ADDR'}
&& defined $wwwaccthash_ref->{'ADDR'}
&& $wwwaccthash_ref->{'ADDR'} ne '' ) {
$addr = $wwwaccthash_ref->{'ADDR'};
}
if ( exists $wwwaccthash_ref->{'ETHDEV'}
&& defined $wwwaccthash_ref->{'ETHDEV'}
&& $wwwaccthash_ref->{'ETHDEV'} ne '' ) {
$ethdev = $wwwaccthash_ref->{'ETHDEV'};
}
if ( !-x "$SYSTEM_SBIN_DIR/ip" ) {
if ($addr) {
return $addr;
}
$logger->die("Fatal error: $SYSTEM_SBIN_DIR/ip is not executable, determining main server IP impossible");
}
my %alias_ips;
my $wwwacct_conf_mtime = ( stat($Cpanel::Config::LoadWwwAcctConf::wwwacctconf) )[9];
my $ipconfig_mtime = 43200; #12 hours
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 @IPS = split( /\n/, Cpanel::GlobalCache::cachedmcommand( 'cpanel', $ipconfig_mtime, "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show', $ethdev eq '' ? () : $ethdev ) );
foreach my $ip (@IPS) {
if ( $ip =~ m{ [\s\:] (\d+ [.] \d+ [.] \d+ [.] \d+) }xms ) {
my $thisip = $1;
if ( !Cpanel::IP::Loopback::is_loopback($thisip) ) {
$cachedserverip = $thisip;
return $thisip;
}
}
}
my $retry_ok = 0;
my $ips = '';
@IPS = ();
if ( $ethdev eq '' ) {
$ips = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show' );
}
else {
$retry_ok = 1;
$ips = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show', $ethdev );
}
@IPS = grep { !exists $alias_ips{$_} } split( /\n/, $ips );
foreach my $ip (@IPS) {
if ( $ip =~ m{ [\s\:] (\d+ [.] \d+ [.] \d+ [.] \d+) }xms ) {
my $thisip = $1;
if ( !Cpanel::IP::Loopback::is_loopback($thisip) ) {
$cachedserverip = $thisip;
return $thisip;
}
}
}
if ($retry_ok) {
$ips = '';
@IPS = ();
$ips = Cpanel::CachedCommand::noncachedcommand( "$SYSTEM_SBIN_DIR/ip", '-4', 'addr', 'show' );
@IPS = split( /\n/, $ips );
foreach my $ip (@IPS) {
if ( $ip =~ m{ [\s\:] (\d+ [.] \d+ [.] \d+ [.] \d+) }xms ) {
my $thisip = $1;
if ( !Cpanel::IP::Loopback::is_loopback($thisip) ) {
$cachedserverip = $thisip;
return $thisip;
}
}
}
}
if ( $ethdev ne '' ) {
$logger->warn("No IP address found on $ethdev, make sure device is correctly configured, returning 0.0.0.0");
}
else {
$logger->warn("No IP address found, returning 0.0.0.0");
}
return '0.0.0.0';
}
sub clearcache {
$cachedmainip = '';
$cachedserverip = '';
Cpanel::IP::Configured::clearcache();
if ( $INC{'Cpanel/DIp.pm'} ) {
Cpanel::DIp::clearcache();
}
}
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;
}
1;
} # --- END Cpanel/DIp/MainIP.pm
{ # --- BEGIN Cpanel/Ips/Fetch.pm
package Cpanel::Ips::Fetch;
use strict;
# use Cpanel::DIp::MainIP ();
sub fetchipslist {
my $ip_ref = Cpanel::DIp::MainIP::getconfiguredips();
my $ips_hashref = { map { $_ => 1 } @{$ip_ref} };
return wantarray ? %{$ips_hashref} : $ips_hashref;
}
sub fetch_ips_array {
my $ip_ref = Cpanel::DIp::MainIP::getconfiguredips();
return wantarray ? @{$ip_ref} : $ip_ref;
}
1;
} # --- END Cpanel/Ips/Fetch.pm
{ # --- BEGIN Cpanel/IP/Local.pm
package Cpanel::IP::Local;
use strict;
# use Cpanel::NAT ();
# use Cpanel::IP::Configured ();
# use Cpanel::IP::LocalCheck ();
# use Cpanel::IP::Loopback ();
# use Cpanel::Validate::IP ();
sub get_local_systems_public_ips {
require Cpanel::Linux::RtNetlink;
require Cpanel::Context;
require Cpanel::Ips::Fetch;
Cpanel::Context::must_be_list();
my @ips;
foreach my $ip ( Cpanel::Ips::Fetch::fetch_ips_array() ) {
push @ips, Cpanel::NAT::get_public_ip($ip);
}
my $ipv6_ref = Cpanel::Linux::RtNetlink::get_addresses_by_interface('AF_INET6'); # Warning: not cached!
foreach my $device ( keys %{$ipv6_ref} ) {
my $device_addresses = $ipv6_ref->{$device};
foreach my $address ( keys %{$device_addresses} ) {
push @ips, $device_addresses->{$address}{'ip'};
}
}
return @ips;
}
*ip_is_on_local_server = \&Cpanel::IP::LocalCheck::ip_is_on_local_server;
1;
} # --- END Cpanel/IP/Local.pm
{ # --- BEGIN Cpanel/Domain/Local.pm
package Cpanel::Domain::Local;
use strict;
use Socket ();
# use Cpanel::IP::Local ();
# use Cpanel::IP::Loopback ();
# use Cpanel::Validate::IP ();
*Cpanel::Domain::Local::_inet_ntoa = \&Socket::inet_ntoa;
sub domain_or_ip_is_on_local_server {
my $domain_or_ip = shift;
return 1 if Cpanel::IP::Loopback::is_loopback($domain_or_ip);
if ( Cpanel::Validate::IP::is_valid_ip($domain_or_ip) ) {
return Cpanel::IP::Local::ip_is_on_local_server($domain_or_ip);
}
elsif ( my $iaddr = gethostbyname($domain_or_ip) ) {
return Cpanel::IP::Local::ip_is_on_local_server( _inet_ntoa($iaddr) );
}
return 0;
}
1;
} # --- END Cpanel/Domain/Local.pm
{ # --- BEGIN Cpanel/MysqlUtils/MyCnf/Basic.pm
package Cpanel::MysqlUtils::MyCnf::Basic;
use strict;
# use Cpanel::LoadModule ();
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, {}, '\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, {}, '\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};
}
elsif ( $INC{'Cpanel/PwCache.pm'} ) {
$HOMECACHE{$user} = $homedir = ( Cpanel::PwCache::getpwnam($user) )[7];
}
else {
$HOMECACHE{$user} = $homedir = ( getpwnam($user) )[7];
}
return $homedir . '/.my.cnf';
}
sub _getmydbparm {
my $param = shift;
my $user = shift;
if ( !$user && $INC{'Cpanel/PwCache.pm'} ) {
$user = 'Cpanel::PwCache'->can('getusername')->();
}
$user ||= ( getpwuid($>) )[0] || 'root';
my $privs_obj;
if ( $user ne 'root' && $> == 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 {
my $socket = _getmydbparm( 'socket', @_ );
if ( $socket && -S $socket ) {
return $socket;
}
Cpanel::LoadModule::load_perl_module('Cpanel::MysqlUtils::MyCnf::Full');
my @potential_sockets;
my $ref = 'Cpanel::MysqlUtils::MyCnf::Full'->can('etc_my_cnf')->();
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} || $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 is_remote_mysql {
my $host = shift || getmydbhost('root');
return ( $host && !Cpanel::Domain::Local::domain_or_ip_is_on_local_server($host) ) ? 1 : 0;
}
1;
} # --- END Cpanel/MysqlUtils/MyCnf/Basic.pm
{ # --- BEGIN Cpanel/Socket/INET.pm
package Cpanel::Socket::INET;
use strict;
# use IO::Socket::INET();
our @ISA;
BEGIN { push @ISA, qw(IO::Socket::INET); }
# use Cpanel::Exception ();
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_) or do {
die Cpanel::Exception->create_raw("TCP/IP connection (@_) failure: [$@] [$!]");
};
return $self;
}
1;
} # --- END Cpanel/Socket/INET.pm
{ # --- BEGIN Cpanel/MysqlUtils/Unprivileged.pm
package Cpanel::MysqlUtils::Unprivileged;
use strict;
# use Cpanel::Autodie ();
# use Cpanel::Socket::INET ();
my $MYSQL_PORT = 3306;
my $MYSQL_PROTOCOL = 10;
my $MYSQL_UNPACK_TEMPLATE = <<END;
x3 #packet length - discard
x #packet number - discard
C #protocol version
Z* #protocol, as string
END
sub get_version_from_host {
my ( $host, $port ) = @_;
$port ||= $MYSQL_PORT;
my ($client) = Cpanel::Socket::INET->new("$host:$port");
my $buffer = q<>;
Cpanel::Autodie::read( $client, $buffer, 64 );
my ( $protocol, $version ) = unpack( $MYSQL_UNPACK_TEMPLATE, $buffer );
if ( $protocol != $MYSQL_PROTOCOL ) {
die "Unknown MySQL protocol: $protocol";
}
if ( defined $version && index( $version, 'MariaDB' ) > 0 ) {
my ( $cap, $v, $name ) = split( '-', $version );
$version = $v . '-' . $name if $name eq 'MariaDB';
}
return $version;
}
1;
} # --- END Cpanel/MysqlUtils/Unprivileged.pm
{ # --- BEGIN Cpanel/Version/Compare.pm
package Cpanel::Version::Compare;
use strict;
sub cmp ($$) { _cmp(@_) }
sub _cmp {
my ( $maj, $min, $rev, $sup ) = split /[\._]/, $_[0];
my ( $mj, $mn, $rv, $sp ) = split /[\._]/, $_[1];
return $maj <=> $mj || $min <=> $mn || $rev <=> $rv || $sup <=> $sp;
}
my %modes = (
'>' => sub {
return if $_[0] eq $_[1]; # no need to continue if they are the same
return _cmp(@_) > 0;
},
'<' => sub {
return if $_[0] eq $_[1]; # no need to continue if they are the same
return _cmp(@_) < 0;
},
'==' => sub { return $_[0] eq $_[1] || _cmp(@_) == 0; },
'!=' => sub { return $_[0] ne $_[1] && _cmp(@_) != 0; },
'>=' => sub {
return 1 if $_[0] eq $_[1]; # no need to continue if they are the same
return _cmp(@_) >= 0;
},
'<=' => sub {
return 1 if $_[0] eq $_[1]; # no need to continue if they are the same
return _cmp(@_) <= 0;
},
'<=>' => sub {
return _cmp(@_);
},
);
sub compare {
my ( $check, $mode, $against ) = @_;
if ( ref $check eq 'HASH' ) {
$mode = $check->{'comparison'};
$against = $check->{'version_b'};
$check = $check->{'version_a'};
}
elsif ( @_ == 2 ) {
$against = $mode;
$mode = '>=';
}
if ( !exists $modes{$mode} ) {
return;
}
for my $ver ( $check, $against ) {
if ( $ver !~ m{ ^((?:\d+[._]){0,}\d+[a-z]?).*?$ }xms ) {
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';
}
}
for my $ver ( $check, $against ) {
if ( $ver !~ m { \A \d+\.\d+\.\d+\.\d+ \z }xms ) {
return;
}
}
return $modes{$mode}->( $check, $against );
}
sub get_major_release {
my $version = shift || '';
$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 {
my ( $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/MysqlUtils/Version.pm
package Cpanel::MysqlUtils::Version;
use strict;
use Try::Tiny;
# use Cpanel::Domain::Local ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::LoadFile ();
# use Cpanel::LoadModule ();
# use Cpanel::MysqlUtils::MyCnf::Basic ();
# use Cpanel::MysqlUtils::Unprivileged ();
# use Cpanel::Version::Compare ();
our $cached_mysql_version;
our $DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED = 5.5; # assume MySQL 5.5 is the default value
our $_VERSION_CACHE_PATH = '/var/cpanel/mysql_server_version_cache';
my $VERSION_CACHE_TTL = 4 * 60 * 60; #4 hours
sub cmp_versions {
my ( $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;
return Cpanel::Version::Compare::cmp( $a, $b );
}
sub is_at_least {
my ( $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 = shift || _getmydbhost() || 'localhost';
die "Only run as root!" if $>;
my $is_remote = !Cpanel::Domain::Local::domain_or_ip_is_on_local_server($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;
try {
$version_string = _get_mysql_version_via_socket($host);
}
catch {
my $exc = $_;
local $@ = $exc;
die if $is_remote;
};
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;
}
}
}
if ( !$version_string ) {
$version_string = get_version_from_frm_files();
}
if ( !$version_string ) {
$version_string = get_version_from_mysql_upgrade_info();
}
if ( !$version_string ) {
die Cpanel::Exception->create( 'The system did not determine the “[_1]” version by connecting to the server, running the executable command named “[_1]”, or manually examining the data directory.', ['mysqld'] );
}
( $maj, $min, $pt ) = _split_mysql_version($version_string);
try {
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 ($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();
return Cpanel::LoadFile::loadfile("$mysql_dir/mysql_upgrade_info");
}
sub get_version_from_frm_files {
my $mysql_dir = _mysql_data_dir();
my $newest_mysql_version_id;
foreach my $potential_file (qw(table_stats slow_log column_stats db user)) {
my $contents = Cpanel::LoadFile::loadfile("$mysql_dir/mysql/${potential_file}.frm") or next;
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 {
my ($newest_mysql_version_id) = @_;
my @VERSION;
while ( length $newest_mysql_version_id ) {
unshift @VERSION, sprintf( "%d", substr( $newest_mysql_version_id, -2, 2, '' ) );
}
return join( '.', @VERSION );
}
sub string_to_number {
my ($version) = @_;
my ( $maj, $min, $pt ) = _split_mysql_version($version);
return 0 + sprintf( "%d%02d%02d", $maj, $min || 0, $pt || 0 );
}
*_get_mysql_version_via_socket = \&Cpanel::MysqlUtils::Unprivileged::get_version_from_host;
*_getmydbhost = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbhost;
sub _load_cache_file {
my $cache = Cpanel::LoadFile::load($_VERSION_CACHE_PATH);
return split m<\n>, $cache, 2; #host => version_string
}
sub _split_mysql_version {
my ($version) = @_;
$version =~ s{\A[0-9]+\.[0-9]+(?:\.[0-9]+)?-}{} if $version =~ m{mariadb}i && $version =~ m{\A[0-9]+\.[0-9]+(?:\.[0-9]+)?-[0-9]+\.};
my $version_splitter_re = qr<
\A
([0-9]+)
(?:
\.
([0-9]+)
(?:
\.
([0-9]+)
(?:
-
([0-9a-z\.\-~+]+)
)?
)?
)?
\z
>xi;
my ( $major, $minor, $point, $build ) = ( $version =~ m<$version_splitter_re> ) or do {
die "Invalid version: $version";
};
return ( $major, $minor, $point, $build );
}
sub _expand_mysql_version {
my ($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');
return 'Cpanel::MysqlUtils'->can('getmysqldir')->();
}
1;
} # --- END Cpanel/MysqlUtils/Version.pm
{ # --- BEGIN Cpanel/AdminBin/Serializer.pm
package Cpanel::AdminBin::Serializer;
use strict;
# use Cpanel::JSON ();
our $VERSION = '2.4';
*MAX_LOAD_LENGTH = \$Cpanel::JSON::MAX_LOAD_LENGTH;
*MAX_PRIV_LOAD_LENGTH = \$Cpanel::JSON::MAX_PRIV_LOAD_LENGTH;
*DumpFile = \&Cpanel::JSON::DumpFile;
*Dump = \&Cpanel::JSON::Dump;
*SafeDump = \&Cpanel::JSON::SafeDump;
sub SafeLoadFile { ## no critic qw(RequireArgUnpacking)
return Cpanel::JSON::_LoadFile( $_[0], $Cpanel::JSON::MAX_LOAD_LENGTH, $Cpanel::JSON::DECODE_UTF8, $_[1], $Cpanel::JSON::LOAD_STRICT );
}
sub LoadFile { ## no critic qw(RequireArgUnpacking)
return Cpanel::JSON::_LoadFile( $_[0], $_[1] || $Cpanel::JSON::MAX_LOAD_LENGTH_UNLIMITED, $Cpanel::JSON::DECODE_UTF8, $_[2], $Cpanel::JSON::LOAD_STRICT );
}
sub clone { ## no critic(RequireArgUnpacking) -- This needs to be fast
return Cpanel::JSON::Load( Cpanel::JSON::Dump( $_[0] ) );
}
*Load = \&Cpanel::JSON::Load;
*looks_like_serialized_data = \&Cpanel::JSON::looks_like_json;
1;
} # --- END Cpanel/AdminBin/Serializer.pm
{ # --- BEGIN Cpanel/AdminBin/Utils/Exit.pm
package Cpanel::AdminBin::Utils::Exit;
use strict;
# use Cpanel::ChildErrorStringifier ();
# use Cpanel::LoadModule ();
sub exit_msg {
my ( $child_status, $call_ref ) = @_;
my $msg_items_all = Cpanel::ChildErrorStringifier->new($child_status)->autopsy();
Cpanel::LoadModule::load_perl_module('Cpanel::Locale');
return Cpanel::Locale->get_handle()->makevar(
"The adminbin “[_1]” in the “[_2]” namespace call to function “[_3]” ended prematurely: [_4]",
$call_ref->{'module'},
$call_ref->{'namespace'},
$call_ref->{'function'},
$msg_items_all
);
}
1;
} # --- END Cpanel/AdminBin/Utils/Exit.pm
{ # --- BEGIN Cpanel/Wrap.pm
package Cpanel::Wrap;
use strict;
# use Cpanel::AdminBin::Serializer ();
# use Cpanel::Hulk::Constants ();
# use Cpanel::Socket::UNIX::Micro ();
# use Cpanel::AdminBin::Utils::Exit ();
our $VERSION = 1.4;
our $CPWRAPD_SOCKET_PATH = '/usr/local/cpanel/var/cpwrapd.sock';
my $logger;
sub _get_cpwrapd_connection {
my %OPTS = @_;
my $socket;
socket(
$socket, $Cpanel::Hulk::Constants::AF_UNIX,
$Cpanel::Hulk::Constants::SOCK_STREAM, 0
);
my $usock = Cpanel::Socket::UNIX::Micro::micro_sockaddr_un($CPWRAPD_SOCKET_PATH);
if ( connect( $socket, $usock ) ) {
return $socket;
}
my $message = "Cpanel::AdminBin::_get_cpwrapd_connection could not connect to $CPWRAPD_SOCKET_PATH";
if ( !$OPTS{'no_cperror'} ) {
$Cpanel::context ||= 'wrap';
$Cpanel::CPERROR{$Cpanel::context} = $message;
}
_logger()->warn($message);
return;
}
sub send_cpwrapd_request_no_cperror {
my (%OPTS) = @_;
$OPTS{'no_cperror'} = 1;
return scalar send_cpwrapd_request(%OPTS);
}
sub send_cpwrapd_request {
my (%OPTS) = @_;
my $socket = _get_cpwrapd_connection() || return {
'status' => 0,
'error' => 1,
'statusmsg' => "Could not connect to cpsrvd socket: $CPWRAPD_SOCKET_PATH",
};
my ( $sent_ok, $response_sr, $stream ) = _send_request_over_socket( $socket, %OPTS );
if ($stream) {
return {
'status' => 1,
'error' => 0,
'streamed' => 1,
};
}
if ( !$response_sr || !$response_sr ) {
if ( !$sent_ok ) {
_logger()->warn("Cpanel::AdminBin::send_cpwrapd_request received SIGPIPE and no response");
}
return {
'status' => 0,
'error' => 1,
'statusmsg' => "No data returned from cpwrapd call: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}]"
};
}
if ( !$sent_ok ) {
_logger()->warn("Cpanel::AdminBin::send_cpwrapd_request received SIGPIPE and still got a response");
}
my $ref = Cpanel::AdminBin::Serializer::Load($$response_sr);
my $cperror_trap;
if ( ref $ref ) {
my $exit_msg;
if ( $ref->{'exit_code'} ) {
my $exitcode = $ref->{'exit_code'};
$exit_msg = Cpanel::AdminBin::Utils::Exit::exit_msg(
$exitcode,
{
'namespace' => ( $OPTS{'namespace'} || 'Cpanel' ),
'module' => $OPTS{'module'},
'function' => $OPTS{'function'}
}
);
if ( !$OPTS{'no_cperror'} ) {
_logger()->warn( __PACKAGE__ . "::send_cpwrapd_request $exit_msg: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}]: set error in context $Cpanel::context: raw_response=[$$response_sr]" ); #issafe
$Cpanel::CPERROR{$Cpanel::context} = _error_as_text( $exit_msg || 'send_cpwrapd_request unknown error' );
}
else {
_logger()->warn( __PACKAGE__ . "::send_cpwrapd_request $exit_msg: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}]: raw_response=[$$response_sr]" );
}
}
if ( $ref->{'error'} ) {
if ( !$OPTS{'no_cperror'} ) {
_logger()->warn( __PACKAGE__ . "::send_cpwrapd_request error: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}]: set error in context $Cpanel::context: statusmsg=[$ref->{'statusmsg'}]" ); #issafe
$Cpanel::CPERROR{$Cpanel::context} = _error_as_text( $ref->{'data'} || $ref->{'statusmsg'} || $exit_msg || 'send_cpwrapd_request unknown error' );
}
else {
_logger()->warn( __PACKAGE__ . "::send_cpwrapd_request error: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}]: statusmsg=[$ref->{'statusmsg'}]" );
}
}
}
if ( !$ref ) {
return {
'status' => 0,
'error' => 1,
'statusmsg' => "Failed to deserialize data returned from cpwrapd call: namespace=[$OPTS{'namespace'}] module=[$OPTS{'module'}] function=[$OPTS{'function'}] data=[$$response_sr]"
};
}
if ( $ref->{'status'} ) {
$ref->{'response_ref'} = $response_sr;
}
return $ref;
}
sub _send_request_over_socket {
my ( $socket, %OPTS ) = @_;
my $response;
my $sent_ok = 1;
my $stream = $OPTS{'stream'};
local $SIG{'PIPE'} = sub {
$sent_ok = 0;
return 1;
};
my $request = Cpanel::AdminBin::Serializer::Dump(
{
'version' => $Cpanel::AdminBin::Serializer::VERSION,
'namespace' => $OPTS{'namespace'},
'module' => $OPTS{'module'},
'function' => $OPTS{'function'},
'action' => $OPTS{'action'},
'env' => $OPTS{'env'},
'data' => $OPTS{'data'},
}
) . "\r\n\r\n"; #must end request with \r\n\r\n
syswrite( STDERR, "[send_cpwrapd_request][REQUEST]=[$request]\n" ) if $Cpanel::Debug::level > 2;
syswrite( $socket, $request );
shutdown( $socket, 1 ); #stopped writing
if ($stream) {
my $buf;
while ( read( $socket, $buf, 65535 ) ) {
syswrite( $stream, $buf );
}
}
else {
local $/ = undef;
$response = readline($socket);
}
syswrite( STDERR, "[send_cpwrapd_request][RESPONSE]=[$response]\n" ) if $Cpanel::Debug::level > 2;
return ( $sent_ok, \$response, $stream );
}
sub _error_as_text {
my ($obj) = @_;
return $obj if !ref $obj;
if ( ref $obj eq 'HASH' ) {
return $obj->{'statusmsg'} || $obj->{'message'} || $obj->{'error'} || 'Unknown error';
}
if ( ref $obj eq 'ARRAY' ) {
return $obj->[0];
}
return $obj;
}
sub _logger {
return $logger if defined $logger;
eval 'require Cpanel::Logger' or die "Failed to load Cpanel::Logger: $@";
return ( $logger = 'Cpanel::Logger'->new() );
}
1;
} # --- END Cpanel/Wrap.pm
{ # --- BEGIN Cpanel/Wrap/Config.pm
package Cpanel::Wrap::Config;
use strict;
our %ALLOWED_ENV = (
'REMOTE_PASSWORD' => 1, #TEMP_SESSION_SAFE
'REMOTE_ADDR' => 1,
'HTTP_COOKIE' => 1, #Needed for locales, Cpanel::AdminBin::Server will filter out any key other than session_locale
'CPRESELLER' => 1,
'CPRESELLERSESSION' => 1,
'CPRESELLERSESSIONKEY' => 1,
'WHM50' => 1,
'cp_security_token' => 1
);
sub safe_hashref_of_allowed_env {
return { map { $ALLOWED_ENV{$_} ? ( $_ => substr( $ENV{$_} || '', 0, 1024 ) ) : () } keys %ENV };
}
1;
} # --- END Cpanel/Wrap/Config.pm
{ # --- BEGIN Cpanel/AdminBin/Cache.pm
package Cpanel::AdminBin::Cache;
use strict;
# use Cpanel::StatCache ();
# use Cpanel::PwCache ();
# use Cpanel::SafeDir::MK ();
my $logger;
sub check_cache_item {
my ( $mtimetobeat, $file ) = @_;
if ( !$file ) {
_logger()->warn('Missing file argument');
return;
}
elsif ( !defined $mtimetobeat || $mtimetobeat !~ m/^\d+/ ) {
_logger()->warn('Cache mtime threshold not provided.');
return;
}
elsif ( !$mtimetobeat ) { # 0 means skip cache
return;
}
my $cache_dir = _get_cache_dir() or return;
return if !-e $cache_dir . '/' . $file;
my ( $size, $mtime ) = ( stat(_) )[ 7, 9 ];
return if ( !$size || !$mtime );
return 1 if ( $mtime > $mtimetobeat && $mtime <= time() ); #timewarp safe;
return;
}
sub _get_cache_dir {
my ($base_dir) = @_;
$base_dir ||= $Cpanel::homedir || Cpanel::PwCache::gethomedir();
if ( !$base_dir ) {
_logger()->warn('No base cache directory provided');
return;
}
my $target_dir = $base_dir . '/.cpanel/datastore';
if ( !Cpanel::StatCache::cachedmtime($target_dir) ) {
if ( $> > 0 ) { # Don't create datastore directory owned by root
if ( Cpanel::SafeDir::MK::safemkdir( $target_dir, 0700 ) ) {
Cpanel::StatCache::clearcache();
return $target_dir;
}
}
return;
}
return $target_dir;
}
sub _logger {
return ( $logger ||= Cpanel::Logger->new() );
}
1;
} # --- END Cpanel/AdminBin/Cache.pm
{ # --- BEGIN Cpanel/AdminBin.pm
package Cpanel::AdminBin;
use strict;
# use Cpanel::Exception ();
# use Cpanel::FileUtils::Open ();
# use Cpanel::LoadFile ();
# use Cpanel::StatCache ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::PwCache ();
# use Cpanel::Logger ();
# use Cpanel::Wrap ();
# use Cpanel::Wrap::Config ();
# use Cpanel::AdminBin::Cache ();
my $logger = Cpanel::Logger->new();
our $VERSION = 2.2;
our $safecaching = 0;
sub adminstor {
my ( $bin, $key, $ref ) = @_;
my $result = Cpanel::Wrap::send_cpwrapd_request(
'namespace' => 'Cpanel',
'module' => $bin,
'function' => $key,
'data' => $ref,
'action' => 'run',
'env' => Cpanel::Wrap::Config::safe_hashref_of_allowed_env(),
);
return $result->{'data'};
}
sub adminrun {
my ( $bin, @AG ) = @_;
_trimws_safe( \@AG );
my $function = shift @AG;
my $full_arg = join( ' ', @AG );
my $result = Cpanel::Wrap::send_cpwrapd_request(
'namespace' => 'Cpanel',
'module' => $bin,
'function' => $function,
'data' => $full_arg,
'action' => 'run',
'env' => Cpanel::Wrap::Config::safe_hashref_of_allowed_env(),
);
return $result->{'data'};
}
sub run_adminbin_with_status {
my ( $bin, @AG ) = @_;
_trimws_safe( \@AG );
my $function = shift @AG;
my $full_arg = join( ' ', @AG );
my $result = Cpanel::Wrap::send_cpwrapd_request_no_cperror(
'namespace' => 'Cpanel',
'module' => $bin,
'function' => $function,
'data' => $full_arg,
'action' => 'run',
'env' => Cpanel::Wrap::Config::safe_hashref_of_allowed_env(),
);
return {
'status' => $result->{'error'} ? 0 : 1,
'statusmsg' => $result->{'statusmsg'},
'data' => $result->{'error'} ? undef : $result->{'data'},
'error' => $result->{'error'} ? _convert_data_to_error( $result->{'data'} ) : undef,
};
}
sub adminfetch {
my ( $bin, $cachecfiles, $func, $result, @AG ) = @_;
return _adminfetch(
'module' => ( $bin || '' ),
'function' => ( $func || '' ),
'format' => ( $result || '' ),
'cache_check_files' => ( $cachecfiles || '' ),
'cache' => 1,
'args' => \@AG,
);
}
sub adminfetchnocache {
my ( $bin, $cachecfiles, $func, $result, @AG ) = @_;
return _adminfetch(
'module' => ( $bin || '' ),
'function' => ( $func || '' ),
'format' => ( $result || '' ),
'cache_check_files' => ( $cachecfiles || '' ),
'cache' => 0,
'args' => \@AG,
);
}
sub fetch_adminbin_with_status {
my ( $bin, $cachecfile, $func, $result, @AG ) = @_;
my $ret_val = _adminfetch(
'module' => ( $bin || '' ),
'function' => ( $func || '' ),
'format' => ( $result || '' ),
'cache_check_files' => ( $cachecfile || '' ),
'cache' => 1,
'args' => \@AG,
'return_status' => 1,
);
return {
'status' => $ret_val->{'error'} ? 0 : 1,
'statusmsg' => $ret_val->{'statusmsg'},
'data' => $ret_val->{'error'} ? undef : $ret_val->{'data'},
'error' => $ret_val->{'error'} ? _convert_data_to_error( $ret_val->{'data'} ) : undef,
};
}
sub fetch_adminbin_nocache_with_status {
my ( $bin, $cachecfile, $func, $result, @AG ) = @_;
my $ret_val = _adminfetch(
'module' => ( $bin || '' ),
'function' => ( $func || '' ),
'format' => ( $result || '' ),
'cache_check_files' => ( $cachecfile || '' ),
'cache' => 0,
'args' => \@AG,
'return_status' => 1,
);
return {
'status' => $ret_val->{'error'} ? 0 : 1,
'statusmsg' => $ret_val->{'statusmsg'},
'data' => $ret_val->{'error'} ? undef : $ret_val->{'data'},
'error' => $ret_val->{'error'} ? _convert_data_to_error( $ret_val->{'data'} ) : undef,
};
}
sub _convert_data_to_error {
my ($data) = @_;
return $data if !$data;
$data =~ s/\A.\n//m; # If this is an error, it shouldn't have the .\n format for data.
return $data;
}
sub _adminfetch {
my %OPTS = @_;
my $bin = $OPTS{'module'};
my $func = $OPTS{'function'};
my $cache_check_files = $OPTS{'cache_check_files'};
my $result_format = $OPTS{'format'};
my $return_status = $OPTS{'return_status'} ? 1 : 0;
my @AG = @{ $OPTS{'args'} };
my $file = join( '_', $bin, $func, $AG[0] || () );
my $res;
my $homedir = $Cpanel::homedir || Cpanel::PwCache::gethomedir($>);
my $call_cachefile = $homedir . '/.cpanel/datastore/' . $file;
my $usecache = $OPTS{'cache'} && ( $Cpanel::AdminBin::safecaching ? 0 : 1 );
if ( @AG && ref $AG[0] ) {
$usecache = 0; # cannot cache complex fetches
}
if ($usecache) {
$res = _fetch_from_cache( $homedir, $cache_check_files, $file, $result_format );
if ( defined $res ) {
return ( ref $res ? $res->{'data'} : $res ) if !$return_status;
return {
'status' => 1,
'statusmsg' => 'Data retrieved from cache.',
'data' => $res->{'data'},
'error' => 0
};
}
}
my $data;
if ( @AG && ref $AG[0] ) {
$data = $AG[0];
}
else {
$data = join( ' ', map { defined $_ ? $_ : '' } @AG );
}
my $wrap_call_coderef = $return_status ? \&Cpanel::Wrap::send_cpwrapd_request_no_cperror : \&Cpanel::Wrap::send_cpwrapd_request;
my $response = $wrap_call_coderef->(
'namespace' => 'Cpanel',
'module' => $bin,
'function' => $func,
'data' => $data,
'action' => ( $result_format eq 'scalar' ? 'run' : 'fetch' ),
'env' => Cpanel::Wrap::Config::safe_hashref_of_allowed_env(),
);
my $exitcode = $response->{'exit_code'};
my $readok = $response->{'status'};
if ( !ref $response->{'data'} ) {
$res = $response->{'data'};
if ( defined $exitcode && $exitcode == 0 && $readok ) {
if ( $usecache && Cpanel::FileUtils::Open::sysopen_with_real_perms( my $data_fh, $call_cachefile, 'O_WRONLY|O_TRUNC|O_CREAT', 0600 ) ) {
print {$data_fh} $res;
close($data_fh);
}
}
return $response if $return_status;
return $res || '';
}
else {
my $res = $response->{'data'};
my $readok = $response->{'status'};
if ( $exitcode == 0 && $readok ) {
if ($usecache) {
if ( Cpanel::FileUtils::Open::sysopen_with_real_perms( my $data_store_fh, $call_cachefile, 'O_WRONLY|O_TRUNC|O_CREAT', 0600 ) ) {
print {$data_store_fh} ${ $response->{'response_ref'} } or $logger->info("Write to $call_cachefile failed: $!");
close($data_store_fh) or $logger->info("close($call_cachefile) failed: $!");
}
else {
$logger->warn("Could not write to $call_cachefile");
}
}
}
return $response if $return_status;
return $res if $readok;
$logger->warn("Failed to retrieve storable data from $bin: $@");
return {};
}
}
sub _fetch_from_cache {
my ( $homedir, $cache_check_files, $file, $result_format ) = @_;
my $call_cachefile = $homedir . '/.cpanel/datastore/' . $file;
my ( $mtimetobeat, $res );
$mtimetobeat = 0;
if ( ref $cache_check_files eq 'ARRAY' ) {
foreach my $checkfile ( @{$cache_check_files} ) {
my $cmtime = ( stat($checkfile) )[9] || 0;
if ( $cmtime > $mtimetobeat ) {
$mtimetobeat = $cmtime;
}
}
}
else {
$mtimetobeat = ( stat($cache_check_files) )[9] || 0;
}
if ( Cpanel::AdminBin::Cache::check_cache_item( $mtimetobeat, $file ) ) {
if ( $result_format eq 'scalar' ) {
return Cpanel::LoadFile::loadfile($call_cachefile);
}
elsif ( -r $call_cachefile ) {
if ( open( my $datastore_fh, '<', $call_cachefile ) ) {
local $SIG{__DIE__} = 'DEFAULT';
local $@;
eval { $res = Cpanel::AdminBin::Serializer::LoadFile($datastore_fh) };
close($datastore_fh) or warn "close($datastore_fh) failed: $!";
}
}
}
return $res;
}
sub _trimws_safe {
my $arrayref = shift;
for ( 0 .. $#$arrayref ) {
if ( defined $arrayref->[$_] ) {
$arrayref->[$_] =~ s<\A[\r\n \t]+><>;
$arrayref->[$_] =~ s<[\r\n \t]+\z><>;
if ( $arrayref->[$_] =~ tr/\r\n \t// ) {
die Cpanel::Exception::create( 'InvalidParameter', 'The parameter “[_1]” contains whitespace. This function cannot accept whitespace.', [ $arrayref->[$_] ] );
}
}
else {
$arrayref->[$_] = '';
}
}
}
1;
} # --- END Cpanel/AdminBin.pm
{ # --- BEGIN Cpanel/Mysql/Privs.pm
package Cpanel::Mysql::Privs;
use strict;
use warnings;
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
# use Cpanel::MysqlUtils::Version ();
my @SUPPORTED_MYSQL_PRIVS = (
'ALTER ROUTINE',
'ALTER',
'CREATE ROUTINE',
'CREATE TEMPORARY TABLES',
'CREATE VIEW',
'CREATE',
'DELETE',
'DROP',
'EXECUTE',
'INDEX',
'INSERT',
'LOCK TABLES',
'REFERENCES',
'SELECT',
'SHOW VIEW',
'UPDATE',
);
my %VERSION_PRIVS_DBI = (
50106 => [
'EVENT',
'TRIGGER',
],
);
my %VERSION_PRIVS_SHORT = (
'5.1' => $VERSION_PRIVS_DBI{50106},
);
my $privs_regexp;
sub get_mysql_privileges_lookup {
my $dbh = shift or die "DBI handle needed";
my %lookup;
@lookup{@SUPPORTED_MYSQL_PRIVS} = ();
my $dbh_version = $dbh->{'mysql_serverversion'};
for my $release ( keys %VERSION_PRIVS_DBI ) {
if ( $dbh_version >= $release ) {
@lookup{ @{ $VERSION_PRIVS_DBI{$release} } } = ();
}
}
$_ = 1 for values %lookup;
return wantarray ? %lookup : \%lookup;
}
sub verify_privileges {
my @privs = @_;
my %privs_lookup;
@privs_lookup{ @SUPPORTED_MYSQL_PRIVS, 'ALL', 'ALL PRIVILEGES' } = ();
my $mysql_version = _get_mysql_version();
for my $version ( keys %VERSION_PRIVS_SHORT ) {
if ( Cpanel::MysqlUtils::Version::is_at_least( $mysql_version, $version ) ) {
@privs_lookup{ @{ $VERSION_PRIVS_SHORT{$version} } } = ();
}
}
my @invalid_privs = grep { !exists $privs_lookup{$_} } @privs;
if (@invalid_privs) {
die Cpanel::Exception::create( 'InvalidParameter', 'The following [asis,MySQL] [numerate,_1,privilege is,privileges are] invalid: [list_and_quoted,_2]', [ scalar(@invalid_privs), \@invalid_privs ] );
}
return 1;
}
sub _get_mysql_version {
my $mysql_version;
if ($>) {
Cpanel::LoadModule::load_perl_module('Cpanel::AdminBin::Call');
$mysql_version = Cpanel::AdminBin::Call::call( 'Cpanel', 'mysql', 'GET_SERVER_INFORMATION' )->{'version'};
}
else {
$mysql_version = Cpanel::MysqlUtils::Version::current_mysql_version()->{'full'};
}
return $mysql_version;
}
sub checkbinlog { #i.e., whether the binary log is OFF
my $self = shift || {};
return $self->{'_cached_binlog'} if exists $self->{'_cached_binlog'};
if ( $self->{'dbh'} ) {
my $value;
my $dbh = $self->{'dbh'};
my $data = $dbh->selectrow_hashref('SHOW VARIABLES LIKE "log_bin"');
$value = $data->{'Value'};
return $self->{'_cached_binlog'} = ( $value eq 'OFF' ) ? 0 : 1;
}
require Cpanel::PwCache;
my ( $user, $homedir ) = ( Cpanel::PwCache::getpwuid($>) )[ 0, 7 ];
if ( $> != 0 && !-e $homedir . '/.my.cnf' ) {
require Cpanel::AdminBin;
$self->{'_cached_binlog'} = Cpanel::AdminBin::adminrun( 'cpmysql', 'CHECKBINLOG' );
return $self->{'_cached_binlog'};
}
die "Unimplemented logic!";
}
1;
} # --- END Cpanel/Mysql/Privs.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 {
return 1 if in_global_destruction() && $INC{'Cpanel/BinCheck.pm'}; #compiled perl only
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 { ## no critic qw(RequireArgUnpacking)
if ( $_[0] =~ m/during global destruction\.$/ ) {
$in_global_destruction = 1;
}
return;
}
1;
} # --- END Cpanel/Destruct.pm
{ # --- BEGIN Cpanel/StringFunc/Match.pm
package Cpanel::StringFunc::Match;
$Cpanel::StringFunc::Match::VERSION = '1.2';
# use Cpanel::StringFunc::Case ();
sub beginmatch {
return ( substr( $_[0], 0, length( $_[1] ) ) eq $_[1] ) ? 1 : 0;
}
sub ibeginmatch {
return beginmatch( Cpanel::StringFunc::Case::ToLower( $_[0] ), Cpanel::StringFunc::Case::ToLower( $_[1] ) );
}
sub endmatch {
return ( substr( $_[0], ( length( $_[1] ) * -1 ) ) eq $_[1] ) ? 1 : 0;
}
sub iendmatch {
return endmatch( Cpanel::StringFunc::Case::ToLower( $_[0] ), Cpanel::StringFunc::Case::ToLower( $_[1] ) );
}
1;
} # --- END Cpanel/StringFunc/Match.pm
{ # --- BEGIN Cpanel/StringFunc/File.pm
package Cpanel::StringFunc::File;
# use Cpanel::Logger ();
# use Cpanel::SafeFile ();
use Symbol ();
our $VERSION = '1.2';
my $logger;
sub addlinefile {
my ( $file, $line ) = @_;
if ( !-e $file ) { open( my $fh, '>>', $file ); close($fh); }
my $stl = Cpanel::SafeFile::safeopen( \*LDT, '+<', $file );
if ( !$stl ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("Could not read from $file");
return;
}
my @CFILE = <LDT>;
my $testline = $line;
$testline .= "\n" if ( $testline !~ /\n$/ );
if ( grep { $_ eq $testline } @CFILE ) { # no need to add as its already there
Cpanel::SafeFile::safeclose( \*LDT, $stl );
return 0;
}
print LDT $line . "\n";
Cpanel::SafeFile::safeclose( \*LDT, $stl );
return 1;
}
sub remlinefile {
my ( $file, $match_line, $matchtype ) = @_;
if ( !$file || !$match_line ) {
$logger ||= Cpanel::Logger->new();
$logger->invalid('remlinefile requires: file, match_line');
return;
}
elsif ( !-e $file ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("file $file does not exist.");
return;
}
chomp $match_line;
$match_line =~ s/^\s+//;
$match_line =~ s/\s+$//;
my $match_regex = ( defined $matchtype && $matchtype eq 'begin' ? qr/^\s*\Q$match_line\E\s*/ : qr/^\s*\Q$match_line\E\s*$/ );
my $sl = Cpanel::SafeFile::safeopen( \*LD, '+<', $file );
if ($sl) {
my @CFILE = <LD>;
if ( grep ( /$match_regex/, @CFILE ) ) { # no need to remove it if its not there
seek( LD, 0, 0 );
print LD grep( !/$match_regex/, @CFILE );
truncate( LD, tell(LD) );
Cpanel::SafeFile::safeclose( \*LD, $sl );
return 1;
}
else {
Cpanel::SafeFile::safeclose( \*LD, $sl );
return 0;
}
}
else {
my $logger = Cpanel::Logger->new();
$logger->warn("Unable to open file $file: $!");
return;
}
}
sub remlinefile_strict {
my ( $file, $match_regex ) = @_;
if ( !$file || !$match_regex ) {
$logger ||= Cpanel::Logger->new();
$logger->invalid('remlinefile requires: file, match_line');
return;
}
elsif ( !-e $file ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("file $file does not exist.");
return;
}
my $sl = Cpanel::SafeFile::safeopen( \*LD, '+<', $file );
if ($sl) {
my @CFILE = <LD>;
if ( grep ( /$match_regex/, @CFILE ) ) { # no need to remove it if its not there
seek( LD, 0, 0 );
print LD grep( !/$match_regex/, @CFILE );
truncate( LD, tell(LD) );
Cpanel::SafeFile::safeclose( \*LD, $sl );
return 1;
}
else {
Cpanel::SafeFile::safeclose( \*LD, $sl );
return 0;
}
}
else {
my $logger = Cpanel::Logger->new();
$logger->warn("Unable to open file $file: $!");
return;
}
}
sub add_lines_to_file_after {
my ( $file, $lines, $matchers ) = @_;
if ( !-e $file ) { open( my $fh, '>>', $file ); close($fh); }
my $fh = Symbol::gensym();
my $file_lock = Cpanel::SafeFile::safeopen( $fh, '+<', $file );
if ( !$file_lock ) {
$logger ||= Cpanel::Logger->new();
return ( 0, "Could not read from $file", 0 );
}
my $line_point = -1;
my %SEEN;
foreach my $line (@$matchers) {
seek( $fh, 0, 0 ); #start at the beginning of the file to look for the lines
while ( readline($fh) ) {
chomp;
$line_point = tell($fh) if ( $line_point == -1 && $_ eq $line );
$SEEN{$_} = 1;
}
last if ( $line_point != -1 ); #we found the insert point
}
if ( $line_point == -1 ) {
Cpanel::SafeFile::safeclose( $fh, $file_lock );
return ( 0, "Could not find any of the matchers in the file", 0 );
}
seek( $fh, $line_point, 0 );
my $end_of_file;
{
local $/;
$end_of_file = readline($fh);
}
seek( $fh, $line_point, 0 );
my $new_lines = 0;
foreach my $line (@$lines) {
( ++$new_lines && print {$fh} $line . "\n" ) if ( !exists $SEEN{$line} );
}
print {$fh} $end_of_file;
Cpanel::SafeFile::safeclose( $fh, $file_lock );
return ( 1, "Added $new_lines new lines", $new_lines );
}
sub get_line_from_file {
my ( $lookup_file, $lookup_key, $is_case_insensitive ) = @_;
my $line;
if ( open my $lookup_fh, '<', $lookup_file ) {
seek( $lookup_fh, 0, 0 );
my $search_regex = $is_case_insensitive ? qr/^\Q$lookup_key\E/i : qr/^\Q$lookup_key\E/;
while ( readline($lookup_fh) ) {
if ( $_ =~ $search_regex ) {
chomp();
$line = $_;
last;
}
}
close $lookup_fh;
}
return $line;
}
1;
} # --- END Cpanel/StringFunc/File.pm
{ # --- BEGIN Cpanel/StringFunc/SplitBreak.pm
package Cpanel::StringFunc::SplitBreak;
use strict;
my $comma_regex;
sub safesplit {
my @sp;
my $regex = $_[0] eq ',' && defined $comma_regex ? $comma_regex : qr{
(?=.) # This zero width positive look ahead assertion is necessary to avoid spurious empty item at the end of @sp
( #$1: The entire expression between separators, whether quoted or not, including trailing space and quotes if quoted
(?:
\s*
("|') #$2: The beginning quote
( #$3: Everything excluding the quote character, unless it's backslash-escaped.
(?:
\\\2|[^\2]
)*?
)
\2 # The closing quote
)?
([^\Q$_[0]\E]*) #$4: A non-quoted value: Anything excluding the separator. Same as $1 when text is non-quoted.
)
(?:\Q$_[0]\E)?
}xs;
$comma_regex = $regex if $_[0] eq ',' && !defined $comma_regex; #most common caller
if ( length $_[1] < 3096 ) {
my @results = $_[1] =~ m/$regex/g;
@sp = map { ( defined $results[ $_ * 4 + 2 ] ? $results[ $_ * 4 + 2 ] : $results[ $_ * 4 ] ) } ( 0 .. $#results / 4 );
}
else {
while ( $_[1] =~ m/$regex/g ) {
push @sp, defined $3 ? $3 : $1;
}
}
return @sp;
}
sub _word_split {
my ( $text, $width ) = @_;
return if ( !$width || !$text );
$width = int($width);
return if ( $width <= 0 );
my $template = ( 'A' . $width ) x ( length($text) / $width ) . ' A*';
my @tokens = unpack( $template, $text );
if ( $tokens[-1] eq '' ) {
pop @tokens;
}
return @tokens;
}
sub textbreak {
my $text = shift;
my $max_column_width = 60;
my $new_text = '';
pos $text = 0;
while ( pos $text < length $text ) {
if ( $text =~ m{ \G ([\s]+) }gcxms ) {
$new_text .= $1;
}
elsif ( $text =~ m{ \G ([\S]+) }gcxms ) {
$new_text .= join( ' ', _word_split( $1, $max_column_width ) );
}
}
return $new_text;
}
sub spacedjoin {
my $width = shift;
$width--;
return join( ' ', map { length($_) < $width ? $_ . ( " " x ( $width - length($_) ) ) : $_ } @_ );
}
1;
} # --- END Cpanel/StringFunc/SplitBreak.pm
{ # --- BEGIN Cpanel/StringFunc/UnquoteMeta.pm
package Cpanel::StringFunc::UnquoteMeta;
use strict;
sub unquotemeta {
my ($string) = @_;
return '' if !defined $string; # quotemeta() undef behavior
$string =~ s/\\(\\|)/$1/g;
return $string;
}
1;
} # --- END Cpanel/StringFunc/UnquoteMeta.pm
{ # --- BEGIN Cpanel/StringFunc.pm
package Cpanel::StringFunc;
use strict;
# use Cpanel::Logger ();
# use Cpanel::SafeFile ();
# use Cpanel::StringFunc::Case ();
# use Cpanel::StringFunc::Match ();
# use Cpanel::StringFunc::Trim ();
# use Cpanel::StringFunc::File ();
# use Cpanel::StringFunc::SplitBreak ();
my $logger = Cpanel::Logger->new();
our $VERSION = '1.4';
*ToUpper = \&Cpanel::StringFunc::Case::ToUpper;
*ToLower = \&Cpanel::StringFunc::Case::ToLower;
*textbreak = \&Cpanel::StringFunc::SplitBreak::textbreak;
*safesplit = \&Cpanel::StringFunc::SplitBreak::safesplit;
*beginmatch = \&Cpanel::StringFunc::Match::beginmatch;
*ibeginmatch = \&Cpanel::StringFunc::Match::ibeginmatch;
*endmatch = \&Cpanel::StringFunc::Match::endmatch;
*iendmatch = \&Cpanel::StringFunc::Match::iendmatch;
*endtrim = \&Cpanel::StringFunc::Trim::endtrim;
*trim = \&Cpanel::StringFunc::Trim::trim;
*ltrim = \&Cpanel::StringFunc::Trim::ltrim;
*rtrim = \&Cpanel::StringFunc::Trim::rtrim;
*begintrim = \&Cpanel::StringFunc::Trim::begintrim;
*addlinefile = \&Cpanel::StringFunc::File::addlinefile;
*remlinefile = \&Cpanel::StringFunc::File::remlinefile;
sub unquotemeta {
require Cpanel::StringFunc::UnquoteMeta; # it said do not add deps above...
goto &Cpanel::StringFunc::UnquoteMeta::unquotemeta;
}
sub countchar {
my $count = 0;
$count++ while $_[0] =~ /\Q$_[1]\E/g;
return $count;
}
sub get_curly_brace_count {
( ( $_[0] =~ tr/{// ) - ( $_[0] =~ tr/}// ) );
}
sub is_namespace {
my ($string) = @_;
return 1 if $string =~ m{ \A \w+ (::\w+)* \z }xms;
return;
}
sub get_file_from_namespace {
my ( $string, $not_abs ) = @_;
return if !is_namespace($string);
my $namespace = $string;
$string =~ s{::}{/}g;
$string .= '.pm';
return $string if $not_abs;
if ( !exists $INC{$string} ) {
eval "use $namespace ();";
}
return $INC{$string} if exists $INC{$string};
return;
}
sub get_dir_from_namespace {
my $file = get_file_from_namespace(@_);
$file =~ s{\.pm$}{};
return $file;
}
sub remove_control_m_str {
my ($string) = @_;
my $m = chr(13);
$string =~ s{$m}{}g;
return $string;
}
sub regex_rep_str {
my ( $string, $regex_ref, $error_hr ) = @_;
for my $hash ( ref $regex_ref eq 'ARRAY' ? @{$regex_ref} : ($regex_ref) ) {
next if ref $hash ne 'HASH';
for my $pair ( keys %{$hash} ) {
eval qq(\$string =~ s{\$pair}{$hash->{$pair}}go;);
$error_hr->{$string} = {
'error' => $@,
'find' => $pair,
'replace' => $hash->{$pair},
}
if $@
&& ref $error_hr eq 'HASH';
}
}
return $string;
}
sub regsrep {
my ( $file, $old, $new, $useregex, $search, $replace ) = @_;
my @CFILE;
if ( !-e $file ) {
$logger->warn("Could not find $file");
return;
}
my $filelock = Cpanel::SafeFile::safeopen( \*FH, '+<', $file );
if ( !$filelock ) {
$logger->warn("Could not open “$file” for editing: $!");
return;
}
while (<FH>) {
if ( $_ =~ m/^\s*$/ || $_ eq "\n" || $_ eq "\r\n" ) {
push @CFILE, $_;
}
elsif ( $_ =~ m{$old} ) {
next if $new eq '-1';
my $mnew = $new;
my $result1 = $1;
my $result2 = $2;
if ( defined $result1 ) {
$mnew =~ s{\$1}{$result1}g;
if ( defined $result2 ) {
$mnew =~ s{\$2}{$result2}g;
}
}
if ($search) {
$mnew =~ s{$search}{$replace}g;
}
if ($useregex) {
$mnew = $_;
$mnew =~ s{$old}{$new}g;
$mnew =~ tr{\n}{}d;
}
push @CFILE, "$mnew\n";
}
else {
push @CFILE, $_;
}
}
seek( FH, 0, 0 ) or warn "Seek error: $!";
print FH join( '', @CFILE ) or warn "Write error: $!";
truncate( FH, tell(FH) ) or warn "Truncate error: $!";
return Cpanel::SafeFile::safeclose( \*FH, $filelock );
}
sub addline {
my ( $file, %replacement_for_pattern ) = @_;
my (@CFILE);
if ( !-e $file ) {
$logger->warn("Could not find $file");
return;
}
my $filelock = Cpanel::SafeFile::safeopen( \*FH, '+<', $file );
if ( !$filelock ) {
$logger->warn("Could not edit $file");
return;
}
while ( my $line = <FH> ) {
if ( $line =~ m/^$/ || $line eq "\n" || $line eq "\r\n" ) {
push @CFILE, $line;
}
else {
my $replaced = 0;
while ( my ( $lineregex, $linereplace ) = each %replacement_for_pattern ) {
if ( $line =~ s/$lineregex/$linereplace/g ) {
$replaced = 1;
$line =~ s/\n//g;
push @CFILE, "$line\n";
delete $replacement_for_pattern{$lineregex};
}
}
if ( !$replaced ) {
push @CFILE, $line;
}
}
}
while ( my ( $lineregex, $linereplace ) = each %replacement_for_pattern ) {
push @CFILE, $linereplace . "\n";
}
seek( FH, 0, 0 );
print FH join( '', @CFILE );
truncate( FH, tell(FH) );
Cpanel::SafeFile::safeclose( \*FH, $filelock );
}
sub shuffle {
my $deck = shift; # $deck is a reference to an array
my $i = @$deck;
while ( $i-- ) {
my $j = int rand( $i + 1 );
@$deck[ $i, $j ] = @$deck[ $j, $i ];
}
}
sub lcmatch {
my ( $m1, $m2 ) = @_;
$m1 =~ tr/[A-Z]/[a-z]/;
$m2 =~ tr/[A-Z]/[a-z]/;
$m1 =~ s/[\r\n]*//g;
$m2 =~ s/[\r\n]*//g;
if ( $m1 eq $m2 ) { return (1); }
return (0);
}
sub indent_string {
my ( $string, $indentor ) = @_;
if ( !defined $indentor || $indentor eq '' ) {
$indentor = ' '; # four spaces, not \t
}
my $chomped = chomp($string);
$string =~ s{\n}{\n$indentor}g;
$string .= "\n" if $chomped; # only append a newline if we removed some whitespace
return $indentor . $string;
}
sub group_words {
my ($input) = @_;
$input =~ tr{A-Z}{a-z}; #lower-case ASCII
$input =~ s/[^a-z0-9_\s]//g; #get rid of anything else
$input =~ s/^\s+|\s+$//g; # Trim whitespace from both ends
$input =~ s/[-\s]+/_/g; # Replace all occurrences of spaces and hyphens with a single hyphen
return $input;
}
1;
} # --- END Cpanel/StringFunc.pm
{ # --- BEGIN Cpanel/FileUtils/Path.pm
package Cpanel::FileUtils::Path;
use strict;
# use Cpanel::FindBin ();
our $VERSION = '1.1';
sub findinpath {
my $bin = shift;
return '' if ( !$bin );
my @paths = split( /:/, $ENV{'PATH'} );
return cleanpath( Cpanel::FindBin::findbin( $bin, 'path' => \@paths ) );
}
sub cleanpath {
my $uncleanpath = shift || return;
my $abspath = ( substr( $uncleanpath, 0, 1 ) eq '/' ? 1 : 0 );
$uncleanpath =~ s/(?<!\.)\.\///g;
$uncleanpath =~ s/\/\.$//g;
$uncleanpath =~ tr/\///s;
my @pathdirs = split( /\//, $uncleanpath );
@pathdirs = grep( /.+/, @pathdirs );
my @cleanpathdirs;
my @back;
foreach my $dir (@pathdirs) {
if ( $dir ne '..' ) {
push( @cleanpathdirs, $dir );
}
else {
if ( $#cleanpathdirs == -1 ) {
push( @back, '..' );
}
else {
pop(@cleanpathdirs);
}
}
}
if ( $#back != -1 ) {
foreach (@back) {
unshift( @cleanpathdirs, $_ );
}
}
if ($abspath) {
while ( $#cleanpathdirs >= 0 && $cleanpathdirs[0] eq '..' ) {
shift @cleanpathdirs;
}
return ( '/' . join( '/', @cleanpathdirs ) );
}
return join( '/', @cleanpathdirs );
}
sub dir_and_file_from_path {
my ($file_path) = @_;
my @PATH_TEMP = split /\/+/, $file_path;
my $filename = pop @PATH_TEMP;
my $filedir = join q{/}, @PATH_TEMP;
$filedir = '/' if !length $filedir;
return ( $filedir, $filename );
}
1;
} # --- END Cpanel/FileUtils/Path.pm
{ # --- BEGIN Cpanel/FileUtils/Copy.pm
package Cpanel::FileUtils::Copy;
use strict;
# use Cpanel::Fcntl ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::SafeFile ();
our $VERSION = '1.0';
my $logger = Cpanel::Logger->new();
my $COPY_CHUNK_SIZE = 131072; #2 ** 17
sub safecopy {
my $srcfile = shift;
my $destfile = shift;
my $normrfcomp = shift || 0;
if ( !length $srcfile ) {
$logger->warn("Source not specified for copy.");
return 0;
}
if ( !length $destfile ) {
$logger->warn("Destination not specified for copy.");
return 0;
}
if ( !-r $srcfile && $srcfile !~ m/\*$/ ) {
$logger->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) {
$src_lock = Cpanel::SafeFile::safelock($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 && $src_lock ) { Cpanel::SafeFile::safeunlock($src_lock) }
if ($val) {
$logger->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;
$logger->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);
}
$logger->warn(qq{rcopy('$srcfile', '$destfile') failed: $err_msg});
$! = $err_no;
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: $!" );
}
return 1; #Nothing to do!
};
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 $!;
$write_lock = 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: $!" );
}
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/FileUtils/Link.pm
package Cpanel::FileUtils::Link;
use strict;
# use Cpanel::Logger ();
# use Cpanel::SafeFile ();
sub safeunlink {
my $file = shift;
return 1 if !-l $file && !-e _;
if ( unlink $file ) {
return 1;
}
else {
Cpanel::Logger::cplog( "Unable to unlink $file: $!", 'warn', __PACKAGE__, 1 );
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 _ );
open( ORI, '<', $orig ) || return 0;
my $destlock = Cpanel::SafeFile::safeopen( \*DEST, '>', $dest ) || do {
Cpanel::Logger::cplog( "Unable to open $dest for write!", 'warn', __PACKAGE__ );
close(ORI);
return 0;
};
while (<ORI>) {
print DEST;
}
close(ORI);
Cpanel::SafeFile::safeclose( \*DEST, $destlock );
if ( -z $orig != -z $dest ) {
unlink($dest);
Cpanel::Logger::cplog( "Unable to properly write $dest", 'warn', __PACKAGE__ );
return 0;
}
unless ( chown( $uid, $gid, $dest ) ) {
Cpanel::Logger::cplog( "Unable to chown $dest to UID $uid GID $gid", 'warn', __PACKAGE__ );
}
unless ( chmod( $mode, $uid, $dest ) ) {
Cpanel::Logger::cplog( "Unable to chmod $dest for UID $uid", 'warn', __PACKAGE__ );
}
unless ( utime( $atime, $mtime, $dest ) ) {
Cpanel::Logger::cplog( "Unable to set utime on $dest for UID $uid", 'warn', __PACKAGE__ );
}
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/FileUtils/Move.pm
package Cpanel::FileUtils::Move;
use strict;
# use Cpanel::Rand ();
# use Cpanel::Logger ();
# use Cpanel::FileUtils::Link ();
sub safemv {
my $srcfile = shift;
my $option;
if ( $srcfile =~ m/^\-/ ) {
$option = $srcfile;
$srcfile = shift;
}
my $destfile = shift;
my $returnval = 0;
my $clobber = 0;
my $verbose = 0;
my $archive = 0;
if ( !-e $srcfile ) {
Cpanel::Logger::cplog( "$srcfile does not exist.", 'warn', __PACKAGE__ );
return 0;
}
return 0 if !$destfile;
if ( $option && $option ne '--' ) {
if ( $option =~ m/f/i ) { $clobber = 1; }
if ( $option =~ m/v/i ) { $verbose = 1; }
if ( $option =~ m/a/i ) { $archive = 1; }
}
if ( !$clobber && -e $destfile ) {
print "Unable to move, $destfile exists!" if $verbose;
Cpanel::Logger::cplog( "Unable to move, $destfile, needs force option.", 'warn', __PACKAGE__ );
return 0;
}
elsif ( $clobber && $archive && -e $destfile ) {
my $tmpdestfile = Cpanel::Rand::get_tmp_file_by_name( $destfile, 'cpbak', $Cpanel::Rand::TYPE_FILE, $Cpanel::Rand::SKIP_OPEN ); # audit case 46806 ok
if ( !rename( $destfile, $tmpdestfile ) ) {
Cpanel::Logger::cplog( "Unable to rename $destfile: $!", 'warn', __PACKAGE__ );
return 0;
}
else {
print "Renamed destination file to $tmpdestfile\n" if $verbose;
}
}
elsif ( -e $destfile ) {
unlink $destfile;
}
if ( !rename( $srcfile, $destfile ) ) {
if ( !Cpanel::FileUtils::Link::_replicate_file( $srcfile, $destfile ) ) {
return 0;
}
unlink $srcfile;
if ( -e $srcfile ) {
unlink $destfile;
return 0;
}
}
print "Moved: $srcfile -> $destfile\n" if $verbose;
return 1;
}
1;
} # --- END Cpanel/FileUtils/Move.pm
{ # --- BEGIN Cpanel/FileUtils/Equiv.pm
package Cpanel::FileUtils::Equiv;
use strict;
# use Cpanel::Logger ();
our $VERSION = '1.0';
sub equivalent_files {
my $file1 = shift;
my $file2 = shift;
if ( !$file1 || !$file2 ) {
Cpanel::Logger::cplog( 'Invalid arguments for file_compare', 'warn', __PACKAGE__, 1 );
return;
}
return 1 if $file1 eq $file2;
my ( $dev1, $inode1, $size1 );
if ( -e $file1 ) {
( $dev1, $inode1, $size1 ) = ( stat(_) )[ 0, 1, 7 ];
}
my ( $dev2, $inode2, $size2 );
if ( -e $file2 ) {
( $dev2, $inode2, $size2 ) = ( stat(_) )[ 0, 1, 7 ];
}
if ( $dev1 == $dev2 && $inode1 == $inode2 && $size1 == $size2 ) {
return 1;
}
return;
}
1;
} # --- END Cpanel/FileUtils/Equiv.pm
{ # --- BEGIN Cpanel/FileUtils/Lines.pm
package Cpanel::FileUtils::Lines;
use strict;
# use Cpanel::Logger ();
our $VERSION = '1.0';
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 $linecounter = 0;
while ( my $line = readline($cfg_fh) ) {
chomp $line;
if ( $linecounter > $number ) {
shift @lines;
}
push @lines, $line;
$linecounter++;
}
close $cfg_fh;
}
else {
Cpanel::Logger::logger(
{
'message' => "Unable to open $cfgfile: $!",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => 0,
'backtrace' => 0,
}
);
}
return wantarray ? @lines : \@lines;
}
1;
} # --- END Cpanel/FileUtils/Lines.pm
{ # --- BEGIN Cpanel/FileUtils.pm
package Cpanel::FileUtils;
use strict;
no strict 'subs';
use IO::File ();
# use Cpanel::SafeFile ();
# use Cpanel::StringFunc ();
# use Cpanel::Logger ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::FileUtils::Path ();
# use Cpanel::FileUtils::Copy ();
# use Cpanel::FileUtils::Link ();
# use Cpanel::FileUtils::Move ();
# use Cpanel::FileUtils::Equiv ();
# use Cpanel::FileUtils::Lines ();
# use Cpanel::FileUtils::Write ();
my $logger = Cpanel::Logger->new();
our $VERSION = '1.9';
*writefile = \&Cpanel::FileUtils::Write::writefile;
sub has_txt_in_file {
my $file = shift;
my $txt = shift;
my $fh = IO::File->new;
my $regex;
eval { $regex = qr($txt); };
if ($@) {
$logger->warn('Invalid regex');
return;
}
if ( open $fh, '<', $file ) {
while ( my $line = readline $fh ) {
if ( $line =~ $regex ) {
close $fh;
return 1;
}
}
close $fh;
}
return;
}
sub walk {
my ( $rcount, $rdata ) = @_;
my $begin = $$rcount;
$$rcount = index( $$rdata, "\n", $begin + 1 );
if ( $$rcount == -1 ) {
return undef;
}
return substr( $$rdata, $begin, ( $$rcount - $begin ) );
}
sub remove_control_m_file {
my ($file) = @_;
return if !-f $file;
my @new_contents;
if ( !-e $file ) { Cpanel::FileUtils::TouchFile::touchfile($file); }
my $filelock = Cpanel::SafeFile::safeopen( \*FH, '+<', $file ); # or return;
if ( !$filelock ) {
$logger->warn("Could not edit $file");
return;
}
while (<FH>) {
push @new_contents, Cpanel::StringFunc::remove_control_m_str($_);
}
seek( FH, 0, 0 );
print FH @new_contents;
truncate( FH, tell(FH) );
Cpanel::SafeFile::safeclose( \*FH, $filelock ); # or return ;
}
sub regex_rep_file {
my ( $file, $regex_ref, $error_hr ) = @_;
my @new_contents;
if ( !-e $file ) { Cpanel::FileUtils::TouchFile::touchfile($file); }
my $filelock = Cpanel::SafeFile::safeopen( \*FH, '+<', $file ); # or return;
if ( !$filelock ) {
$logger->warn("Could not edit $file");
return;
}
while ( my $line = readline FH ) {
if ( $line !~ /^$/ && $line ne "\n" && $line ne "\r\n" ) {
$line = Cpanel::StringFunc::regex_rep_str( $line, $regex_ref, $error_hr );
}
push @new_contents, $line;
}
return if ref $error_hr eq 'HASH' && keys %{$error_hr};
seek( FH, 0, 0 );
print FH @new_contents;
truncate( FH, tell(FH) );
Cpanel::SafeFile::safeclose( \*FH, $filelock ); # or return ;
}
sub touchfile {
goto &Cpanel::FileUtils::TouchFile::touchfile;
}
sub equivalent_files {
goto &Cpanel::FileUtils::Equiv::equivalent_files;
}
sub findinpath {
goto &Cpanel::FileUtils::Path::findinpath;
}
sub cleanpath {
goto &Cpanel::FileUtils::Path::cleanpath;
}
sub safecopy {
goto &Cpanel::FileUtils::Copy::safecopy;
}
sub safemv {
goto &Cpanel::FileUtils::Move::safemv;
}
sub safeunlink {
goto &Cpanel::FileUtils::Link::safeunlink;
}
sub _replicate_file {
goto &Cpanel::FileUtils::Link::_replicate_file;
}
sub safelink {
goto &Cpanel::FileUtils::Link::safelink;
}
sub get_file_lines {
goto &Cpanel::FileUtils::Lines::get_file_lines;
}
sub get_last_lines {
goto &Cpanel::FileUtils::Lines::get_last_lines;
}
sub appendline {
my $filename = shift;
my $line = shift;
my $fh = IO::File->new;
if ( open $fh, '>>', $filename ) {
print $fh $line . "\n";
close $fh;
return 1;
}
return;
}
1;
} # --- END Cpanel/FileUtils.pm
{ # --- BEGIN Cpanel/Config/LoadConfig/Tiny.pm
package Cpanel::Config::LoadConfig::Tiny;
sub loadConfig {
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';
if ( open( my $fh, '<', $file ) ) {
local $/;
my ( $parser_code, $name, $value, $k, $v, $count );
if ( $use_hash_of_arr_refs || $pretreatline || $allow_undef_values || !length $delimiter ) {
$parser_code = '
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 = ' %{$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 = ' %{$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;
if ($@) {
die "Failed to parse $file: $@";
}
}
return wantarray ? %{$conf_ref} : $conf_ref;
}
1;
} # --- END Cpanel/Config/LoadConfig/Tiny.pm
{ # --- BEGIN Cpanel/Parser/Vars.pm
package Cpanel::Parser::Vars;
use strict;
our ( $current_tag, $can_leave_cpanelaction, $buffer ) = ( '', 1, '' );
our ( $incpanelaction, $altmode, $jsonmode, $xmlmode, $javascript, $title, $input, $style, $embtag, $textarea ) = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
our ( $file, $firstfile ) = ( '[stdin]', '[stdin]' );
our $trap_defaultfh = undef; # Known to be boolean.
1;
} # --- END Cpanel/Parser/Vars.pm
{ # --- BEGIN Cpanel/Locale/Utils/Paths.pm
package Cpanel::Locale::Utils::Paths;
sub get_locale_yaml_root {
return '/usr/local/cpanel/locale';
}
sub get_locale_yaml_local_root {
return '/var/cpanel/locale.local';
}
sub get_locale_database_root {
return '/var/cpanel/locale';
}
sub get_legacy_lang_root {
return '/usr/local/cpanel/lang';
}
sub get_legacy_lang_cache_root {
return '/var/cpanel/lang.cache';
}
sub get_i_locales_config_path {
return '/var/cpanel/i_locales';
}
1;
} # --- END Cpanel/Locale/Utils/Paths.pm
{ # --- BEGIN Cpanel/Locale/Utils.pm
package Cpanel::Locale::Utils;
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 ( !-e $cdb_file ) {
_logger()->warn("Missing CDB file $cdb_file specified for readonly operation");
return;
}
if ( !$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;
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 {
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" ) {
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" ) {
if ( !$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;
}
else {
_logger()->info(qq{No such locale as '$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' }, );
}
my %CHARSET_ALIASES = ( # unpreferred preferred
"ASCII" => "US-ASCII",
"BIG5-ETEN" => "BIG5",
"CP1251" => "WINDOWS-1251",
"CP1252" => "WINDOWS-1252",
"CP936" => "GBK",
"CP949" => "KS_C_5601-1987",
"EUC-CN" => "GB2312",
"KS_C_5601" => "KS_C_5601-1987",
"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",
);
my @all_charmaps;
my @non_alias_charmaps;
my @filesystem_charmaps;
sub get_charmap_list {
my ( $root_says_to_make_symlinks, $no_aliases ) = @_;
if ($no_aliases) {
return @non_alias_charmaps if @non_alias_charmaps;
}
else {
return @all_charmaps if @all_charmaps;
}
if ( !@filesystem_charmaps ) {
@filesystem_charmaps = qw(utf-8 us-ascii);
my $charmapsdir = -e '/usr/local/share/i18n/charmaps' ? '/usr/local/share/i18n/charmaps' : '/usr/share/i18n/charmaps';
for my $key ( keys %CHARSET_ALIASES ) {
if ( $root_says_to_make_symlinks && $> == 0 ) {
lstat("$charmapsdir/$key.gz"); # The stat preceding -l _ wasn't an lstat at ...
if ( -e _ ) {
lstat("$charmapsdir/$CHARSET_ALIASES{$key}.gz"); # The stat preceding -l _ wasn't an lstat at ...
if ( !-e _ && !-l _ ) {
symlink( "$charmapsdir/$key.gz", "$charmapsdir/$CHARSET_ALIASES{$key}.gz" );
}
}
elsif ( !-l _ && -e "$charmapsdir/$CHARSET_ALIASES{$key}.gz" ) {
symlink( "$charmapsdir/$CHARSET_ALIASES{$key}.gz", "$charmapsdir/$key.gz" );
}
}
}
if ( opendir my $charmaps_dh, $charmapsdir ) {
@filesystem_charmaps = map { m{\A([^.].*)\.gz\z} ? $1 : () } readdir $charmaps_dh;
closedir $charmaps_dh;
}
}
my %charmaps;
my %excluded_charmaps =
$no_aliases
? ( map { tr{A-Z}{a-z}; $_ => 1 } keys %CHARSET_ALIASES )
: ();
for my $cm ( @filesystem_charmaps, ( $no_aliases ? ( values %CHARSET_ALIASES ) : %CHARSET_ALIASES ) ) {
$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;
}
}
if ($no_aliases) {
return @non_alias_charmaps = values %charmaps;
}
else {
return @all_charmaps = values %charmaps;
}
}
sub cdb_mtime_is_old {
my ( $cdb_file, $locale ) = @_;
my $cdb_mtime = ( stat($cdb_file) )[9] or return 1;
my $theme_path = '';
if ( $cdb_file =~ m{/themes/([^/]+)/} ) {
$theme_path = "/usr/local/cpanel/base/frontend/$1";
}
foreach my $file (
$theme_path
? ( "$theme_path/locale/$locale.yaml", "$theme_path/locale/$locale.yaml.local" )
: ( Cpanel::Locale::Utils::Paths::get_locale_yaml_root() . "/$locale.yaml", Cpanel::Locale::Utils::Paths::get_locale_yaml_local_root() . "/$locale.yaml" )
) {
my $file_mtime = ( stat($file) )[9] || 0;
return 1 if ( $cdb_mtime < $file_mtime );
}
return;
}
1;
} # --- END Cpanel/Locale/Utils.pm
{ # --- BEGIN Cpanel/CPAN/I18N/LangTags.pm
require 5.000;
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
require 5;
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;
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;
$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/^([-+]?\d+)(\d{3})/$1,$2/s ) { 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/([^':]+)(?:::)?$/s;
$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 ) = @_;
if (@methods) {
$handle->{'blacklist'} = { map { $_ => 1 } @methods };
}
else {
$handle->{'blacklist'} = {};
}
no strict 'refs';
$handle->{'blacklist'} = {
%{ $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 { /^_/ } keys %{ __PACKAGE__ . "::" }
),
};
}
sub whitelist {
my ( $handle, @methods ) = @_;
if (@methods) {
$handle->{'whitelist'} = { map { $_ => 1 } @methods };
}
else {
delete $handle->{'whitelist'};
}
}
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 ( exists $h_r->{$phrase} ) {
DEBUG and warn " Found \"$phrase\" in $h_r\n";
unless ( ref( $value = $h_r->{$phrase} ) ) {
if ( !defined $value || $value eq '' ) {
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 ( $phrase !~ m/^_/s 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) ) {
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");
}
}
elsif ( 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 {
if ( exists $INC{'utf8.pm'} || eval { local $SIG{'__DIE__'}; require utf8; } ) {
utf8->import();
DEBUG and warn " utf8 on for _compile()\n";
}
else {
DEBUG and warn " utf8 not available for _compile() ($INC{'utf8.pm'})\n$@\n";
}
}
sub _compile {
return \"$_[1]" if $_[1] !~ tr/[//;
my ( $handle, $target, $call_count, $big_pile, @c, @code ) = ( $_[0], ( ref( $_[0] ) || $_[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 '' ) {
$target->_die_pointing( $under_one, 'Unterminated bracket group' );
}
else {
$target->_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 (
( ord('A') == 65 )
? $c[-1] !~ m/[^\x20-\x7E]/s
: $c[-1] !~ m/[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/s
)
) {
$c[-1] =~ s/'/\\'/g;
push @code, q{ '} . $c[-1] . "',\n";
$c[-1] = ''; # reuse this slot
}
else {
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] =~ m/^\s+$/s ) {
DEBUG > 2 and warn " -- (Ignoring)\n";
$c[-1] = ''; # reset out chink
next;
}
( $m, @params ) = split( /,/, $c[-1], -1 ); # was /\s*,\s*/
if ( ord('A') == 65 ) { # ASCII, etc
foreach ( $m, @params ) { tr/\x7F/,/ }
}
else { # EBCDIC (1047, 0037, POSIX-BC)
foreach ( $m, @params ) { tr/\x07/,/ }
}
if ( $m eq '_*' or $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 =~ /^\w+$/s
&& !$handle->{'blacklist'}{$m}
&& ( !defined $handle->{'whitelist'} || $handle->{'whitelist'}{$m} )
) {
push @code, ' $_[0]->' . $m . '(';
}
else {
$target->_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 ( $p =~ m/^_(-?\d+)$/s ) {
$code[-1] .= '$_[' . ( 0 + $1 ) . '], ';
}
elsif (
$USE_LITERALS and (
( ord('A') == 65 )
? $p !~ m/[^\x20-\x7E]/s
: $p !~ m/[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/s
)
) {
$p =~ s/'/\\'/g;
$code[-1] .= q{'} . $p . q{', };
}
else {
push @c, $p;
push @code, ' $c[' . $#c . '], ';
}
}
$code[-1] .= "),\n";
push @c, '';
}
else {
$target->_die_pointing( $under_one, q{Unbalanced ']'} );
}
}
elsif ( substr( $1, 0, 1 ) ne '~' ) {
my $text = $1;
$text =~ s/\\/\\\\/g;
$c[-1] .= $text;
}
elsif ( $1 eq '~~' ) { # "~~"
$c[-1] .= '~';
}
elsif ( $1 eq '~[' ) { # "~["
$c[-1] .= '[';
}
elsif ( $1 eq '~]' ) { # "~]"
$c[-1] .= ']';
}
elsif ( $1 eq '~,' ) { # "~,"
if ($in_group) {
if ( ord('A') == 65 ) { # 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;
$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";
if ( @code == 0 ) { # not possible?
DEBUG and warn "Empty code\n";
return \'';
}
elsif ( @code > 1 ) { # most cases, presumably!
unshift @code, "join '',\n";
}
unshift @code, "use strict; sub {\n";
push @code, "}\n";
DEBUG and warn @code;
my $sub = eval( join '', @code );
die "$@ while evalling" . join( '', @code ) if $@; # Should be impossible.
return $sub;
}
sub _die_pointing {
my $target = shift; # 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/CPAN/Locale/Maketext/Pseudo.pm
package Cpanel::CPAN::Locale::Maketext::Pseudo;
use warnings;
use strict;
our $VERSION = q('0.0.3');
# use Exporter();
our @ISA;
BEGIN { push @ISA, qw(Exporter); }
our @EXPORT_OK = qw(env_maketext env_print env_fetch env_say env_get set_maketext_obj);
my $_maketext_obj;
sub new {
my ( $class, $args_ref ) = @_;
my $self = bless {}, $class;
set_maketext_obj($self) if !$args_ref->{'skip_env'};
return $self;
}
sub set_maketext_obj {
$_maketext_obj = shift;
return;
}
sub env_maketext {
my ( $string, @args ) = @_;
if ( ref $_maketext_obj && $_maketext_obj->can('maketext') ) {
$string = $_maketext_obj->maketext( $string, @args );
}
else {
require Local::Maketext::Pseudo;
Local::Maketext::Pseudo->new( { 'skip_env' => $ENV{'maketext_obj_skip_env'} } )->maketext( $string, @args );
}
return $string;
}
sub env_print {
print env_maketext(@_);
}
sub env_fetch {
return env_maketext(@_);
}
sub env_say {
my $text = env_maketext(@_);
local $/ = !defined $/ || !$/ ? "\n" : $/; # otherwise assume they are not stupid
print $text . $/ if $text;
}
sub env_get {
my $text = env_maketext(@_);
local $/ = !defined $/ || !$/ ? "\n" : $/; # otherwise assume they are not stupid
return $text . $/ if $text;
return;
}
sub maketext {
my ( $fake, $string, @args ) = @_;
for my $idx ( 1 .. scalar(@args) ) {
$string =~ s{ \[ [_]( [-]?$idx ) \] }{$args[ substr($1, 0, 1) eq '-' ? $1 : ($1 - 1) ]}xmsg;
}
return $string;
}
sub print {
print shift->maketext(@_);
}
sub fetch {
return shift->maketext(@_);
}
sub say {
my $text = shift->maketext(@_);
local $/ = !defined $/ || !$/ ? "\n" : $/; # otherwise assume they are not stupid
print $text . $/ if $text;
}
sub get {
my $text = shift->maketext(@_);
local $/ = !defined $/ || !$/ ? "\n" : $/; # otherwise assume they are not stupid
return $text . $/ if $text;
return;
}
1;
} # --- END Cpanel/CPAN/Locale/Maketext/Pseudo.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.pm
package Cpanel::CPAN::Locales;
use strict;
$Cpanel::CPAN::Locales::VERSION = 0.30_1; # change in POD
$Cpanel::CPAN::Locales::cldr_version = '2.0'; # change in POD
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");
}
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");
}
my ( $language, $territory ) = split_tag( $locale->{'locale'} );
no strict 'refs'; ## no critic (ProhibitNoStrict)
$locale->{'language'} = $language;
$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"},
'code_to_name' => \%{"$class\::DB::Language::$tag\::code_to_name"},
'name_to_code' => \%{"$class\::DB::Language::$tag\::name_to_code"},
};
$locale->{'territory'} = $territory;
$locale->{'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"},
'name_to_code' => \%{"$class\::DB::Territory::$tag\::name_to_code"},
};
$locale->{'misc'}{'list_quote_mode'} = 'none';
$singleton_stash{$tag} = bless $locale, $class;
}
return $singleton_stash{$tag};
}
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");
no strict 'refs'; ## no critic (ProhibitNoStrict)
$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};
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})';
$string =~ s/\{0\}/$ln/g;
$string =~ s/\{1\}/$tn/g;
return $string;
}
return;
}
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'},
];
}
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");
no strict 'refs'; ## no critic (ProhibitNoStrict)
$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");
no strict 'refs'; ## no critic (ProhibitNoStrict)
$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 get_list_or {
my ( $self, @items ) = @_;
$self->_quote_get_list_items( \@items );
return if !@items;
return $items[0] if @items == 1;
return "$items[0] or $items[1]" if @items == 2;
my $last = pop(@items);
return join( ', ', @items ) . ", or $last";
}
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] =~ m/\A(?: |\xc2\xa0)+\z/ ) {
$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, @items ) = @_;
$self->_quote_get_list_items( \@items );
return if !@items;
return $items[0] if @items == 1;
if ( @items == 2 ) {
my $two = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list'}{'2'};
$two =~ s/\{([01])\}/$items[$1]/g;
return $two;
}
else {
@items = map { my $c = $_; defined $c && $c =~ s/\{([01])\}/__\{__${1}__\}__/g; $c } @items; # I know ick, patches welcome
my $aggregate = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list'}{'start'};
$aggregate =~ s/\{([01])\}/$items[$1]/g;
for my $i ( 2 .. $#items ) {
next if $i == $#items;
my $middle = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list'}{'middle'};
$middle =~ s/\{0\}/$aggregate/g;
my $item = defined $items[$i] ? $items[$i] : '';
$middle =~ s/\{1\}/$item/g;
$aggregate = $middle;
}
my $end = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'list'}{'end'};
$end =~ s/\{0\}/$aggregate/g;
$end =~ s/\{1\}/$items[-1]/g;
$end =~ s/__\{__([01])__\}__/\{$1\}/g; # See "I know ick, patches welcome" above
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}';
$pattern =~ s/\{0\}/$str/;
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}';
$pattern =~ s/\{(0|1)\}/$_[$1 + 1]/g; # use index instead of variable to avoid formatter confusion, e.g. $first contains the string '{1}'
return $pattern;
}
sub get_formatted_ellipsis_final {
my ( $self, $str ) = @_;
my $pattern = $self->{'language_data'}{'misc_info'}{'cldr_formats'}{'ellipsis'}{'final'} || '{0}…';
$pattern =~ s/\{0\}/$str/;
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/\.[0-9]+/\.$trim/;
}
}
else {
$n = sprintf( '%.' . $max_len . 'f', $n );
return $n if $n =~ tr/Ee//; # poor man's is exponential check.
}
$n =~ s{([^0-9]+[0-9]*?[1-9])0+$}{$1};
$n =~ s{[^0-9]+0+$}{};
$n =~ s/^[^0-9]+//; # strip signs since any would be defined in pattern
my $format = $_my_pattern || $self->{'language_data'}{'misc_info'}{'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( /(?<!\')\;(?!\')/, $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;
$dec_sec_cnt++ while ( $format =~ m/(?<!\')\.(?!\')/g );
if ( $dec_sec_cnt != 1 ) {
require Carp;
Carp::carp("Format should have one decimal section. Using default pattern.");
$format = '#,##0.###';
}
if ( !defined $format || $format eq '' || $format =~ m/^\s+$/ ) {
require Carp;
Carp::carp("Format is empty. Using default pattern.");
$format = '#,##0.###';
}
my $result = '';
if ( $format eq '#,##0.###' ) {
$result = $n;
while ( $result =~ s/^([-+]?\d+)(\d{3})/$1,$2/s ) { 1 } # right from perlfaq5
}
else {
my ( $integer, $decimals ) = split( /\./, $n, 2 );
my ( $i_pat, $d_pat ) = split( /(?<!\')\.(?!\')/, $format, 2 );
my ( $cur_idx, $trailing_non_n, $cur_d, $cur_pat ) = ( 0, '' ); # buffer
my @i_pat = reverse( split( /(?<!\')\,(?!\')/, $i_pat ) );
my $next_to_last_pattern = @i_pat == 1 ? $i_pat[0] : $i_pat[-2];
$next_to_last_pattern =~ s/0$/#/;
while ( $i_pat[0] =~ s/((?:\'.\')+)$// || $i_pat[0] =~ s/([^0#]+)$// ) {
$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 ( $i_pat[$cur_idx] =~ m/(\',\')$/ ) {
$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/(?<!\')\#(?!\')//g; # 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/((?:\'.\')+)$// || $d_pat[-1] =~ s/([^0#]+)$// ) {
$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 ( $d_pat[$cur_idx] =~ m/^(\'.\')/ ) {
$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, 1 ) eq ',' ) {
substr( $result, -1, 1, '' );
}
if ( defined $d_pat[$cur_idx] ) {
$d_pat[$cur_idx] =~ s/(?<!\')\#(?!\')//g; # remove any left over non-literal #
$result .= $d_pat[$cur_idx]; # append it (e.g. 0 and -)
}
$result .= $trailing_non_n;
}
}
$result =~ s/(?<!\')\.(?!\')/_LOCALES-DECIMAL-PLACEHOLDER_/g; # _LOCALES-DECIMAL-PLACEHOLDER_' not likley to be in CLDR format ;) - if that does not hold true then append "time . $$" to placeholder
$result =~ s/(?<!\')\,(?!\')/$self->{language_data}{misc_info}{cldr_formats}{_decimal_format_group}/g;
$result =~ s/_LOCALES-DECIMAL-PLACEHOLDER_/$self->{language_data}{misc_info}{cldr_formats}{_decimal_format_decimal}/g;
if ( $is_negative && !$negative_pat ) {
$result = "-$result";
}
return $result;
}
sub get_territory_codes {
return keys %{ shift->{'territory_data'}{'code_to_name'} };
}
sub get_territory_names {
return values %{ shift->{'territory_data'}{'code_to_name'} };
}
sub get_territory_lookup {
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;
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);
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 {
return keys %{ shift->{'language_data'}{'code_to_name'} };
}
sub get_language_names {
return values %{ shift->{'language_data'}{'code_to_name'} };
}
sub get_language_lookup {
return %{ shift->{'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;
if ( exists $self->{'language_data'}{'code_to_name'}{$code} ) {
return $self->{'language_data'}{'code_to_name'}{$code};
}
elsif ($always_return) {
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})';
$string =~ s/\{0\}/$ln/g;
$string =~ s/\{1\}/$tn/g;
return $string;
}
return;
}
sub get_code_from_language {
my ( $self, $name ) = @_;
return if !$name;
my $key = normalize_for_key_lookup($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{"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{"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 {
my $tag = $_[0];
return if !defined $tag;
$tag =~ tr/A-Z/a-z/;
$tag =~ s{\s+}{}g;
$tag =~ s{[^a-z0-9]+$}{}; # I18N::LangTags::locale2language_tag() does not allow trailing '_'
$tag =~ s{[^a-z0-9]+}{_}g;
while ( $tag =~ s/([^_]{8})([^_])/$1\_$2/ ) { } # I18N::LangTags::locale2language_tag() only allows parts bewteen 1 and 8 character
return $tag;
}
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;
$key =~ s{[\'\"\-\(\)\[\]\_]+}{}g;
return $key;
}
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;
}
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_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::CPAN::Locales::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
# use Cpanel::CPAN::Locale::Maketext::Pseudo ();
# use Cpanel::Encoder::Punycode ();
@Cpanel::CPAN::Locale::Maketext::Utils::ISA = qw(Cpanel::CPAN::Locale::Maketext);
my %singleton_stash = ();
sub _compile {
my ( $lh, $string, @args ) = @_;
$string =~ s/_TILDE_/~~/g; # this helps make parsing easier (via code or visually)
my $compiled = $lh->SUPER::_compile($string);
return $compiled if ref($compiled) ne 'CODE';
return sub {
my ( $lh, @ref_args ) = @_;
@ref_args = map { s/\_(\-?[0-9]+|\*)/-!-$1-!-/g if defined; $_ } @ref_args;
my $built = $compiled->( $lh, @ref_args ); # if an method that supported embedded args ever looked for /\_(\-?[0-9]+|\*)/ and acted upon it then it'd need to be aware of this convention and operate on /-!-(\-?[0-9]+|\*)-!-/ instead (or better yet don't have it look for an act upon things that look like bracket notation arguments)
$built =~ s/-!-(\-?[0-9]+|\*)-!-/_$1/g; # 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) = @_;
Cpanel::CPAN::Locale::Maketext::Pseudo::set_maketext_obj($lh) if !$ENV{'maketext_obj_skip_env'};
$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 ( $key =~ m/^_/s ) {
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 ( $key =~ m/^_/s ) {
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 !~ m{ \A \w+ (::\w+)* \z }xms;
my $base = $is_base_class ? $ns : $lh->get_base_class();
no strict 'refs';
for my $pkg ( ref $pkgs ? @{$pkgs} : $pkgs ) {
next if $pkg !~ m{ \A \w+ (::\w+)* \z }xms;
*{ $base . '::' . $pkg . '::VERSION' } = *{ $ns . '::VERSION' };
*{ $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 = shift->get_language_class();
$ns =~ s{::\w+$}{};
return $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 '::', shift->get_language_class() )[-1];
}
sub print {
local $Carp::CarpLevel = 1;
print shift->maketext(@_);
}
sub fetch {
local $Carp::CarpLevel = 1;
return shift->maketext(@_);
}
sub say {
local $Carp::CarpLevel = 1;
my $text = shift->maketext(@_);
local $/ = !defined $/ || !$/ ? "\n" : $/; # otherwise assume they are not stupid
print $text . $/ if $text;
}
sub get {
local $Carp::CarpLevel = 1;
my $text = shift->maketext(@_);
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) );
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 {
require Carp;
Carp::croak('text() requires a singlef parameter') unless @_ == 2;
my ( $handle, $phrase ) = splice( @_, 0, 2 );
Carp::confess('No handle/phrase') unless ( defined($handle) && defined($phrase) );
if ( !$handle->{'use_external_lex_cache'} ) {
Carp::carp("text() requires you to have 'use_external_lex_cache' enabled.");
return;
}
my $at = $@;
@_ = @_;
my $value;
foreach my $h_r ( @{ $handle->_lex_refs } ) { # _lex_refs() caches itself
if ( exists $h_r->{$phrase} ) {
if ( ref( $h_r->{$phrase} ) ) {
Carp::carp("Previously compiled phrase ('use_external_lex_cache' enabled after phrase was compiled?)");
}
$value = $h_r->{$phrase};
last;
}
elsif ( $phrase !~ m/^_/s and $h_r->{'_AUTO'} ) {
$value = $phrase;
last;
}
}
unless ( defined($value) ) {
}
$@ = $at; # Put $@ back in case we altered it along the way.
return $phrase if !defined $value || $value eq '';
return $value;
}
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();
$path =~ s{::}{/}g; # !!!! make this File::Spec safe !! File::Spec->separator() !-e
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) ) {
$pm =~ s{\.pm$}{};
next PM if !$pm;
next PM if $pm eq 'Utils';
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"
$langname->{$code} = $lh->{'Locales.pm'}{'_main_'}->get_language_from_code( $code, 1 );
if ( defined $native ) {
$native->{$code} = $lh->{'Locales.pm'}{'_main_'}->get_native_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 {
my ($lh) = @_;
return ( ref($lh) || $lh );
}
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();
$inc_key =~ s{::}{/}g; # TODO make portable via File::Spec
$inc_key .= '.pm';
if ( exists $INC{$inc_key} ) {
if ( -e $INC{$inc_key} ) {
$lh->{'Cpanel::CPAN::Locale::Maketext::Utils'}{'_base_clase_dir'} = $INC{$inc_key};
$lh->{'Cpanel::CPAN::Locale::Maketext::Utils'}{'_base_clase_dir'} =~ s{\.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 sort map { ( m{([^/]+)\.pm$} && $1 ne 'Utils' && $1 ne 'Lazy' ) ? $1 : () } 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;
$ret = $code->($root);
return $ret if defined $ret;
my $loc_obj = $lh->get_locales_obj($tag);
my $loc; # buffer
my %seen = ( $root => 1 );
for $loc ( $loc_obj->get_fallback_list( $lh->{'Locales.pm'}{'get_fallback_list_special_lookup_coderef'} ) ) {
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 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 ( $string =~ m/%s\b/ ) {
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 list {
require Carp;
Carp::carp('list() is deprecated, use list_and() or list_or() instead');
my $lh = shift;
my $com_sep = ', ';
my $oxford = ',';
my $def_sep = '&';
if ( ref($lh) ) {
$com_sep = $lh->{'list_separator'} if exists $lh->{'list_separator'};
$oxford = $lh->{'oxford_separator'} if exists $lh->{'oxford_separator'};
$def_sep = $lh->{'list_default_and'} if exists $lh->{'list_default_and'};
}
my $sep = shift || $def_sep;
return if !@_;
my @expanded = map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @_;
if ( @expanded == 1 ) {
return $expanded[0];
}
elsif ( @expanded == 2 ) {
return CORE::join( " $sep ", @expanded );
}
else {
my $last = pop @expanded;
return CORE::join( $com_sep, @expanded ) . "$oxford $sep $last";
}
}
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 !~ m/\A[0-9]+\z/ ) {
$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 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 );
$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();
}
}
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) }
sub output_nbsp {
return "\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->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 {
shift;
require Math::Units;
return Math::Units::convert(@_);
}
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 $str !~ m/\_(\-?[0-9]+)/;
my @args = __caller_args( $_[1] ); # this way be dragons
$str =~ s/\_(\-?[0-9]+)/$args[$1]/g;
return $str;
}
sub __caller_args {
package DB;
() = caller( $_[0] + 3 );
return @DB::args;
}
sub __proc_emb_meth {
my ( $lh, $str ) = @_;
$str =~ s/(su[bp])\(((?:\\\)|[^\)])+?)\)/my $s=$2;my $m="output_$1";$s=~s{\\\)}{\)}g;$lh->$m($s)/eg;
$str =~ s/chr\(((?:\d+|[\S]))\)/$lh->output_chr($1)/eg;
$str =~ s/numf\((\d+(?:\.\d+)?)\)/$lh->numf($1)/eg;
$str =~ s/amp\(\)/$lh->output_amp()/eg;
return $str;
}
sub output {
my ( $lh, $output_function, $string, @output_function_args ) = @_;
if ( defined $string && $string ne '' && $string =~ tr/(// ) {
$string = __proc_emb_meth( $lh, $string );
}
if ( $output_function eq 'url' && defined $output_function_args[0] && $output_function_args[0] ne '' && $output_function_args[0] =~ tr/(// ) {
$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 ) = @_;
return Cpanel::Encoder::Punycode::punycode_encode_str($s);
}
sub output_decode_puny {
my ( $self, $s ) = @_;
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/\A\d+\z/ ) {
return if length($chr_num) != 1;
return $chr_num if !$lh->context_is_html();
return
$chr_num eq '"' ? '"'
: $chr_num eq '&' ? '&'
: $chr_num eq "'" ? '''
: $chr_num eq '<' ? '<'
: $chr_num eq '>' ? '>'
: $chr_num;
}
return if $chr_num !~ m/\A\d+\z/;
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 ? '"'
: $chr_num == 38 ? '&'
: $chr_num == 39 || $chr_num == 145 || $chr_num == 146 ? '''
: $chr_num == 60 ? '<'
: $chr_num == 62 ? '>'
: $chr_num == 173 ? '­'
: $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 {
my ($lh) = @_;
if ( !exists $lh->{'-t-STDIN'} ) {
$lh->set_context();
}
return 'plain' if !defined $lh->{'-t-STDIN'};
return 'ansi' if $lh->{'-t-STDIN'};
return 'html' if !$lh->{'-t-STDIN'};
return $lh->{'-t-STDIN'};
}
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/Cookies.pm
package Cpanel::Cookies;
$Cpanel::Cookies::VERSION = '0.1';
sub get_cookie_hashref_from_string {
return {} if !defined $_[0];
my ( $name, $value );
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;
sub read_dir {
my ( $dir, $coderef ) = @_;
if ( !-d $dir ) {
$! = 20;
return;
}
if ( !defined $coderef || ref $coderef ne 'CODE' ) {
$coderef = sub { return 1; };
}
my @contents;
if ( opendir my $dir_dh, $dir ) {
while ( my $file = readdir($dir_dh) ) {
next if $file =~ m{ \A [.]+ \z }xms;
push @contents, $file if $coderef->($file);
}
closedir $dir_dh;
return wantarray ? @contents : \@contents;
}
else {
return;
}
}
1;
} # --- END Cpanel/SafeDir/Read.pm
{ # --- BEGIN Cpanel/CPAN/YAML/Syck.pm
package Cpanel::CPAN::YAML::Syck;
eval { local $SIG{__DIE__} = sub { warn "YAML\:\:Syck is not available (attempting to ignore)."; }; require YAML::Syck; };
sub _init {
$YAML::Syck::LoadBlessed = 0;
{
no warnings 'redefine';
*Cpanel::CPAN::YAML::Syck::_init = sub { };
}
}
_init();
1;
} # --- END Cpanel/CPAN/YAML/Syck.pm
{ # --- BEGIN Cpanel/Locale/Utils/MkDB.pm
package Cpanel::Locale::Utils::MkDB;
# use Cpanel::Locale::Utils ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeDir::Read ();
# use Cpanel::Logger ();
# use Cpanel::Locale::Utils::Legacy ();
$Cpanel::Locale::Utils::MkDB::only_non_existant = 0;
my $logger = Cpanel::Logger->new();
sub from_hash {
my ( $save_to, $hr, $force_level, $charset ) = @_;
my $mtime = 0;
require Cpanel::CPAN::YAML::Syck;
$YAML::Syck::ImplicitTyping = 0;
if ( $force_level == 2 && -e $save_to ) {
unlink $save_to or return ( 0, translatable("Could not unlink “[_1]”: [_2]"), $save_to, $! );
}
else {
if ( -e $save_to ) {
my %test;
my $tie = Cpanel::Locale::Utils::get_readonly_tie( $save_to, \%test );
my $corrupt = $tie ? 0 : 1;
undef $tie;
untie %test;
if ($corrupt) {
Cpanel::Logger->new()->info("Detected corrupt CDB file, removing so that it can be rebuilt ...");
unlink $save_to or return ( 0, translatable("Could not unlink “[_1]”: [_2]"), $save_to, $! );
}
}
$mtime = 1;
}
if ( !$force_level ) {
my $changed = -e $save_to ? 0 : 1;
my %read;
my $rtie;
if ( !$changed ) {
$rtie = Cpanel::Locale::Utils::get_readonly_tie( $save_to, \%read ) || $changed++;
if ( !$changed && exists $hr->{'__VERSION'} && exists $read{'__VERSION'} && $read{'__VERSION'} ne $hr->{'__VERSION'} ) {
$changed++;
}
elsif ( !$changed && exists $read{'__FORENSIC'} ) {
my $cur_struct = YAML::Syck::Load( $read{'__FORENSIC'} );
my $cur_len = exists $cur_struct->{'order'} && int scalar( ref( $cur_struct->{'order'} ) eq 'ARRAY' ? @{ $cur_struct->{'order'} } : () );
my $new_len = exists $hr->{'__FORENSIC'}{'order'} && int scalar( ref( $hr->{'__FORENSIC'}{'order'} ) eq 'ARRAY' ? @{ $hr->{'__FORENSIC'}{'order'} } : () );
if ( $cur_len == $new_len ) {
for my $idx ( 0 .. $cur_len - 1 ) {
if ( $cur_struct->{'order'}[$idx] ne $hr->{'__FORENSIC'}{'order'}[$idx] ) {
$changed++;
last;
}
if ( $cur_struct->{'mtime'}{ $cur_struct->{'order'}[$idx] } ne $hr->{'__FORENSIC'}{'mtime'}{ $hr->{'__FORENSIC'}{'order'}[$idx] } ) {
$changed++;
last;
}
}
}
else {
$changed++;
}
}
}
if ( !$changed ) {
undef $rtie;
untie %read;
return ( 1, translatable("CDB file “[_1]” is already current"), $save_to );
}
undef $rtie;
untie %read;
}
if ($mtime) {
$mtime = ( stat($save_to) )[9] || 6;
$mtime -= 5;
utime( $mtime, $mtime, $save_to ); # ? update touchfile() to take an arg to specify desired a/mtime ?
}
my $build_attempt = 1;
BUILD:
my %new;
while ( my ( $k, $v ) = each %{$hr} ) {
next if $k eq 'charset';
if ( $k eq '__FORENSIC' ) {
$new{$k} = YAML::Syck::Dump($v);
next;
}
if ( defined $charset ) {
my $new_k = $k;
my $new_v = $v;
require Encode;
$new_k = Encode::decode( $charset, $new_k );
$new_v = Encode::decode( $charset, $new_v );
$new_k = Encode::encode( 'utf-8', $new_k );
$new_v = Encode::encode( 'utf-8', $new_v );
if ( !$Cpanel::Locale::Utils::MkDB::only_non_existant || !exists $new{$new_k} ) {
$new{$new_k} = $new_v; # mtime is updated, even if the key or value is not new
}
if ( !defined $new{$new_k} || $new{$new_k} eq '' ) {
$new{$new_k} = $new_k; # hash is one-sided so fallback to the key itself
}
}
else {
if ( !$Cpanel::Locale::Utils::MkDB::only_non_existant || !exists $new{$k} ) {
$new{$k} = $v; # mtime is updated, even if the key or value is not new
}
if ( !defined $new{$k} || $new{$k} eq '' ) {
$new{$k} = $k; # hash is one-sided so fallback to the key itself
}
}
if ( Cpanel::Locale::Utils::Legacy::phrase_is_legacy_key($k) ) {
$new{$k} = __make_legacy_quote_safe( $new{$k} );
}
else {
$new{$k} = __make_markup_safe( $new{$k} );
}
}
my $create_db_status = Cpanel::Locale::Utils::create_cdb( $save_to, \%new );
if ( !$create_db_status ) {
if ( $build_attempt > 2 ) {
return ( 0, "File not updated “[_1]”: [_2]", $save_to, $! );
}
$logger->info("Could not get create_cdb on '$save_to' ($!), retrying ...");
$! = 0;
sleep($build_attempt);
$build_attempt++;
goto BUILD;
}
if ( $force_level == 2 ) {
return ( 1, "File updated “[_1]”", $save_to ) if -s $save_to;
if ( $build_attempt > 2 ) {
return ( 0, "File not updated “[_1]”: [_2]", $save_to, $! );
}
$logger->info("Writeable tie on non-existent '$save_to' ($!) resulted in empty or non-existant file, retrying ...");
$! = 0;
sleep($build_attempt);
$build_attempt++;
goto BUILD;
}
else {
return ( 1, "File updated “[_1]”", $save_to ) if ( stat($save_to) )[9] > $mtime;
if ( $build_attempt > 2 ) {
return ( 0, "File not updated “[_1]”: [_2]", $save_to, $! );
}
$logger->info("Writeable tie on existing '$save_to' ($!) had no mtime update, retrying ...");
$! = 0;
sleep($build_attempt);
$build_attempt++;
goto BUILD;
}
}
sub get_hash_of_legacy_file_or_its_cache {
my ($legacy_file) = @_;
require Cpanel::Locale::Utils::Legacy;
my $legacy_file_cache = Cpanel::Locale::Utils::Legacy::get_legacy_file_cache_path($legacy_file);
if ( -e $legacy_file_cache ) {
require Cpanel::SafeStorable;
my $hr;
eval { local $SIG{__DIE__}; local $SIG{__WARN__}; $hr = Cpanel::SafeStorable::retrieve($legacy_file_cache); };
return $hr || {};
}
else {
return get_hash_of_legacy_file($legacy_file) || {};
}
}
sub get_hash_of_legacy_file {
my ($legacy_file) = @_;
if ( open my $lang_fh, '<', $legacy_file ) {
my @TEMP_LOAD;
while ( my $line = readline $lang_fh ) {
next if ( !( $line =~ s/\s+$// ? $line : $line ) || $line =~ m{^\s*//} || $line !~ tr/=// );
push @TEMP_LOAD, split( /=/, $line, 2 );
}
close $lang_fh;
return {@TEMP_LOAD};
}
else {
return;
}
}
sub __make_markup_safe {
my ($phrase) = @_;
eval "require Cpanel::CPAN::Locale::Maketext::Utils::Phrase;"; # It'd be odd for this to fail other than when compiling a 5.6 binary, hence the error message below
if ($@) {
$logger->die("from_hash() can not be called in compiled code due to a qr// in a CPAN module that Cpanel::CPAN::Locale::Maketext::Utils::Phrase needs.");
}
my $struct = $phrase =~ tr/~[]// ? Cpanel::CPAN::Locale::Maketext::Utils::Phrase::phrase2struct($phrase) : [$phrase];
my %map = (
"'" => 39,
'"' => 34,
'<' => 60,
'>' => 62,
'&' => 38,
);
$phrase = '';
for my $piece ( @{$struct} ) {
if ( !ref($piece) ) {
if ( $piece =~ tr/'"<>&// ) {
$piece =~ s/'/[output,apos]/g;
$piece =~ s/"/[output,quot]/g;
$piece =~ s/</[output,lt]/g;
$piece =~ s/>/[output,gt]/g;
$piece =~ s/&/[output,amp]/g;
}
$phrase .= $piece;
}
else {
$piece->{'cont'} =~ s/(chr[(,])(['"<>&])/$1$map{$2}/g; # turn all method and embedded ones into numeric
$piece->{'cont'} =~ s/(['"<>&])/chr\($map{$1}\)/g; # embed the rest. in the event the method supports embedded methods great, in the event it doesn't at least it won't have markup
$phrase .= "[$piece->{'cont'}]";
}
}
return $phrase;
}
sub __make_legacy_quote_safe {
my ($phrase) = @_;
$phrase =~ s{(?<!.=)'}{[output,apos]}g;
$phrase =~ s{(?<!.=)"}{[output,quot]}g;
$phrase =~ s{(.='[^']*?)\[output,apos\]}{$1'}g;
$phrase =~ s{(.="[^"]*?)\[output,quot\]}{$1"}g;
$phrase =~ s{'}{"}g;
return $phrase;
}
sub translatable { ## no extract maketext
return $_[0];
}
1;
} # --- END Cpanel/Locale/Utils/MkDB.pm
{ # --- BEGIN Cpanel/Locale/Utils/Legacy.pm
package Cpanel::Locale::Utils::Legacy;
use strict;
# use Cpanel::Locale::Utils::Paths ();
# use Cpanel::Locale::Utils::MkDB ();
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()
'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 { };
}
}
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;
for my $name ( grep { $_ !~ m/^\./ } ( $args{'no_root'} ? () : Cpanel::SafeDir::Read::read_dir('/usr/local/cpanel/lang') ), @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';
$legacy_file =~ s{/usr/local/cpanel/lang}{/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 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;
@charset_lookup{ map { Cpanel::CPAN::Locales::normalize_tag($_) } Cpanel::Locale::Utils::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::CPAN::Locales::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::CPAN::Locales::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 ) {
$legacy_lookup = {
%{ Cpanel::Locale::Utils::MkDB::get_hash_of_legacy_file('/usr/local/cpanel/lang/english-utf8') || {} },
%{ Cpanel::Locale::Utils::MkDB::get_hash_of_legacy_file('/usr/local/cpanel/base/frontend/x3/lang/english-utf8') || {} },
};
}
return 1 if exists $legacy_lookup->{$key};
return;
}
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/ArrayFunc.pm
package Cpanel::ArrayFunc;
use strict;
our $VERSION = '1.2';
sub reorder {
my $element = shift;
my $rARRY = shift;
my $c = 0;
@{$rARRY} = grep { $_ ne $element or ++$c and 0 } @{$rARRY};
for ( 1 .. $c ) {
push( @{$rARRY}, $element );
}
}
sub uniq_from_arrayrefs {
my %seen;
my @final_values = ();
my @temp = map { @{$_} } grep { ref $_ eq 'ARRAY' } @_;
foreach my $value (@temp) {
unless ( defined( $seen{$value} ) ) {
push @final_values, $value;
$seen{$value} = 1;
}
}
return wantarray ? @final_values : [@final_values];
}
sub uniq_from_aoh {
my @uniq;
my %seen_refs_lookup;
HASH:
foreach my $hashref ( map { @{$_} } grep { ref $_ eq 'ARRAY' } @_ ) {
if ( ref $hashref ne 'HASH' ) {
push @uniq, $hashref;
}
else {
next HASH
if exists $seen_refs_lookup{"$hashref"}; # double quotes for explicity not necessity
$seen_refs_lookup{"$hashref"}++; # double quotes for explicity not necessity
SEEN:
for my $seen_item (@uniq) {
next SEEN
if ref $seen_item ne 'HASH'; # from first if(), this check saves us from having another array @seen
next SEEN if ( keys %{$seen_item} != keys %{$hashref} );
my $diff = 0;
SEEN_CHECK:
for my $seen_item_key ( keys %{$seen_item} ) {
if ( exists $hashref->{$seen_item_key} ) {
if ( $seen_item->{$seen_item_key} ne $hashref->{$seen_item_key} ) {
$diff++;
last SEEN_CHECK;
}
}
else {
$diff++;
last SEEN_CHECK;
}
}
if ( !$diff ) {
HASH_CHECK:
for my $hashref_key ( keys %{$hashref} ) {
if ( exists $seen_item->{$hashref_key} ) {
if ( $hashref->{$hashref_key} ne $seen_item->{$hashref_key} ) {
$diff++;
last HASH_CHECK;
}
}
else {
$diff++;
last HASH_CHECK;
}
}
}
next HASH if !$diff;
}
push @uniq, $hashref;
}
}
return wantarray ? @uniq : \@uniq;
}
sub any { $_ && return $_ for @_; 0 } #FG: RETURN THE FIRST TRUE VALUE, NOT 1
sub all { $_ || return $_ for @_; 1 } #FG: RETURN THE FALSE VALUE, IF ANY
sub none { $_ && return 0 for @_; 1 }
sub notall { $_ || return 1 for @_; 0 }
sub true {
scalar grep { $_ } @_;
}
sub false {
scalar grep { !$_ } @_;
}
sub first (&@) {
my $code = shift;
foreach (@_) {
return $_ if &{$code}(); # see comment at mapfirst() below
}
undef;
}
sub mapfirst (&@) {
my $code = shift;
foreach (@_) {
my $val = &{$code}($_); # see comment above
return $val if $val;
}
undef;
}
sub uniq (@) {
my %seen;
return grep { !$seen{$_}++ } @_;
}
sub sum (@) {
my $sum;
if (@_) {
$sum = 0;
$sum += $_ for @_;
}
return $sum;
}
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 ];
}
$_[0];
}
1;
} # --- END Cpanel/ArrayFunc.pm
{ # --- BEGIN Cpanel/StringFunc/LineIterator.pm
package Cpanel::StringFunc::LineIterator;
use strict;
sub new { ##no critic qw(RequireArgUnpacking)
my $class = $_[0];
my $self = bless {
_todo_cr => $_[2],
_buffer_sr => \$_[1],
_first_modified_offset => length $_[1],
},
"${class}::InProgress";
return $self->_run();
}
sub has_changed {
my ($self) = @_;
return $self->{'_has_changed'} ? 1 : 0;
}
sub stopped {
my ($self) = @_;
return $self->{'_stopped'} ? 1 : 0;
}
sub get_first_modified_offset {
my ($self) = @_;
return $self->{'_has_changed'} ? $self->{'_first_modified_offset'} : undef;
}
package Cpanel::StringFunc::LineIterator::InProgress;
use strict;
# use Cpanel::StringFunc::LineIterator();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::StringFunc::LineIterator); }
use Try::Tiny;
sub _run {
my ($self) = @_;
my $todo_cr = $self->{'_todo_cr'};
my $iteration_index = 0;
$self->{'_iteration_index_sr'} = \$iteration_index;
my $buffer_sr = $self->{'_buffer_sr'};
pos($$buffer_sr) = 0;
try {
my $line;
$self->{'_line_sr'} = \$line;
while ( $$buffer_sr =~ m<([^\n]*\n|[^\n]+\z)>g ) {
my $cur_line = $line = $1;
for ($cur_line) {
$todo_cr->($self);
$iteration_index++;
}
}
}
catch {
die $_ if !UNIVERSAL::isa( $_, __PACKAGE__ . '::_STOP' );
$self->{'_stopped'} = 1;
};
my $done_class = __PACKAGE__;
$done_class =~ s<::InProgress\z><>;
return bless $self, $done_class;
}
sub prepend { ##no critic qw(RequireArgUnpacking)
my $self = $_[0];
return $self->replace_with( $_[1] . ${ $self->{'_line_sr'} } );
}
sub append { ##no critic qw(RequireArgUnpacking)
my $self = $_[0];
return $self->replace_with( ${ $self->{'_line_sr'} } . $_[1] );
}
sub replace_with { ##no critic qw(RequireArgUnpacking)
my $self = $_[0];
my $old_length = length ${ $self->{'_line_sr'} };
my $new_length = length $_[1];
my $start_pos_of_change = pos( ${ $self->{'_buffer_sr'} } ) - $old_length;
substr(
${ $self->{'_buffer_sr'} },
$start_pos_of_change,
$old_length,
$_[1],
);
if ( $start_pos_of_change < $self->{'_first_modified_offset'} ) {
$self->{'_first_modified_offset'} = $start_pos_of_change;
}
pos( ${ $self->{'_buffer_sr'} } ) = $start_pos_of_change + $new_length;
$self->{'_has_changed'} = 1;
${ $self->{'_line_sr'} } = $_[1];
return;
}
sub get_iteration_index {
my ($self) = @_;
return ${ $self->{'_iteration_index_sr'} };
}
sub get_buffer_position {
my ($self) = @_;
return pos ${ $self->{'_buffer_sr'} };
}
sub stop {
my ($self) = @_;
die Cpanel::StringFunc::LineIterator::InProgress::_STOP->new();
}
package Cpanel::StringFunc::LineIterator::InProgress::_STOP;
sub new {
my ($class) = @_;
my $scalar;
my $self = \$scalar;
return bless $self, $class;
}
1;
} # --- END Cpanel/StringFunc/LineIterator.pm
{ # --- BEGIN Cpanel/PwUtils.pm
package Cpanel::PwUtils;
use strict;
# use Cpanel::Exception ();
# use Cpanel::PwCache ();
# use Cpanel::StringFunc::LineIterator ();
sub normalize_to_uid {
my ($user) = @_;
if ( !length $user ) {
die Cpanel::Exception::create( 'MissingParameter', 'Supply a username or a user ID.' );
}
my ( $uid, $user_gid, @gids );
if ( $user =~ m{\A\d+\z} ) {
$uid = $user;
}
else {
$uid = ( Cpanel::PwCache::getpwnam($user) )[2];
if ( !defined $uid ) {
die Cpanel::Exception::create( 'UserNotFound', { name => $user } );
}
}
return $uid;
}
sub lookup_entry_from_pw_text {
my ( $passwd_sr, $matcher_cr ) = @_;
my $result;
Cpanel::StringFunc::LineIterator->new(
$$passwd_sr,
sub {
my ( $iterator, $line ) = ( shift, $_ );
my @fields = split /:/, $line;
if ( $matcher_cr->( \@fields ) ) {
$result = \@fields;
$iterator->stop;
}
}
);
return $result;
}
1;
} # --- END Cpanel/PwUtils.pm
{ # --- BEGIN Cpanel/AccessIds/Utils.pm
package Cpanel::AccessIds::Utils;
use strict;
# use Cpanel::ArrayFunc ();
# use Cpanel::Logger ();
# use Cpanel::PwCache ();
# use Cpanel::PwUtils ();
sub normalize_user_and_groups {
my ( $user, @groups ) = @_;
my $uid = Cpanel::PwUtils::normalize_to_uid($user);
@groups = grep { defined } @groups;
my @gids;
if (@groups) {
@gids = map { m{\A\d+\z} ? $_ : scalar( ( getgrnam $_ )[2] ) } @groups;
}
else {
@gids = ( Cpanel::PwCache::getpwuid($uid) )[3];
}
return ( $uid, Cpanel::ArrayFunc::uniq(@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(@args) );
}
sub set_egid {
my @gids = @_;
if ( !@gids ) {
Cpanel::Logger->new()->die("No arguments passed to set_egid()!");
}
_check_positive_int($_) for @gids;
my $new_egid = join( q{ }, $gids[0], Cpanel::ArrayFunc::uniq(@gids) );
return _set_var( \$), 'EGID', $new_egid );
}
sub set_rgid {
my ( $gid, @extra_gids ) = @_;
if (@extra_gids) {
Cpanel::Logger->new()->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 {
my ($val) = @_;
if ( !length $val || $val !~ m{\A\d+\z} ) {
Cpanel::Logger->new()->die("“$val” is not a positive integer!");
}
return 1;
}
sub _set_var {
my ( $var_r, $name, $desired_value ) = @_;
my $error;
my $old_value = $$var_r;
$$var_r = $desired_value;
my $new_value = $$var_r;
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;
}
else {
@desired_parts = sort { $a <=> $b } Cpanel::ArrayFunc::uniq(@desired_parts);
@new_parts = sort { $a <=> $b } Cpanel::ArrayFunc::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;
}
}
if ($error) {
my $logger = Cpanel::Logger->new();
$logger->die("Failed to change $name from “$old_value” to “$new_value”: $!");
}
return 1;
}
1;
} # --- END Cpanel/AccessIds/Utils.pm
{ # --- BEGIN Cpanel/AccessIds/SetUids.pm
package Cpanel::AccessIds::SetUids;
use strict;
# use Cpanel::PwCache ();
# use Cpanel::AccessIds::Utils ();
our $VERSION = '1.2';
sub setuids {
my ( $uid, $gid, @additional_gids ) = Cpanel::AccessIds::Utils::normalize_user_and_groups(@_);
if ( $< != 0 ) {
require Cpanel::Logger;
Cpanel::Logger->new()->die("setuids failed: Attempting to setuid as a normal user with RUID $<");
}
if ( $> != 0 ) {
require Cpanel::Logger;
Cpanel::Logger->new()->die("setuids failed: Attempting to setuid as a normal user with EUID $>");
}
Cpanel::PwCache::pwmksafecache();
if ( !defined $uid || !defined $gid ) {
require Cpanel::Logger;
Cpanel::Logger->new()->die("setuids failed: Could not resolve UID or GID (@_)");
}
Cpanel::AccessIds::Utils::set_egid( $gid, @additional_gids );
Cpanel::AccessIds::Utils::set_rgid($gid);
Cpanel::AccessIds::Utils::set_euid($uid);
Cpanel::AccessIds::Utils::set_ruid($uid);
return $uid;
}
1;
} # --- END Cpanel/AccessIds/SetUids.pm
{ # --- BEGIN Cpanel/AccessIds/ReducedPrivileges.pm
package Cpanel::AccessIds::ReducedPrivileges;
use strict;
# use Cpanel::PwCache ();
# use Cpanel::Logger ();
# use Cpanel::AccessIds::Utils ();
sub new {
my $class = shift;
if ( $class ne __PACKAGE__ ) {
my $logger = Cpanel::Logger->new();
$logger->die("Attempting to drop privileges as '$class'.");
}
my ( $uid, @gids ) = Cpanel::AccessIds::Utils::normalize_user_and_groups(@_);
_allowed_to_reduce_privileges();
_prevent_dropping_to_root( $uid, @gids );
my $self = {
'uid' => $>,
'gid' => $),
'user' => scalar( ( Cpanel::PwCache::getpwuid($uid) )[0] ),
'new_uid' => $uid,
'new_gid' => join( q< >, @gids ),
};
_reduce_privileges( $uid, @gids );
return bless $self;
}
sub DESTROY {
my ($self) = @_;
_allowed_to_restore_privileges( $self->{'new_uid'}, $self->{'new_gid'} );
_restore_privileges( $self->{'uid'}, $self->{'gid'} );
}
sub call_as_user {
my ( $code, $uid, $gid, @supplemental_gids ) = Cpanel::AccessIds::Utils::normalize_code_user_groups(@_);
_prevent_dropping_to_root( $uid, $gid );
if ( !$code ) {
my $logger = Cpanel::Logger->new();
$logger->die("No code reference supplied.");
}
_allowed_to_reduce_privileges();
my ( $saved_uid, $saved_gid ) = ( $>, $) );
_reduce_privileges( $uid, $gid, @supplemental_gids );
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 ) {
my $logger = Cpanel::Logger->new();
$logger->die("Attempting to drop privileges as a normal user with RUID $<");
}
if ( $> != 0 ) {
my $logger = Cpanel::Logger->new();
$logger->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 {
my (@uids_and_gids) = @_;
if ( grep { !$_ } @uids_and_gids ) {
my $logger = Cpanel::Logger->new();
$logger->die("Attempting to drop privileges to root.");
}
return 1;
}
sub _allowed_to_restore_privileges {
my ( $uid, $gid ) = @_;
if ( $< != 0 ) {
my $logger = Cpanel::Logger->new();
$logger->die("Attempting to restore privileges as a normal user with RUID $<");
}
if ( $> != $uid ) {
my $logger = Cpanel::Logger->new();
$logger->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 ) {
my $logger = Cpanel::Logger->new();
$logger->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 );
return 1;
}
1;
} # --- END Cpanel/AccessIds/ReducedPrivileges.pm
{ # --- BEGIN Cpanel/Syscall.pm
package Cpanel::Syscall;
use strict;
use warnings;
# use Cpanel::OSSys::Bits ();
my %NAME_TO_NUMBER;
sub _set_system_call_numbers {
my @constants = qw(
close 6 3
fcntl 55 72
lchown 16 94
getrlimit 191 97
gettimeofday 78 96
sendfile 187 40
setrlimit 75 160
splice 313 275
write 4 1
setsid 66 112
);
my $bits = Cpanel::OSSys::Bits::getbits();
my $idx = $bits == 32 ? 0 : 1;
while ( my ( $name, @vals ) = splice( @constants, 0, 3 ) ) {
$NAME_TO_NUMBER{$name} = $vals[$idx];
}
return;
}
BEGIN {
_set_system_call_numbers();
}
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)
my ($name) = shift;
local $!;
my $ret = CORE::syscall(
( $NAME_TO_NUMBER{$name} || _die_unknown_syscall($name) ),
@_,
);
if ( ( $ret == -1 ) && $! ) {
if ( $INC{'Cpanel/Exception.pm'} ) {
die Cpanel::Exception::create( 'SystemCall', { name => $name, error => $! } );
}
else {
die "Failed system call “$name”: $!";
}
}
return $ret;
}
1;
} # --- END Cpanel/Syscall.pm
{ # --- BEGIN Cpanel/Sys/Setsid.pm
package Cpanel::Sys::Setsid;
use strict;
# use Cpanel::Syscall ();
# use Cpanel::Exception ();
sub full_daemonize {
my $opts = shift;
my $pid = fork();
if ( !defined $pid ) {
die Cpanel::Exception::create( 'IO::ForkError', { error => $! } );
}
elsif ($pid) {
if ( $opts->{'keep_parent'} ) {
waitpid( $pid, 0 );
return $pid;
}
else {
exit;
}
}
else {
Cpanel::Syscall::syscall('setsid');
my $cpid = fork();
if ( !defined $cpid ) {
die Cpanel::Exception::create( 'IO::ForkError', { error => $! } );
}
elsif ($cpid) {
waitpid( $cpid, 0 ) if $opts->{'keep_parent'};
my $ec = $? >> 8;
exit $ec;
}
else {
return $cpid;
}
}
}
sub fast_setsid {
my $TIOCNOTTY = 0x5422;
setpgrp( 0, 0 );
open( my $tty, '+<', '/dev/tty' ) or 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.pm
{ # --- BEGIN Cpanel/AccessIds.pm
package Cpanel::AccessIds;
use strict;
use Try::Tiny;
# use Cpanel::ForkSync ();
# use Cpanel::PwCache ();
# use Cpanel::Logger ();
# use Cpanel::Carp ();
# use Cpanel::AccessIds::SetUids ();
# use Cpanel::AccessIds::ReducedPrivileges ();
# use Cpanel::AccessIds::Utils ();
# use Cpanel::Sys::Setsid ();
our $VERSION = '1.4';
my $logger;
{
no warnings 'once';
*setuid = \&Cpanel::AccessIds::SetUids::setuids;
*setuids = \&Cpanel::AccessIds::SetUids::setuids;
*run_as_user_group = \&runasusergroup;
*run_as_user = \&runasuser;
}
sub runasuser {
my $user = shift;
my $gid = ( Cpanel::PwCache::getpwnam($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::getpwnam($user) )[7];
}
else {
$homedir = ( Cpanel::PwCache::getpwuid($user) )[7];
}
if ( my $pid = fork() ) {
waitpid( $pid, 0 );
}
elsif ( defined $pid ) {
Cpanel::Sys::Setsid::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 {
my ( $code, $user, $group ) = Cpanel::AccessIds::Utils::normalize_code_user_groups(@_);
my $setuid_coderef = sub {
Cpanel::Sys::Setsid::fast_setsid();
Cpanel::AccessIds::SetUids::setuids( $user, $group );
return $code->(@_);
};
my $forksync = Cpanel::ForkSync->new($setuid_coderef);
if ( defined $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 {
local $@;
my ( $code, $user, $group ) = eval { Cpanel::AccessIds::Utils::normalize_code_user_groups(@_) };
return if !length $user;
return if !length $group;
if ( !$user || !$group ) {
die Cpanel::Carp::safe_longmess("do_as_user_group may not be called for root.");
}
if ( !$code || ref $code ne 'CODE' ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("Failed to provide CODE");
return;
}
my $setuid_coderef = sub {
Cpanel::Sys::Setsid::fast_setsid();
Cpanel::AccessIds::SetUids::setuids( $user, $group );
return $code->(@_);
};
return Cpanel::ForkSync::do_in_child($setuid_coderef);
}
*do_as_current_user = \&Cpanel::ForkSync::do_in_child;
sub loadfile_as_user {
my $user = shift;
my $file = shift;
my ( $uid, $gid );
try {
( $uid, $gid ) = Cpanel::AccessIds::Utils::normalize_user_and_groups($user);
}
catch {
warn $_->to_string();
};
$logger ||= Cpanel::Logger->new();
if ( !defined $uid || !defined $gid ) {
$logger->warn('Attempting to use non-existent user.');
return;
}
my $data;
if ( $< != 0 && $uid != $> ) {
$logger->panic("Attempting to setuid as a normal user $>");
}
my $code = sub {
if ( open my $rr_fh, '<', $file ) {
local ( $/, $! );
$data = readline($rr_fh);
if ($!) {
$logger->warn("Failed to read '$file' for reading: $!");
}
close $rr_fh or $logger->warn("Failed to close '$file': $!");
}
else {
$logger->warn("Could not open file '$file' for reading: $!");
}
1;
};
my $change_effectives = ( $< == 0 && $uid != $> ) ? 1 : 0;
if ($change_effectives) {
Cpanel::AccessIds::ReducedPrivileges::call_as_user( $code, $uid, $gid )
|| $logger->warn("Cpanel::AccessIds::ReducedPrivileges::call_as_user did not return true");
}
else {
$code->();
}
return $data;
}
1;
} # --- END Cpanel/AccessIds.pm
{ # --- BEGIN Cpanel/DataStore.pm
package Cpanel::DataStore;
use strict;
# use Cpanel::Logger ();
my $logger = Cpanel::Logger->new();
sub store_ref {
my ( $file, $outof_ref, $perm ) = @_;
require Cpanel::CPAN::YAML::Syck;
$YAML::Syck::ImplicitTyping = 0;
local $YAML::Syck::SingleQuote = 1;
local $YAML::Syck::SortKeys = 1;
if ( ref($file) ) {
my $yaml_string = YAML::Syck::Dump($outof_ref);
print( {$file} __grapheme_to_character($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) ) {
$logger->info("Could not touch \xE2\x80\x9C$file\xE2\x80\x9D: $!");
return;
}
if ( $perm->[0] ) {
if ( !chmod( oct( $perm->[0] ), $file ) ) {
$logger->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; # or use() ?
Cpanel::AccessIds::do_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} __grapheme_to_character($yaml_string);
close $yaml_out;
return 1;
}
else {
$logger->warn("Could not open file '$file' for writing: $!");
return;
}
}
sub fetch_ref {
my ( $file, $is_array ) = @_;
my $ref = $is_array ? [] : {};
if ( load_ref( $file, $ref ) ) {
return $ref;
}
else {
return $is_array ? [] : {};
}
}
sub load_ref {
my ( $file, $into_ref ) = @_;
return if ( !-e $file || -z _ );
require Cpanel::CPAN::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];
};
$logger->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];
};
$logger->warn("Error loading YAML data: $!") if ( !$struct );
close $yaml_in;
}
else {
$logger->warn("Could not open file '$file' for reading: $!");
return;
}
if ( !$struct ) {
$logger->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 ) {
$logger->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 {
$logger->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' ) {
$logger->warn('second arg needs to be a coderef');
return;
}
my $ref = $is_array ? [] : {};
if ( !-e $file ) {
$logger->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 ) ) {
$logger->warn("Modifications to file $file could not be saved");
return;
}
}
}
else {
$logger->warn("Could not load datastore $file");
return;
}
return 1;
}
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/Locale/Utils/3rdparty.pm
package Cpanel::Locale::Utils::3rdparty;
%Cpanel::Locale::Utils::3rdparty::cpanel_provided = (
'ar' => 1,
'cs' => 1,
'da' => 1,
'de' => 1,
'el' => 1,
'en' => 1,
'es' => 1,
'es_419' => 1,
'es_es' => 1,
'fi' => 1,
'fil' => 1,
'fr' => 1,
'he' => 1,
'hu' => 1,
'i_cpanel_snowmen' => 1,
'id' => 1,
'it' => 1,
'ja' => 1,
'ko' => 1,
'ms' => 1,
'nb' => 1,
'nl' => 1,
'pl' => 1,
'pt' => 1,
'pt_br' => 1,
'ro' => 1,
'ru' => 1,
'sv' => 1,
'th' => 1,
'tr' => 1,
'uk' => 1,
'vi' => 1,
'zh' => 1,
'zh_tw' => 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'
},
'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 {
my ($locale_obj) = @_;
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::writefile( "/var/cpanel/locale/3rdparty/conf/$locale_tag/$_3rdparty", $setting );
}
1;
} # --- END Cpanel/Locale/Utils/3rdparty.pm
{ # --- BEGIN Cpanel/ServerTasks.pm
package Cpanel::ServerTasks;
# use Cpanel::LoadModule ();
our $VERSION = '0.0.4';
my $logger;
my $queue_dir = '/var/cpanel/taskqueue';
my $qname = 'servers';
sub queue_task {
my $plugins = shift;
if ( ref $plugins ne 'ARRAY' ) {
die "Implementor Error: queue_task requires a list of plugins to load as the first argument";
}
if ( !@_ ) {
die "Implementor Error: queue_task requires a list of tasks to queue";
}
_init_task_queue_and_plugins($plugins);
$logger ||= 'Cpanel::LoggerAdapter'->new();
my $queue = 'cPanel::TaskQueue'->new( { name => $qname, cache_dir => $queue_dir, logger => $logger } );
foreach my $cmdstring (@_) {
$queue->queue_task($cmdstring);
}
'Cpanel::TaskQueue::Manager'->can('kick_queueprocd')->();
return 1;
}
sub schedule_task {
my $plugins = shift;
my $delay = shift;
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";
}
_init_task_queue_and_plugins($plugins);
_load_taskqueue_module('cPanel::TaskQueue::Scheduler') if !$INC{"cPanel/TaskQueue/Scheduler.pm"};
$logger ||= 'Cpanel::LoggerAdapter'->new();
my $sched = 'cPanel::TaskQueue::Scheduler'->new( { name => $qname, cache_dir => $queue_dir, logger => $logger } );
foreach my $cmdstring (@_) {
$sched->schedule_task( $cmdstring, { 'delay_seconds' => $delay } );
}
'Cpanel::TaskQueue::Manager'->can('kick_queueprocd')->();
return 1;
}
my ( $file_ext, $serializer_in_use );
sub _load_taskqueue_modules {
if ( !$serializer_in_use || !$INC{'cPanel/StateFile.pm'} || !$INC{'cPanel/TaskQueue.pm'} || !$INC{'Cpanel/TaskQueue/Manager.pm'} || !$INC{'Cpanel/LoggerAdapter.pm'} ) {
no warnings 'redefine';
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 ( !$serializer_in_use ) {
Cpanel::LoadModule::load_perl_module('Cpanel::TaskQueue::Serializer::Utils');
( $file_ext, $serializer_in_use ) = Cpanel::TaskQueue::Serializer::Utils::get_active_serializer_format_and_module_name();
}
Cpanel::LoadModule::load_perl_module('cPanel::StateFile') if !$INC{'cPanel/StateFile.pm'};
if ( !$INC{'cPanel/TaskQueue.pm'} ) {
my $scheduler = 'cPanel::TaskQueue::Scheduler';
my $was_using_scheduler = $INC{'cPanel/TaskQueue/Scheduler.pm'} ? 1 : 0;
_load_taskqueue_module('cPanel::TaskQueue');
if ( !$was_using_scheduler && $INC{'cPanel/TaskQueue/Scheduler.pm'} ) {
$scheduler->can('import')->( $scheduler, '-serializer' => $serializer_in_use );
}
}
Cpanel::LoadModule::load_perl_module('Cpanel::TaskQueue::Manager') if !$INC{'Cpanel/TaskQueue/Manager.pm'};
Cpanel::LoadModule::load_perl_module('Cpanel::LoggerAdapter') if !$INC{'Cpanel/LoggerAdapter.pm'};
}
return 1;
}
sub _load_taskqueue_module {
my ($mod) = @_;
return Cpanel::LoadModule::load_perl_module( $mod, -serializer => $serializer_in_use );
}
my %loaded_plugins;
sub _init_task_queue_and_plugins {
my $plugins = shift;
_load_taskqueue_modules();
local @INC = ( '/var/cpanel/perl', @INC );
Cpanel::LoadModule::load_perl_module('cPanel::TaskQueue::PluginManager');
foreach my $p (@$plugins) {
my $mod = $p =~ /::/ ? $p : 'Cpanel::TaskProcessors::' . $p;
next if $loaded_plugins{$p};
unless ( 'cPanel::TaskQueue::PluginManager'->can('load_plugin_by_name')->($mod) ) {
die "ERROR: Unable to load plugin: $p ($mod)\n";
}
$loaded_plugins{$p} = 1;
}
return 1;
}
1;
} # --- END Cpanel/ServerTasks.pm
{ # --- BEGIN Cpanel/Locale/Utils/Display.pm
package Cpanel::Locale::Utils::Display;
# use Cpanel::Locale::Utils::Paths ();
sub get_locale_list {
my ($lh) = @_;
return @{ $lh->{'_cached_get_locale_list'} ||= [ sort ( 'en', $lh->list_available_locales() ) ] };
}
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 ( $localized_name_for_tag, $native_name_for_tag, $direction_map ) = $lh->lang_names_hashref(@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 ( $tag =~ m{^i_} ) {
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/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 $locale = _get_best_locale_for_datetime_obj( $lh->language_tag() );
my $encoding = $lh->encoding();
return _get_formatted_datetime( $locale, $encoding, $format, $epoch, $timezone );
}
sub get_lookup_hash_of_multi_epoch_datetime {
my ( $lh, $epochs_ar, $format, $timezone ) = @_;
$format ||= 'date_format_long';
my %lookups;
my $locale = _get_best_locale_for_datetime_obj( $lh->language_tag() );
my $encoding = $lh->encoding();
foreach my $epoch ( @{$epochs_ar} ) {
next if exists $lookups{$epoch};
$lookups{$epoch} = _get_formatted_datetime( $locale, $encoding, $format, $epoch, $timezone );
}
return \%lookups;
}
sub _get_formatted_datetime {
my ( $locale, $encoding, $format, $epoch, $timezone ) = @_;
$timezone ||= 'UTC';
if ( $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 ) );
}
else {
die 'Invalid datetime format: ' . $format;
}
}
sub _get_best_locale_for_datetime_obj {
my ( $language_tag, $epoch ) = @_;
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 ( my $loc = 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/Locale/Utils/User.pm
package Cpanel::Locale::Utils::User;
use strict;
# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::PwCache ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::Server::Utils ();
our $DATASTORE_MODULE = 'Cpanel::DataStore';
our $LOCALE_MODIFY_MODULE = 'Cpanel::Locale::Utils::User::Modify';
our $LOCALE_LEGACY_MODULE = 'Cpanel::Locale::Utils::Legacy';
my $inited_cpdata_user;
my $userlocale = {};
my $logger;
sub _logger {
return ( $logger ||= Cpanel::Logger->new() );
}
sub init_cpdata_keys {
my $user = shift || $Cpanel::user || $ENV{'REMOTE_USER'} || ( $> == 0 ? 'root' : ( Cpanel::PwCache::getpwuid($>) )[0] );
my $user_uid = shift;
my $homedir = shift;
return if ( defined $inited_cpdata_user && $inited_cpdata_user eq $user );
if ( !$Cpanel::CPDATA{'LOCALE'} && $user ne 'root' ) {
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()");
}
Cpanel::LoadModule::load_perl_module($LOCALE_MODIFY_MODULE);
$LOCALE_MODIFY_MODULE->can('migrate_user_locale_from_file')->( $user, $user_uid, $homedir );
if ( $> == 0 || ( $> && $> == Cpanel::PwCache::getpwnam($user) ) ) {
$Cpanel::CPDATA{'LOCALE'} = get_user_locale($user);
}
}
$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::LoadCpUserFile::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/Locale.pm
package Cpanel::Locale;
use strict;
BEGIN {
$ENV{'IGNORE_WIN32_LOCALE'} = 1;
}
# use Cpanel::Parser::Vars ();
# 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::Utils ();
our $LTR = 1;
our $RTL = 2;
our %known_locales_character_orientation = (
ar => $RTL,
bn => $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,
pl => $LTR,
pt_br => $LTR,
pt => $LTR,
ro => $LTR,
ru => $LTR,
sv => $LTR,
th => $LTR,
tr => $LTR,
uk => $LTR,
vi => $LTR,
zh => $LTR,
zh_tw => $LTR,
);
our $DEFAULT_OUTPUT_CONTEXT;
@Cpanel::Locale::ISA = ('Cpanel::CPAN::Locale::Maketext::Utils');
my $logger;
sub _logger {
require Cpanel::Logger;
$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'} ) {
eval ' require Cpanel::Locale::Utils::User; ' if !exists $INC{'Cpanel/Locale/Utils/User.pm'};
eval ' Cpanel::Locale::Utils::User::init_cpdata_keys(); ';
}
if ( $ENV{'HTTP_COOKIE'} ) {
require Cpanel::Cookies;
}
if ( $INC{'Cpanel/Cookies.pm'} && !keys %Cpanel::Cookies ) {
%Cpanel::Cookies = %{ Cpanel::Cookies::get_cookie_hashref() };
}
%Cpanel::Grapheme = %{ Cpanel::Locale->get_grapheme_helper_hashref() };
}
sub makevar {
return shift->maketext( ref $_[0] ? @{ $_[0] } : @_ ); ## no extract maketext
}
*maketext = \&Cpanel::CPAN::Locale::Maketext::maketext; ## no extract maketext
my %singleton_stash = ();
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 = ();
}
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{$_} } @locales ) {
require Cpanel::Locale::Utils::Legacy;
goto \&Cpanel::Locale::Utils::Legacy::map_any_old_style_to_new_style;
}
return @locales;
}
sub _setup_for_real_get_handle {
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 );
Cpanel::Locale->make_alias( [qw(en en_us i_default)], 1 );
}
return @langtags;
}
sub _real_get_handle {
my ( $class, @arg_langtags ) = @_;
my @langtags = _setup_for_real_get_handle( $class, @arg_langtags );
my $args_sig = join( ',', @langtags ) || 'no_args';
return (
( exists $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();
if ( defined $DEFAULT_OUTPUT_CONTEXT ) {
my $setter_cr = $lh->can("set_context_$DEFAULT_OUTPUT_CONTEXT") or do {
my $PACKAGE = __PACKAGE__;
die "Invalid ${PACKAGE}::DEFAULT_OUTPUT_CONTEXT: “$DEFAULT_OUTPUT_CONTEXT”!";
};
$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->{'cpanel'}{'is_devbox'} = -e '/var/cpanel/dev_sandbox' ? 1 : 0;
$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, @args ) = @_;
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} );
};
}
return $lh;
}
sub output_cpanel_error {
my ( $lh, $position, @args ) = @_;
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 '' || $path !~ m/\.js$/;
my $query = $path;
$query =~ s{(?:[\.\-]min|_optimized)\.js$}{.js}; # first, remove get_js_variations() part
$query =~ s{\.js$}{-%s.js}; # second, add asset placeholder
if ( defined $rv && $rv !~ m/%s/ ) {
$rv =~ s{\.js$}{-%s.js};
}
my $asset_path = $lh->get_asset_file( $query, $rv );
return $asset_path if $asset_path && $asset_path =~ m/-[^.]*\.js$/; # 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 get_server_locale {
if (%main::CPCONF) {
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->{'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 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 );
Cpanel::Locale->make_alias( [qw(en en_us i_default)], 1 );
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;
Cpanel::Locale::Utils::get_readonly_tie( $lh->get_cdb_file_path(), \%{ 'Cpanel::Locale::' . $locale . '::Lexicon' } );
}
sub cpanel_compile_my_lexicon_if_needed {
my ( $lh, $strict ) = @_;
my $locale = $lh->get_language_tag();
$locale = 'en' if $locale eq 'en_us' || $locale eq 'i_default';
if ( Cpanel::Locale::Utils::cdb_mtime_is_old( $lh->get_cdb_file_path(), $locale ) ) {
if ( !$lh->cpanel_compile_lexicon($locale) ) {
if ($strict) {
return;
}
_logger->info( q{'[_1]' did not return true.}, 'cpanel_compile_lexicon()' );
}
}
return $lh;
}
sub cpanel_compile_lexicon {
my ( $lh, $locale ) = @_;
my $reinit = 0;
my $cur_locale = $lh->get_language_tag();
$cur_locale = 'en' if $cur_locale eq 'en_us' || $cur_locale eq 'i_default';
if ( !$locale ) {
$reinit++;
$locale = $cur_locale;
}
else {
$locale = 'en' if $locale eq 'en_us' || $locale eq 'i_default';
if ( $locale eq $cur_locale ) {
$reinit++;
}
}
die "Possible compile loop (i.e. fork bomb) prevented" if $lh->{'Cpanel::Locale'}{'compile_lexicon'}{$locale}++; # '++' on right == current value
if ( $> == 0 ) {
require Cpanel::ServerTasks;
_logger->info( $lh->maketext( qq{Rebuilding “[_1]” database as uid “[_2]”.}, $locale, $> ) );
Cpanel::ServerTasks::queue_task( ['LocaleTasks'], "build_locale_databases --locale=$locale --quiet" );
}
else {
_logger->info( $lh->maketext( qq{Rebuilding “[_1]” database as uid “[_2]”.}, $locale, $> ) );
$lh->cpanel_detach_lexicon() if $reinit;
require Cpanel::SafeRun::Errors;
Cpanel::SafeRun::Errors::saferunallerrors( '/usr/local/cpanel/bin/langwrap', 'UPDATEQUIET', $locale );
my $rc = $?;
$lh->cpanel_attach_lexicon() if $reinit;
return if $rc != 0;
}
return 1;
}
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;
}
my $_lh;
sub Locale_maketext {
$_lh ||= Cpanel::Locale->get_handle();
$_[0] =~ s{\\'}{'}g;
if ($Cpanel::Parser::Vars::embtag) {
require Cpanel::Encoder::Tiny;
print Cpanel::Encoder::Tiny::safe_html_encode_str( $_lh->makevar(@_) );
}
elsif ($Cpanel::Parser::Vars::javascript) {
my $str = $_lh->makevar(@_);
$str =~ s/"/\\"/g;
$str =~ s/'/\\'/g;
print $str;
}
else {
print $_lh->makevar(@_);
}
}
sub _api1_maketext { ## no extract maketext
$_lh ||= Cpanel::Locale->get_handle();
$_[0] =~ s{\\'}{'}g;
my $localized_str = $_lh->makevar(@_);
if ($Cpanel::Parser::Vars::embtag) {
require Cpanel::Encoder::Tiny;
$localized_str = Cpanel::Encoder::Tiny::safe_html_encode_str($localized_str);
}
elsif ($Cpanel::Parser::Vars::javascript) {
$localized_str =~ s/"/\\"/g;
$localized_str =~ s/'/\\'/g;
}
return {
status => 1,
statusmsg => $localized_str,
};
}
our $api1 = {
'maketext' => { ## no extract maketext
'function' => \&_api1_maketext, ## no extract maketext
'internal' => 1,
'legacy_function' => 2,
'modify' => 'inherit',
},
};
sub convert {
_logger->die("convert() has been disabled");
}
sub current_year {
return (localtime)[5] + 1900; # we override datetime() so we can't use the internal current_year()
}
sub datetime {
my ( $lh, $epoch, $format, $timezone ) = @_;
require Cpanel::Locale::Utils::DateTime;
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 ( $name =~ m/^i_/ ) {
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 {
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] ) );
}
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 $API = { 'get_locale_name' => {}, 'get_encoding' => {}, 'get_html_dir_attr' => {}, 'get_user_locale' => {}, 'get_user_locale_name' => {}, 'numf' => {}, };
sub api2 {
return $API->{ $_[0] };
}
my $global_lh;
sub lh {
$global_lh ||= Cpanel::Locale->get_handle();
return $global_lh;
}
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;
}
}
1;
} # --- END Cpanel/Locale.pm
{ # --- BEGIN Cpanel/Config/FlushConfig.pm
package Cpanel::Config::FlushConfig;
use strict;
# use Cpanel::FileUtils::Write ();
our $VERSION = '1.4';
my $DEFAULT_DELIMITER = '=';
my $logger;
sub flushConfig {
my ( $filename_or_fh, $conf, $delimiter, $header, $opts ) = @_;
if ( !$filename_or_fh ) {
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
$logger->warn('flushConfig requires valid filename or fh as first argument');
return;
}
elsif ( !$conf || ref $conf ne 'HASH' ) {
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
$logger->warn('flushConfig requires HASH reference as second argument');
return;
}
my $contents_sr = serialize(
$conf,
do_sort => $opts && $opts->{'sort'},
delimiter => $delimiter,
header => $header,
);
my $perms;
if ( defined $opts->{'perms'} ) {
$perms = $opts->{'perms'};
}
elsif ( -e $filename_or_fh ) {
$perms = ( stat(_) )[2] & 0777;
}
return Cpanel::FileUtils::Write::writefile(
$filename_or_fh,
$contents_sr,
$perms,
( ( $opts && exists $opts->{'no_overwrite'} ) ? $opts->{'no_overwrite'} : undef ),
);
}
sub serialize {
my ( $conf, %opts ) = @_;
my ( $do_sort, $delimiter, $header ) = @opts{qw(do_sort delimiter header)};
$delimiter ||= $DEFAULT_DELIMITER;
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/GreyList/Config.pm
package Cpanel::GreyList::Config;
use strict;
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::Config::LoadConfig::Tiny ();
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';
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() );
}
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;
Cpanel::Config::LoadConfig::Tiny::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};
}
}
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 = {
'initial_block_time_mins' => 10, # 10 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
};
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'};
}
Cpanel::Config::LoadConfig::Tiny::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;
}
1;
} # --- END Cpanel/GreyList/Config.pm
{ # --- BEGIN Cpanel/Services/Enabled.pm
package Cpanel::Services::Enabled;
use strict;
# use Cpanel::FileUtils::TouchFile ();
my %disable_files_exceptions = (
'dns' => '/etc/nameddisable',
'ftp' => [ '/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}],
);
my $services_status_from_cpanel_config = {
'mailman' => { key => 'skipmailman', meaning => 'disabled' },
'imap' => { key => 'mailserver' },
'pop' => { key => 'mailserver' },
};
sub is_enabled {
my $service = shift;
return -1 unless defined $service;
if ( $service eq 'cpgreylistd' ) {
eval q{require Cpanel::GreyList::Config; 1} or return -1;
return 'Cpanel::GreyList::Config'->can('is_enabled')->();
}
if ( $service eq 'cphulkd' ) {
eval q{require Cpanel::Config::Hulk; 1} or return -1;
return 'Cpanel::Config::Hulk'->can('is_enabled')->();
}
return 1 if ( $service eq 'dnsadmin' || $service eq 'cpsrvd' );
if ( my $cpconfig_exception = $services_status_from_cpanel_config->{$service} ) {
eval q{require Cpanel::Config::LoadCpConf; 1} or return -1;
return -1 unless my $loadcpconf = 'Cpanel::Config::LoadCpConf'->can('loadcpconf');
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 _check_for_disabled_file($service);
}
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;
}
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();
}
my $files = get_files_for_service($service);
return unless defined $files && defined $files->[0];
return Cpanel::FileUtils::TouchFile::touchfile( $files->[0] );
}
sub remove_disable_files {
my $service = shift;
return unless defined $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 get_files_for_service {
my $service = shift;
return unless defined $service;
return if $service !~ m/^imap|pop$/ && exists $services_status_from_cpanel_config->{$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} ];
}
1;
} # --- END Cpanel/Services/Enabled.pm
{ # --- BEGIN Cpanel/RPM.pm
package Cpanel::RPM;
use strict;
use Carp ();
# use Cpanel::FindBin ();
# use Cpanel::SafeRun::Errors ();
sub new {
my ( $class, $opts ) = @_;
$opts ||= {};
my $self = {%$opts};
bless $self, $class;
return $self;
}
sub bin {
my $self = shift or Carp::croak 'bin() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("bin() must be called as a method.");
$self->{'rpm_bin'} ||= Cpanel::FindBin::findbin('rpm');
return $self->{'rpm_bin'};
}
sub qa {
my $self = shift or Carp::croak 'qa() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("qa() must be called as a method.");
my @filter = @_;
my $answer = $self->cmd( '-qa', '--queryformat', '%{NAME} %{VERSION}-%{RELEASE}\n', @filter );
return {} if $answer->{status} != 0;
my $out = $answer->{output};
my %installed;
for my $line ( split( "\n", $out ) ) {
chomp $line;
my ( $rpm, $version ) = split( qr/\s+/, $line, 2 );
$installed{$rpm} = $version;
}
return \%installed;
}
sub qf {
my $self = shift or Carp::croak 'qf() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("qf() must be called as a method.");
my @filter = @_;
Carp::croak 'qf() requires at least one search filter'
if !@filter;
local $ENV{'LC_ALL'} = 'C';
my $answer = $self->cmd( '-qf', '--queryformat', '%{NAME} %{VERSION}-%{RELEASE}\n', @filter );
if ( $answer->{'status'} && $answer->{'output'} ) {
my @not_owned = ( $answer->{'output'} =~ m/^file (.+?) is not owned by any package$/gm );
Carp::croak 'The system could not find any RPM owner for the following file(s): ' . join( ', ', @not_owned )
if @not_owned;
}
Carp::croak 'The system could not find query for the specfied file(s): ' . join( ', ', @filter )
if $answer->{status} != 0;
my %rpmfiles = ( $answer->{'output'} =~ m/^(\S+?)\s+(.+?)$/gm );
return \%rpmfiles;
}
sub qR {
my $self = shift or Carp::croak 'qR() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("qR() must be called as a method.");
my @filter = @_;
Carp::croak 'qR() requires at least one search filter'
if !@filter;
local $ENV{'LC_ALL'} = 'C';
my $answer = $self->cmd( '-qR', '--queryformat', '%{NAME} %{VERSION}-%{RELEASE}\n', @filter );
if ( $answer->{'status'} && $answer->{'output'} ) {
my @not_installed = ( $answer->{'output'} =~ m/^package (.+?) is not installed$/gm );
Carp::croak 'The system could not find the following RPM(s): ' . join( ', ', @not_installed )
if @not_installed;
Carp::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 has_rpm {
my $self = shift or Carp::croak 'has_rpm() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("has_rpm() must be called as a method.");
my $search = shift;
Carp::croak 'has_rpm() requires a search filter'
if !$search;
my $q = $self->qa($search);
return $q && $q->{$search} ? 1 : 0;
}
sub cmd {
my $self = shift or Carp::croak 'cmd() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("cmd() must be called as a method.");
my @args = @_;
my $out = Cpanel::SafeRun::Errors::saferunallerrors( $self->bin(), @args );
return { output => $out, status => $? };
}
1;
} # --- END Cpanel/RPM.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/Maxmem.pm
package Cpanel::Maxmem;
use strict;
sub default {
return 512;
}
1;
} # --- END Cpanel/Maxmem.pm
{ # --- BEGIN Cpanel/Config/Sources.pm
package Cpanel::Config::Sources;
# use Cpanel::Config::LoadConfig ();
our $cpsources_conf_file = '/etc/cpsources.conf';
sub loadcpsources {
my $update_default = 'httpupdate.cpanel.net';
my %sources = (
'NEWS' => 'web.cpanel.net',
'RSYNC' => 'rsync.cpanel.net',
'HTTPUPDATE' => $update_default,
'MYIP' => 'https://myip.cpanel.net/v1.0/', # URL to determine a local IP's public IP (1to1 NAT)
);
if ( -e $cpsources_conf_file ) {
Cpanel::Config::LoadConfig::loadConfig( $cpsources_conf_file, \%sources );
}
$sources{'LAYER'} = $sources{'HTTPUPDATE'};
if ( $sources{'HTTPUPDATE'} eq 'layer2.cpanel.net' ) {
$sources{'LAYER'} = $update_default;
$sources{'HTTPUPDATE'} = $update_default;
}
foreach my $key ( keys %sources ) {
next if ( !$sources{$key} );
$sources{$key} =~ s/^\s+//;
$sources{$key} =~ s/\s+$//;
}
return wantarray ? %sources : \%sources;
}
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 = [];
my $SIG_VALIDATION_CPCONF_KEY = 'signature_validation';
my $WEAK_CHECKSUM_CPCONF_KEY = 'allow_weak_checksums';
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 {
my $allow_weak_checksums = _load_cpconf_setting($WEAK_CHECKSUM_CPCONF_KEY);
my @algos = ('sha512');
if ($allow_weak_checksums) {
push( @algos, 'md5' );
}
return @algos;
}
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/Config/CpConfGuard/Default.pm
package Cpanel::Config::CpConfGuard::Default;
use strict;
# use Cpanel::ConfigFiles::Apache 'apache_paths_facade'; # see POD for import specifics
INIT { Cpanel::ConfigFiles::Apache->import(qw{apache_paths_facade}); }
# use Cpanel::Config::Constants ();
# use Cpanel::ConfigFiles ();
sub default_statics {
return {
'RS' => 'x3',
'VFILTERDIR' => '/etc/vfilters',
'access_log' => '/usr/local/cpanel/logs/access_log',
'account_login_access' => 'owner_root',
'adminuser' => 'cpanel',
'allow_login_autocomplete' => '1',
'allow_server_info_status_from' => '',
'allowcpsslinstall' => '1',
'allowparkhostnamedomainsubdomains' => '0',
'allowparkonothers' => '0',
'allowwhmparkonothers' => '0',
'allowremotedomains' => '0',
'allowresellershostnamedomainsubdomains' => '0',
'allowunregistereddomains' => '0',
'allow_weak_checksums' => '0',
'alwaysredirecttossl' => '0',
'anon_data_optout' => '0',
'apache_port' => '0.0.0.0:80',
'apache_ssl_port' => '0.0.0.0:443',
'api_shell' => '0',
'autocreateaentries' => '1',
'autodiscover_host' => 'cpanelemaildiscovery.cpanel.net',
'autodiscover_mail_service' => 'imap',
'autodiscover_proxy_subdomains' => '0',
'awstatsbrowserupdate' => '0',
'awstatsreversedns' => '0',
'basename' => 'cpanel',
'bind_deferred_restart_time' => '0',
'blockcommondomains' => '1',
'bwcycle' => '2',
'cgiemaildisabled' => '0',
'cgihidepass' => '0',
'check_zone_owner' => '1',
'check_zone_syntax' => '1',
'chkservd_check_interval' => '300',
'chkservd_hang_allowed_intervals' => '2',
'chkservd_plaintext_notify' => '0',
'cluster_autodisable_threshold' => '10',
'cluster_failure_notifications' => '1',
'conserve_memory' => '0',
'cookieipvalidation' => 'strict',
'coredump' => '0',
'cpaddons_adminemail' => '',
'cpaddons_autoupdate' => '1',
'cpaddons_max_moderation_req_all_mod' => '99',
'cpaddons_max_moderation_req_per_mod' => '99',
'cpaddons_moderation_request' => '0',
'cpaddons_no_3rd_party' => '0',
'cpaddons_no_modified_cpanel' => '1',
'cpaddons_notify_owner' => '1',
'cpaddons_notify_root' => '1',
'cpaddons_notify_users' => 'Allow users to choose',
'cpanel_locale' => '',
'cpredirect' => 'Origin Domain Name',
'cpredirectssl' => 'SSL Certificate Name',
'cpsrvd-domainlookup' => '0',
'create_account_dkim' => '1',
'create_account_spf' => '0',
'cycle_hours' => '24',
'database_prefix' => '1',
'debughooks' => '0',
'default_archive-logs' => '1',
'default_login_theme' => 'cpanel',
'default_remove-old-archived-logs' => '1',
'defaultmailaction' => 'localuser',
'disable-php-as-reseller-security' => '0',
'disableipnscheck' => '0',
'disablequotacache' => '0',
'discardformmailbccsubject' => '1',
'disk_usage_include_mailman' => '1',
'disk_usage_include_sqldbs' => '1',
'dnsadmin_log' => '0',
'dnsadmin_verbose_sync' => '0',
'dnsadminapp' => undef,
'dnslookuponconnect' => '0',
'docroot' => '/usr/local/cpanel/base',
'domainowner_mail_pass' => '0',
'dormant_services' => join( ',', @Cpanel::Config::Constants::DORMANT_SERVICES_LIST ),
'dumplogs' => '1',
'email_account_quota_default_selected' => 'userdefined',
'email_account_quota_userdefined_default_value' => '1024',
'email_send_limits_count_mailman' => '0',
'email_send_limits_defer_cutoff' => '125',
'email_send_limits_min_defer_fail_to_trigger_protection' => 5,
'email_send_limits_max_defer_fail_percentage' => undef,
'emailarchive' => '0',
'emailpasswords' => '0',
'emailusers_diskusage_critical_contact_admin' => '1',
'emailusers_diskusage_critical_percent' => '90',
'emailusers_diskusage_full_contact_admin' => '1',
'emailusers_diskusage_full_percent' => '98',
'emailusers_diskusage_warn_contact_admin' => '0',
'emailusers_diskusage_warn_percent' => '80',
'emailusers_mailbox_critical_percent' => '90',
'emailusers_mailbox_full_percent' => '98',
'emailusers_mailbox_warn_percent' => '80',
'emailusersbandwidthexceed' => '0',
'emailusersbandwidthexceed70' => '0',
'emailusersbandwidthexceed75' => '0',
'emailusersbandwidthexceed80' => '1',
'emailusersbandwidthexceed85' => '0',
'emailusersbandwidthexceed90' => '0',
'emailusersbandwidthexceed95' => '0',
'emailusersbandwidthexceed97' => '0',
'emailusersbandwidthexceed98' => '0',
'emailusersbandwidthexceed99' => '0',
'enable_piped_logs' => '0',
'enablecompileroptimizations' => '0',
'engine' => 'cpanel',
'enginepl' => 'cpanel.pl',
'engineroot' => '/usr/local/cpanel',
'exim-retrytime' => '15',
'exim_retention_days' => '10',
'eximmailtrap' => '1',
'extracpus' => '0',
'file_upload_max_bytes' => undef,
'file_upload_must_leave_bytes' => '5',
'file_usage' => '0',
'ftppasslogs' => '0',
'ftpquotacheck_expire_time' => '30',
'ftpserver' => 'pure-ftpd',
'gzip_compression_level' => '6',
'gzip_pigz_block_size' => '4096',
'gzip_pigz_processes' => '1',
'htaccess_check_recurse' => '2',
'ignoredepreciated' => '0',
'ionice_bandwidth_processing' => '6',
'ionice_cpbackup' => '6',
'ionice_email_archive_maintenance' => '7',
'ionice_ftpquotacheck' => '6',
'ionice_log_processing' => '7',
'ionice_quotacheck' => '6',
'ionice_userbackup' => '7',
'ionice_userproc' => '6',
'ipv6_control' => '0',
'ipv6_listen' => '0',
'jailapache' => '0',
'jaildefaultshell' => '0',
'jailmountbinsuid' => '0',
'jailmountusrbinsuid' => '0',
'jailprocmode' => 'mount_proc_jailed_fallback_full',
'keepftplogs' => '0',
'keeplogs' => '0',
'keepstatslog' => '0',
'loadthreshold' => undef,
'local_nameserver_type' => 'bind',
'logchmod' => '0640',
'logout_redirect_url' => '',
'mailserver' => 'dovecot',
'maxcpsrvdconnections' => '200',
'maxemailsperhour' => undef,
'maxmem' => '512',
'minpwstrength' => '65',
'modsec_keep_hits' => '7',
'mycnf_auto_adjust_openfiles_limit' => '1',
'mycnf_auto_adjust_maxallowedpacket' => '1',
'mycnf_auto_adjust_innodb_buffer_pool_size' => '0',
'myname' => 'cpaneld',
'mysql-host' => 'localhost',
'mysql-version' => '5.6',
'mysqldebug' => '0',
'nativessl' => '1',
'maintenance_rpm_version_check' => '1',
'maintenance_rpm_version_digest_check' => '1',
'nobodyspam' => '0',
'nocpbackuplogs' => '0',
'nosendlangupdates' => '0',
'numacctlist' => '30',
'overwritecustomproxysubdomains' => '0',
'overwritecustomsrvrecords' => '0',
'permit_appconfig_entries_without_acls' => '0',
'permit_appconfig_entries_without_features' => '0',
'permit_unregistered_apps_as_reseller' => '0',
'permit_unregistered_apps_as_root' => '0',
'php_max_execution_time' => '90',
'php_post_max_size' => '55',
'php_upload_max_filesize' => '50',
'phploader' => '',
'phpopenbasedirhome' => '0',
'popbeforesmtpsenders' => '0',
'popbeforesmtp' => '0',
'port' => '2082',
'postgresdebug' => '0',
'product' => 'cPanel',
'proxysubdomains' => '1',
'proxysubdomainsfornewaccounts' => '1',
'proxysubdomainsoverride' => '1',
'publichtmlsubsonly' => '0',
'referrerblanksafety' => '0',
'referrersafety' => '0',
'remotewhmtimeout' => '35',
'repquota_timeout' => '60',
'requiressl' => '1',
'resetpass' => '0',
'resetpass_sub' => '0',
'root' => '/usr/local/cpanel',
'rotatelogs_size_threshhold_in_megabytes' => '300',
'roundcube_db' => 'mysql',
'send_error_reports' => '1',
'send_server_configuration' => '1',
'send_server_usage' => '1',
'server_locale' => 'en',
'showwhmbwusageinmegs' => '0',
'signature_validation' => 'Release Keyring Only',
'skip_chkservd_recovery_notify' => '0',
'skipanalog' => '0',
'skiprecentauthedmailiptracker' => '0',
'skipapacheclientsoptimizer' => '0',
'skipawstats' => '0',
'skipboxcheck' => '1',
'skipboxtrapper' => '0',
'skipbwlimitcheck' => '0',
'skipchkservd' => '0',
'skipcpbandwd' => '0',
'skipdiskcheck' => '0',
'skipoomcheck' => '0',
'skipdiskusage' => '0',
'skipeximstats' => '0',
'skipformmail' => '1',
'skiphorde' => '0',
'skiphttpauth' => '1',
'skipjailmanager' => '0',
'skipmailauthoptimizer' => '0',
'skipmailman' => '0',
'skipmodseclog' => '0',
'skipnotifyacctbackupfailure' => '0',
'skipparentcheck' => '0',
'skiproundcube' => '0',
'skipspamassassin' => '0',
'skipspambox' => '1',
'skipsqmail' => '0',
'skiptailwatchd' => '0',
'skipwebalizer' => '0',
'skipwhoisns' => '0',
'smtpmailgidonly' => '1',
'stats_log' => '/usr/local/cpanel/logs/stats_log',
'statsloglevel' => '1',
'statthreshhold' => '256',
'stunnel' => '0',
'system_diskusage_critical_percent' => '92.55',
'system_diskusage_warn_percent' => '82.55',
'tcp_check_failure_threshold' => '3',
'transfers_timeout' => '1800',
'tweak_unset_vars' => '',
'update_log_analysis_retention_length' => '90',
'upcp_log_retention_days' => '45',
'use_apache_md5_for_htaccess' => '1',
'use_information_schema' => '1',
'useauthnameservers' => '0',
'usemailformailmanurl' => '0',
'usemysqloldpass' => '0',
'userdirprotect' => '0',
'verify_3rdparty_cpaddons' => '0',
'version' => '3.4',
};
}
sub default_dead_variables {
return [
qw /
SecurityPolicy::NoRootLogin SecurityPolicy::PasswdAge SecurityPolicy::PasswdAge::maxage SecurityPolicy::PasswdStrength
cppop cycle disablerootlogin allowperlupdates deny_quicksupport_password email_account_quota_display enable_cpansqlite
maildir force_binary_rrdtool php_register_globals popchecktimes popfloodcheck skipmelange send_update_log_for_analysis
interchangever ionice_optimizefs userstatsoverride skiplogaholic hordeadmins gzip_use_pigz skipantirelayd python cpsrvd-gzip
urchinsetpath
/
];
}
sub dynamic_variable_methods {
return {
'autodiscover_proxy_subdomains' => \&compute_autodiscover_proxy_subdomains,
'conserve_memory' => \&compute_conserve_memory,
'domainowner_mail_pass' => \&compute_domainowner_mail_pass,
'dormant_services' => \&compute_dormant_services,
'eximmailtrap' => \&compute_eximmailtrap,
'ftpserver' => \&compute_ftpserver,
'gzip_pigz_processes' => \&compute_system_processes,
'local_nameserver_type' => \&compute_local_nameserver_type,
'mailserver' => \&compute_mailserver,
'maxmem' => \&compute_maxmem,
'mysql-host' => \&compute_mysql_host,
'mysql-version' => \&compute_mysql_version,
'proxysubdomains' => \&compute_proxysubdomains,
'signature_validation' => \&compute_signature_validation,
};
}
sub critical_values {
return [
qw/
mysql-version
mysql-host
local_nameserver_type
mailserver
ftpserver
server_locale
autodiscover_proxy_subdomains
proxysubdomains
database_prefix
/
];
}
sub new {
my ( $class, %OPTS ) = @_;
my %data;
my @class_variables = qw/dynamic_variable_method defaults default_file_contents keys dead_variables/;
@data{@class_variables} = @OPTS{@class_variables};
$data{'dynamic_variable_method'} ||= dynamic_variable_methods();
$data{'default_file_contents'} ||= default_statics();
$data{'dead_variables'} ||= default_dead_variables();
$data{'is_root'} ||= ( $> == 0 ) ? 1 : 0;
my $self = bless \%data, $class;
$self->init;
return $self;
}
sub init {
my ($self) = @_;
_verify_called_as_object_method($self);
return if ( $self->{'defaults'} ); # Don't re-load as long as defaults is populated.
my $defaults = $self->{'default_file_contents'};
$self->{'keys'} = [ keys %$defaults ];
$self->{'defaults'} = {};
foreach my $key ( sort keys %$defaults ) {
next if $self->{'dynamic_variable_method'}->{$key}; # Not a static variable.
$self->{'defaults'}->{$key} = $defaults->{$key};
}
return 1;
}
sub get_all_defaults {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
foreach my $key ( keys %{ $self->{'dynamic_variable_method'} } ) {
$self->get_default_for($key);
}
return $self->{'defaults'};
}
sub is_dynamic {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
return $self->{'dynamic_variable_method'}->{$key} ? 1 : 0;
}
sub get_keys {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
return @{ $self->{keys} };
}
sub get_dynamic_keys_hash {
my ($self) = @_;
_verify_called_as_object_method($self);
my %keys_hash = map { ( $_ => 1 ) } keys %{ $self->{'dynamic_variable_method'} };
return \%keys_hash;
}
sub get_static_default_for {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
return $self->{'default_file_contents'}->{$key};
}
sub get_default_for {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
my $defaults = $self->{'defaults'};
return $defaults->{$key} if exists $defaults->{$key};
return $self->get_dynamic_key($key);
}
sub dead_variables {
my ($self) = @_;
_verify_called_as_object_method($self);
return $self->{'dead_variables'} || [];
}
sub get_dynamic_key {
my ( $self, $key ) = @_;
_verify_called_as_object_method($self);
my $code = $self->{'dynamic_variable_method'}->{$key};
return unless ( $code && ref $code eq 'CODE' );
return $self->{'defaults'}->{$key} = $code->($self);
}
sub compute_autodiscover_proxy_subdomains {
my $self = shift;
_verify_called_as_object_method($self);
return 0 unless $self->{'is_root'}; # Cannot figure this out reliably when not root.
require Cpanel::FileUtils;
return 0 unless -e apache_paths_facade->file_conf();
return Cpanel::FileUtils::has_txt_in_file( apache_paths_facade->file_conf(), '^\s*ServerAlias.*autodiscover\.\*' ) ? 1 : 0;
}
sub compute_conserve_memory {
return _check_file('/var/cpanel/conserve_memory');
}
sub compute_domainowner_mail_pass {
return _check_file('/var/cpanel/allow_domainowner_mail_pass');
}
sub compute_dormant_services {
my $self = shift;
_verify_called_as_object_method($self);
return '' unless $self->{'is_root'}; # Cannot figure this out reliably when not root.
return '' unless -d $Cpanel::ConfigFiles::DORMANT_SERVICES_DIR;
return join( ',', map { -f $Cpanel::ConfigFiles::DORMANT_SERVICES_DIR . "/$_/enabled" ? $_ : () } @Cpanel::Config::Constants::DORMANT_SERVICES_LIST );
}
sub compute_eximmailtrap {
return _check_file('/etc/eximmailtrap');
}
sub compute_ftpserver {
my $self = shift;
_verify_called_as_object_method($self);
return 'disabled' unless $self->{'is_root'}; # Cannot figure this out reliably when not root.
require Cpanel::Services::Enabled;
return 'disabled' unless Cpanel::Services::Enabled::is_enabled('ftp');
require Cpanel::RPM;
my $rpm = Cpanel::RPM->new();
my $ftps = $rpm->qa('*ftp*');
if ($ftps) {
for my $is_cprpm ( 1, 0 ) {
foreach my $search (qw/pure-ftpd proftpd/) {
return $search
if $ftps->{$search}
&& ( !$is_cprpm || $ftps->{$search} =~ m/\.cp\d+$/ );
}
}
}
return 'disabled';
}
sub compute_system_processes {
my $self = shift;
_verify_called_as_object_method($self);
return 1 unless $self->{'is_root'}; # Cannot figure this out reliably when not root.
require Cpanel::Cpu;
return Cpanel::Cpu::get_physical_cpu_count();
}
sub compute_local_nameserver_type {
my $self = shift;
_verify_called_as_object_method($self);
require Cpanel::Services::Enabled;
return 'disabled' unless Cpanel::Services::Enabled::is_enabled('dns');
unless ( $self->{'is_root'} ) {
return $self->{'default_file_contents'}->{'local_nameserver_type'};
}
require Cpanel::RPM;
my $rpm = Cpanel::RPM->new();
my $map = { 'cpanel-mydns' => 'mydns' };
for my $ns ( 'nsd', 'cpanel-mydns', 'mydns' ) {
my $q = $rpm->qa($ns);
return $map->{$ns} || $ns if $q && $q->{$ns};
}
return $self->{'default_file_contents'}->{'local_nameserver_type'};
}
sub compute_mailserver {
my $self = shift;
_verify_called_as_object_method($self);
require Cpanel::Services::Enabled;
return 'disabled' unless Cpanel::Services::Enabled::is_enabled('mail');
unless ( $self->{'is_root'} ) {
return $self->{'default_file_contents'}->{'mailserver'};
}
require Cpanel::RPM;
my $rpm = Cpanel::RPM->new();
for my $is_cprpm ( 1, 0 ) {
my $q = $rpm->qa('dovecot');
return 'dovecot' if $q && $q->{'dovecot'} && ( !$is_cprpm || $q->{'dovecot'} =~ m/\.cp\d+$/ );
}
return $self->{'default_file_contents'}->{'mailserver'};
}
sub compute_maxmem {
require Cpanel::Maxmem;
return Cpanel::Maxmem::default();
}
sub compute_mysql_host {
my $self = shift;
_verify_called_as_object_method($self);
return $self->{'default_file_contents'}->{'mysql-host'} unless $self->{'is_root'};
require Cpanel::MysqlUtils::MyCnf::Basic;
return Cpanel::MysqlUtils::MyCnf::Basic::getmydbhost('root') || $self->{'default_file_contents'}->{'mysql-host'};
}
sub compute_mysql_version {
my $self = shift;
_verify_called_as_object_method($self);
return $self->{'default_file_contents'}->{'mysql-version'} unless $self->{'is_root'};
eval q/require Cpanel::MysqlUtils::Version; 1/ or return;
local $@;
my $version = eval { Cpanel::MysqlUtils::Version::mysqlversion() };
$version ||= Cpanel::MysqlUtils::Version::get_short_mysql_version_from_data_files();
$version ||= $Cpanel::MysqlUtils::Version::DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED;
return $version;
}
sub compute_proxysubdomains {
require Cpanel::SafeRun::Simple;
return 0 unless -r apache_paths_facade->file_conf();
return 1 if Cpanel::SafeRun::Simple::saferun( 'grep', '-l', '^# CPANEL/.*PROXY SUBDOMAINS', apache_paths_facade->file_conf() ) && $? == 0;
return 0;
}
sub compute_signature_validation {
my $self = shift;
_verify_called_as_object_method($self);
require Cpanel::Crypt::GPG::Settings;
return Cpanel::Crypt::GPG::Settings::validation_setting_for_configured_mirror(),;
}
sub _check_file {
my $f = shift or return 0;
return -e $f ? 1 : 0;
}
sub _verify_called_as_object_method {
my $call = shift;
ref($call) eq __PACKAGE__ or die '' . ( caller(0) )[3] . " was not called as an object method line " . ( caller(0) )[2] . "\n";
return;
}
1;
} # --- END Cpanel/Config/CpConfGuard/Default.pm
{ # --- BEGIN Cpanel/Config/CpConfGuard.pm
package Cpanel::Config::CpConfGuard;
use strict;
# use Cpanel::JSON::FailOK ();
# use Cpanel::FileUtils::Write::JSON::Lazy ();
# use Cpanel::ConfigFiles ();
# use Cpanel::Carp ();
# use Cpanel::Debug ();
# use Cpanel::Destruct ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::CpConfGuard::Default ();
# use Cpanel::LoadModule ();
our $IN_LOAD = 0;
our $SENDING_MISSING_FILE_NOTICE = 0;
my $FILESYS_PERMS = 0644;
my $is_daemon;
my $loaded_json;
BEGIN {
$is_daemon = 0; # initialize the value in the begin block
$is_daemon = 1 if ( $0 =~ m/updatenow|cpsrvd|cpdavd|queueprocd|tailwatchd|cpanellogd/ or $0 =~ m/\.static$/ );
}
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 && !$loaded_json;
$loaded_json = 1;
my $self = bless {
%opts, # to be improved
'path' => $Cpanel::ConfigFiles::cpanel_config_file,
'pid' => $$,
'modified' => 0,
'is_root' => ( $> == 0 ) ? 1 : 0,
'changes' => {},
}, $class;
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 or $opts{'no_validate'} or !$self->{'is_root'};
$self->find_missing_keys();
$self->validate_keys();
$self->notify_and_save_if_changed();
return $self;
}
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'} && $config->{'tweak_unset_vars'} =~ /$k/ ) {
my %unset = map { ( $_ => 1 ) } split( /\s*,\s*/, $config->{'tweak_unset_vars'} );
delete( $unset{$k} );
$config->{'tweak_unset_vars'} = join( ',', sort keys %unset );
}
return 1;
}
sub config_copy {
my ($self) = @_;
_verify_called_as_object_method($self);
my $config = $self->{'data'} || $self->{'cache'} || {};
my %config_copy = %$config;
return \%config_copy;
}
sub find_missing_keys {
my ($self) = @_;
_verify_called_as_object_method($self);
my $default = Cpanel::Config::CpConfGuard::Default->new();
if ( $self->{'is_missing'} ) {
if ( $self->{'cache'} && ref( $self->{'cache'} ) eq 'HASH' && scalar keys %{ $self->{'cache'} } ) {
$self->{'data'} = {};
%{ $self->{'data'} } = %{ $self->{'cache'} };
my $config = $self->{'data'};
foreach my $key ( $default->get_keys() ) {
next if exists $config->{$key};
$self->{'data'}->{$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;
next;
}
my $changes_type = $default->is_dynamic($key) ? 'from_dynamic' : 'from_default';
$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->{'is_root'};
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:');
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,
]
);
}
sub save {
my ( $self, %opts ) = @_;
_verify_called_as_object_method($self);
return unless ( $self->{'is_root'} );
return if ( $] > 5.007 && $] < 5.014 );
return 1 if $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 ref( $self->{'data'} ) ne '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,
},
);
%{$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 _cache_is_valid() && $self->{'cache_is_valid'}; # Don't re-write the file if it looks correct.
$MEM_CACHE_CPANEL_CONFIG_MTIME = ( stat($Cpanel::ConfigFiles::cpanel_config_file) )[9] || 0;
return unless $self->{'is_root'}; # never update the cache when not root
local $@;
my $ok = eval { Cpanel::FileUtils::Write::JSON::Lazy::write_file( $Cpanel::ConfigFiles::cpanel_config_cache_file, $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 release_lock {
my ($self) = @_;
_verify_called_as_object_method($self);
return unless $self->{'is_root'} && defined $self->{'pid'} && $self->{'pid'} eq $$ && $self->{'lock'};
Cpanel::LoadModule::load_perl_module('Cpanel::SafeFile');
'Cpanel::SafeFile'->can('safeclose')->( $self->{'fh'}, $self->{'lock'}, sub { return $self->_update_cache() } );
$self->{'fh'} = $self->{'lock'} = undef;
$self->{'is_locked'} = 0;
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 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 ( -r $Cpanel::ConfigFiles::cpanel_config_cache_file ) {
$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) {
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->{'is_root'} && $self->{'is_missing'} ); # We can't do anything if the file is missing and we're not root. ABORT!
if ( $self->{'is_root'} && $self->{'is_missing'} ) {
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->{'is_root'} && !$self->{'cache_is_valid'} );
my ( $ref, $fh, $conflock ) = Cpanel::Config::LoadConfig::loadConfig(
$Cpanel::ConfigFiles::cpanel_config_file,
$config,
(undef) x 4, #if we must pass flags, then at least name them...
{ 'nocache' => 1, 'keep_locked_open' => 1, 'rw' => $self->{'rw'}, 'allow_undef_values' => 1 }
);
$self->{'fh'} = $fh;
$self->{'lock'} = $conflock;
$self->{'data'} = $config;
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 {
ref( $_[0] ) eq __PACKAGE__ or die '' . ( caller(0) )[3] . " was not called as an object method\n";
}
sub DESTROY {
my ($self) = @_;
return if Cpanel::Destruct::in_dangerous_global_destruction();
return 1 if ( $> or $memory_only ); # Special modes we don't or won't write to cpanel.config files.
return 2 if ( !$self or !keys %$self ); # Nothing to cleanup if we're just a blessed empty hash.
$self->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 Cpanel::Config::CpConfGuard ();
sub loadcpconf {
my $cpconf = Cpanel::Config::CpConfGuard->new( 'loadcpconf' => 1 )->config_copy;
return wantarray ? %$cpconf : $cpconf;
}
sub loadcpconf_not_copy {
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/DB/Prefix.pm
package Cpanel::DB::Prefix;
use strict;
# use Cpanel::MysqlUtils::Version ();
# use Cpanel::Mysql::Privs ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::DB::Utils ();
# use Cpanel::LoadModule ();
our $PRE_MARIADB_TEN_PREFIX_LENGTH = 8;
our $POST_MARIADB_TEN_PREFIX_LENGTH = 16;
our $MARIADB_TEN_MIN_VERSION = '10.0';
our $PREFIX_LENGTH;
sub get_prefix_length {
return $PREFIX_LENGTH if defined $PREFIX_LENGTH;
my $current_mysqlver = Cpanel::Mysql::Privs::_get_mysql_version();
return ( $PREFIX_LENGTH = Cpanel::MysqlUtils::Version::is_at_least( $current_mysqlver, $MARIADB_TEN_MIN_VERSION ) ? $POST_MARIADB_TEN_PREFIX_LENGTH : $PRE_MARIADB_TEN_PREFIX_LENGTH );
}
our $use_prefix; # our for testing purposes
sub use_prefix {
return $use_prefix if defined $use_prefix;
my $cpanel_conf = Cpanel::Config::LoadCpConf::loadcpconf();
return $use_prefix = $cpanel_conf->{'database_prefix'};
}
sub username_to_prefix {
my ($username) = @_;
return substr(
Cpanel::DB::Utils::username_to_dbowner($username),
0,
get_prefix_length(),
);
}
sub prefix_to_username {
my ($prefix) = @_;
my $userowners_hr = _load_user_to_owner_hashref();
for my $user ( keys %$userowners_hr ) {
if ( username_to_prefix($user) eq $prefix ) {
return $user;
}
}
return undef;
}
sub _load_user_to_owner_hashref {
Cpanel::LoadModule::load_perl_module('Cpanel::Config::LoadUserOwners');
return Cpanel::Config::LoadUserOwners::loadtrueuserowners( undef, 1, 1 );
}
sub add_prefix {
my ( $cpuser, $name ) = @_;
return username_to_prefix($cpuser) . "_$name";
}
sub add_prefix_if_name_needs {
my ( $cpuser, $name ) = @_;
my $prefix = username_to_prefix($cpuser);
return $name if $name =~ m<\A\Q$prefix\E_.+>;
return "$prefix\_$name";
}
1;
} # --- END Cpanel/DB/Prefix.pm
{ # --- BEGIN Cpanel/Validate/Username/Mode.pm
package Cpanel::Validate::Username::Mode;
use strict;
# use Whostmgr::Transfers::State ();
sub allows_leading_digits {
return -e '/etc/allowstupidstuff';
}
sub in_transfer_mode {
return Whostmgr::Transfers::State::is_transfer();
}
sub additional_reserved_usernames {
return ();
}
1;
} # --- END Cpanel/Validate/Username/Mode.pm
{ # --- BEGIN Cpanel/Validate/Username/Core.pm
package Cpanel::Validate::Username::Core;
use strict;
# use Cpanel::Validate::Username::Mode ();
our $MAX_LENGTH = 16; #Constrained by MySQL
our $MAX_SYSTEM_USERNAME_LENGTH = 31;
sub list_reserved_usernames {
return qw(
abrt
all
clamav
cpeasyapache
cpses
cphulkd
dbus
dirs
dovecot
eximstats
files
haldaemon
horde
mailman
modsec
munin
mydns
nobody
postgres
proftpd
root
roundcube
shadow
spamassassin
system
tcpdump
tmp
tomcat
toor
virtfs
virtual
whmxfer
_lock
), Cpanel::Validate::Username::Mode::additional_reserved_usernames();
}
sub list_reserved_username_patterns {
return qw(
^test
^passwd\.
assword$
^cpmydns
^cpanel
^mydns
^pg_toast
^pg_temp
^cpses
^cpbackup
);
}
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-Za-z0-9]{1,$MAX_LENGTH}\$";
}
sub _regexp_lead {
return Cpanel::Validate::Username::Mode::allows_leading_digits() ? '(?!\.)' : '(?![.\d])';
}
sub is_valid_system_username {
my ($user) = @_;
return if !defined $user;
my $regexp = get_system_username_regexp_str();
return $user =~ m{$regexp};
}
sub is_valid {
my ($user) = @_;
return if !defined $user;
my $regexp = get_regexp_str();
return $user =~ m{$regexp};
}
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-zA-Z0-9._//cd;
}
else {
$name =~ tr/a-zA-Z0-9._//cd;
}
$name =~ s/^\.//;
$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();
foreach my $regex ( list_reserved_username_patterns() ) {
return 1 if $user =~ m{$regex};
}
return;
}
1;
} # --- END Cpanel/Validate/Username/Core.pm
{ # --- BEGIN Cpanel/Validate/Username.pm
package Cpanel::Validate::Username;
use strict;
# use Whostmgr::Transfers::State ();
# use Cpanel::DB::Prefix ();
# use Cpanel::Exception ();
# use Cpanel::IO ();
# use Cpanel::Validate::Username::Core ();
# use Cpanel::Validate::Username::Mode ();
our $VERSION = 1.4;
our ( $MAX_LENGTH, $MAX_SYSTEM_USERNAME_LENGTH );
*MAX_LENGTH = \$Cpanel::Validate::Username::Core::MAX_LENGTH;
*MAX_SYSTEM_USERNAME_LENGTH = \$Cpanel::Validate::Username::Core::MAX_SYSTEM_USERNAME_LENGTH;
my $logger;
*list_reserved_usernames = \&Cpanel::Validate::Username::Core::list_reserved_usernames;
*list_reserved_username_patterns = \&Cpanel::Validate::Username::Core::list_reserved_username_patterns;
*get_system_username_regexp_str = \&Cpanel::Validate::Username::Core::get_system_username_regexp_str;
*get_regexp_str = \&Cpanel::Validate::Username::Core::get_regexp_str;
sub get_strict_regexp_str {
my $for_transfer = Cpanel::Validate::Username::Mode::in_transfer_mode();
return make_strict_regexp_str($for_transfer);
}
sub make_strict_regexp_str {
my $for_transfer = $_[0]; #boolean representing but not necessarily in_transfer_mode()
my $special_chars = $for_transfer ? '-.A-Z' : q{};
$special_chars .= '\_' if $for_transfer || !Cpanel::DB::Prefix::use_prefix();
my $chars = "[${special_chars}a-z0-9]";
my $len = "{1,$MAX_LENGTH}";
return '^' . Cpanel::Validate::Username::Core::_regexp_lead() . $chars . $len . '$';
}
*is_valid_system_username = \&Cpanel::Validate::Username::Core::is_valid_system_username;
*is_valid = \&Cpanel::Validate::Username::Core::is_valid;
sub validate_or_die {
my ($specimen) = @_;
if ( !is_valid($specimen) ) {
die Cpanel::Exception::create( 'InvalidUsername', { value => $specimen } );
}
return 1;
}
sub user_exists_or_die {
my ($specimen) = @_;
if ( !user_exists($specimen) ) {
die Cpanel::Exception::create( 'UserNotFound', 'This system does not contain a user named “[_1]”.', [$specimen] );
}
return 1;
}
sub is_strictly_valid {
return if !defined $_[0];
my $regexp = get_strict_regexp_str();
return $_[0] =~ m{$regexp};
}
*normalize = \&Cpanel::Validate::Username::Core::normalize;
*scrub = \&Cpanel::Validate::Username::Core::scrub;
*reserved_username_check = \&Cpanel::Validate::Username::Core::reserved_username_check;
sub user_exists { _pw_exists( $_[0], '/etc/passwd' ) }
sub group_exists { _pw_exists( $_[0], '/etc/group' ) }
sub _pw_exists {
my ( $user, $file ) = @_;
if ( !$user || !length $file ) {
_log_warn('Missing or invalid argument');
return;
}
local $!;
my $user_match = qr/\n\Q$user\E:/s;
if ( open my $pw_fh, '<', $file ) {
while ( my $block = Cpanel::IO::read_bytes_to_end_of_line( $pw_fh, 65535 ) ) {
$block = "\n" . $block; # need a \n for our regex to match -- we use /s since is much faster than /m
if ( $block =~ $user_match ) {
close $pw_fh;
return 1;
}
}
if ($!) {
_log_warn("Assuming pw user “$user” exists. Failed to read “$file”: $!");
return 1;
}
close $pw_fh or _log_warn("Failed to close “$file”: $!");
}
else {
_log_warn("Assuming pw user “$user” exists. Failed to open “$file” for reading: $!");
return 1; # If we can't verify then say it exists
}
return;
}
sub _log_warn {
my ($msg) = @_;
require Cpanel::Logger;
$logger ||= Cpanel::Logger->new();
$logger->warn($msg);
return;
}
1;
} # --- END Cpanel/Validate/Username.pm
{ # --- BEGIN Cpanel/AcctUtils/Domain.pm
package Cpanel::AcctUtils::Domain;
use strict;
# use Cpanel::FileLookup ();
# use Cpanel::ConfigFiles ();
# use Cpanel::Config::LoadCpUserFile ();
sub getdomain {
my ($user) = @_;
if ( $Cpanel::FileLookup::REVERSE_FILELOOKUPCACHE{$Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE}{$user} ) {
return $Cpanel::FileLookup::REVERSE_FILELOOKUPCACHE{$Cpanel::ConfigFiles::TRUEUSERDOMAINS_FILE}{$user};
}
return unless Cpanel::Config::LoadCpUserFile::has_cpuser_file($user);
my $cpuser_ref = Cpanel::Config::LoadCpUserFile::loadcpuserfile($user);
return $cpuser_ref->{'DOMAIN'};
}
1;
} # --- END Cpanel/AcctUtils/Domain.pm
{ # --- BEGIN Cpanel/AcctUtils/GetHomeDir.pm
package Cpanel::AcctUtils::GetHomeDir;
use strict;
# use Cpanel::PwCache ();
*gethomedir = \&Cpanel::PwCache::gethomedir;
1;
} # --- END Cpanel/AcctUtils/GetHomeDir.pm
{ # --- BEGIN Cpanel/Validate/EmailRFC.pm
package Cpanel::Validate::EmailRFC;
use strict;
# use Cpanel::StringFunc::Case ();
# use Cpanel::StringFunc::Trim ();
# use Cpanel::WildcardDomain ();
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 is_localpart_valid($local) && is_domain_valid($domain);
}
sub is_valid_remote {
my ($name) = @_;
return unless defined $name;
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 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-zA-Z0-9!#\$%&'*+\-\/=?^_`{|}~]+
(?:
\.
[a-zA-Z0-9!#\$%&'*+\-\/=?^_`{|}~]+
)*
$
/x;
}
sub is_domain_valid {
my ($domain) = @_;
return unless defined $domain;
return 0 if Cpanel::WildcardDomain::is_wildcard_domain($domain);
return scalar $domain =~ m/
^
[0-9a-zA-Z]
(?:
[0-9a-zA-Z-]*
[0-9a-zA-Z]
)?
(?:
\.
[0-9a-zA-Z]
(?:
[0-9a-zA-Z-]*
[0-9a-zA-Z]
)?
)*
$
/x;
}
sub is_domain_valid_remote {
my ($domain) = @_;
return unless defined $domain;
return unless scalar $domain =~ m/
^
[0-9a-zA-Z]
(?:
[0-9a-zA-Z-]*
[0-9a-zA-Z]
)?
(?:
\.
[0-9a-zA-Z]
(?:
[0-9a-zA-Z-]*
[0-9a-zA-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 strict;
# use Cpanel::Logger ();
# use Cpanel::PwCache ();
# use Cpanel::AccessIds::ReducedPrivileges ();
# use Cpanel::AcctUtils::GetHomeDir ();
# use Cpanel::Validate::EmailRFC ();
sub getcontactemail {
my ( $user, $homedir, $read_uid, $read_gid ) = @_;
$user ||= Cpanel::PwCache::getusername();
if ( !$homedir ) {
$homedir = $Cpanel::homedir || Cpanel::AcctUtils::GetHomeDir::gethomedir($user);
return '' if !$homedir;
}
if ( !-e $homedir . '/.contactemail' || -l $homedir . '/.contactemail' ) {
return '';
}
if ( !defined $read_uid || !defined $read_gid ) {
( $read_uid, $read_gid ) = ( Cpanel::PwCache::getpwnam($user) )[ 2, 3 ];
}
my $email;
if ( $> != $read_uid ) {
Cpanel::AccessIds::ReducedPrivileges::call_as_user(
sub {
$email = _read_contactemail( $homedir, 1 );
},
$read_uid,
$read_gid
);
}
else {
$email = _read_contactemail( $homedir, 1 );
}
if ( wantarray() ) {
return split_multi_email_string($email);
}
else {
return join( ',', split_multi_email_string($email) );
}
}
sub split_multi_email_string {
my ($email_string) = @_;
my @addr;
return 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 if @addr;
return;
}
sub _read_contactemail {
my ( $homedir, $skip_stat ) = @_;
my $email = '';
if ( $skip_stat || -e $homedir . '/.contactemail' && !-l $homedir . '/.contactemail' ) {
if ( open( my $contact_fh, '<', $homedir . '/.cpanel/contactinfo' ) ) {
my @emails;
while ( readline($contact_fh) ) {
if (m/^['"]?([a-z_]*)email['"]?[ \t]*:[ \t]*['"]?(.*)['"]?/) {
my $type = $1;
my $email = $2;
$email =~ s{['"]$}{} if length $email;
if ( !length $type ) {
unshift @emails, $email; #primary email is always first
}
else {
push @emails, $email;
}
}
}
$email = join( ',', @emails );
}
if ( !length $email && open my $contact_fh, '<', $homedir . '/.contactemail' ) {
$email = readline $contact_fh;
close $contact_fh;
if ($email) {
chomp $email;
$email =~ s/[\n\s\r\t<>]//g;
}
}
elsif ( !length $email ) {
Cpanel::Logger::logger(
{
'message' => "Failed to read $homedir/.contactemail with EUID $>: $!",
'level' => 'warn',
'service' => __PACKAGE__,
'output' => 0,
'backtrace' => 0,
}
);
}
}
return $email;
}
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 = $path =~ s<\A/><>;
$path =~ s</\z><>;
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() );
}
die $_;
};
}
return 1;
}
1;
} # --- END Cpanel/Validate/FilesystemPath.pm
{ # --- BEGIN Cpanel/MultiUserDirStore.pm
package Cpanel::MultiUserDirStore;
use strict;
# use Cpanel::Exception ();
# use Cpanel::PwCache ();
# use Cpanel::SafeDir::MK ();
# 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::SafeDir::MK::safemkdir( $dir, 0755 ) || die Cpanel::Exception::create( 'IO::DirectoryCreateError', { path => $dir, error => $! } );
}
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::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::FileUtils::TouchFile ();
# 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 ( m/^[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_write_fh {
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;
}
sub _strip_underscores {
my ( $self, @data ) = @_;
tr<_><>d for @data;
return @data;
}
1;
} # --- END Cpanel/MultiUserDirStore/TimeIndexedData.pm
{ # --- BEGIN Cpanel/Auth/Digest/Realm.pm
package Cpanel::Auth::Digest::Realm;
sub get_realm {
return 'cPanel';
}
1;
} # --- END Cpanel/Auth/Digest/Realm.pm
{ # --- BEGIN Cpanel/Rollback.pm
package Cpanel::Rollback;
use strict;
use Try::Tiny;
# use Cpanel::Exception ();
sub new {
my ($class) = @_;
return bless [], $class;
}
sub add {
my ( $self, $cmd, $label ) = @_;
die 'Command must be coderef!' if !UNIVERSAL::isa( $cmd, 'CODE' );
return push @$self, { code => $cmd, label => $label };
}
sub _iterate_commands {
my ( $self, $catch_cr ) = @_;
while (@$self) {
my $cmd = pop @$self;
my ( $code, $label ) = @{$cmd}{qw(code label)};
try { $code->() }
catch {
$catch_cr->( $code, $label, $_ );
};
}
return;
}
sub rollback {
my ( $self, $base_exception ) = @_;
if ( !try { $base_exception->isa('Cpanel::Exception') } ) {
if ( length $base_exception && !ref $base_exception ) {
$base_exception = Cpanel::Exception->create_raw($base_exception);
}
else {
die "Need a Cpanel::Exception, not “$base_exception”!";
}
}
$self->_iterate_commands(
sub {
my ( $code, $label, $err ) = @_;
my $exception = Cpanel::Exception::create(
'RollbackError',
{
error => $err,
label => $label,
}
);
$base_exception->add_auxiliary_exception($exception);
}
);
return 1;
}
1;
} # --- END Cpanel/Rollback.pm
{ # --- BEGIN Cpanel/CommandQueue.pm
package Cpanel::CommandQueue;
use strict;
use Try::Tiny;
# use Cpanel::Rollback ();
sub new {
my ($class) = @_;
return bless { _queue => [] }, $class;
}
sub add {
my ( $self, $work_todo, $undo_todo, $undo_label ) = @_;
push @{ $self->{'_queue'} },
{
work => $work_todo,
undo => $undo_todo,
undo_label => $undo_label,
};
return;
}
sub run {
my ($self) = @_;
my $rollback = Cpanel::Rollback->new();
my $stmt;
try {
while ( $stmt = shift @{ $self->{'_queue'} } ) {
$self->_convert_cmd_to_coderef( $stmt->{'work'} )->();
if ( $stmt->{'undo'} ) {
$rollback->add(
$self->_convert_cmd_to_coderef( $stmt->{'undo'} ),
$stmt->{'undo_label'},
);
}
}
}
catch {
my $err = $_;
$rollback->rollback($err);
die $err;
};
return;
}
sub _convert_cmd_to_coderef {
my ( $self, $todo_cr ) = @_;
return $todo_cr;
}
1;
} # --- END Cpanel/CommandQueue.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/Autodie/More.pm
package Cpanel::Autodie::More;
use strict;
use warnings;
use Try::Tiny;
# use Cpanel::Autodie ();
# use Cpanel::Autodie::More::Lite ();
# use Cpanel::Autodie::Utils ();
# use Cpanel::CommandQueue ();
# use Cpanel::Exception ();
# use Cpanel::Umask ();
*exists = \&Cpanel::Autodie::More::Lite::exists;
sub unlink_if_exists {
my ( $path, @xtra ) = @_;
die "Must have 1 parameter!" if @xtra || !defined $path;
my $ret = 0;
try {
$ret = Cpanel::Autodie::unlink($path);
}
catch {
die $_ if !try { $_->isa('Cpanel::Exception::IO::UnlinkError') };
die $_ if !$_->error_name() || $_->error_name() ne 'ENOENT';
};
return $ret;
}
sub rename_nondir_politely {
my ( $old, $new ) = @_;
my $q = Cpanel::CommandQueue->new();
$q->add(
sub { Cpanel::Autodie::link( $old, $new ) },
sub { Cpanel::Autodie::unlink($new) },
'unlink new path',
);
$q->add(
sub { Cpanel::Autodie::unlink($old) },
);
$q->run();
return;
}
sub mkdir {
my (@args) = @_;
my $umask;
if ( @args > 1 ) {
$umask = Cpanel::Umask->new(0);
}
return Cpanel::Autodie::mkdir(@args);
}
sub mkdir_if_not_exists {
my (@args) = @_;
local ( $!, $^E );
my $umask = ( @args > 1 ) && Cpanel::Umask->new(0);
my $ret = Cpanel::Autodie::Utils::mkdir_list(@args) or do {
Cpanel::Autodie::Utils::die_for_mkdir(@args) if !$!{'EEXIST'};
};
return $ret ? 1 : 0;
}
sub rename_if_exists {
my (@args) = @_;
my $ret;
try {
$ret = Cpanel::Autodie::rename(@args);
}
catch {
local $@ = $_;
die if !try { $_->isa('Cpanel::Exception::IO::RenameError') };
die if $_->error_name() ne 'ENOENT';
};
return $ret ? 1 : 0;
}
our $_SYS_GUARD_FUNC;
sub sysread {
$_SYS_GUARD_FUNC = \&_sysread;
goto &_guard_against_EINTR;
}
sub syswrite {
$_SYS_GUARD_FUNC = \&_syswrite;
goto &_guard_against_EINTR;
}
*_sysread = \&Cpanel::Autodie::sysread;
*_syswrite = \&Cpanel::Autodie::syswrite;
sub _guard_against_EINTR { ##no critic qw(RequireArgUnpacking)
my $ret;
local $@;
DO_FUNC:
while (1) {
last DO_FUNC if eval {
$ret = $_SYS_GUARD_FUNC->(@_);
1;
};
die if !try { $@->error_name() eq 'EINTR' };
}
return $ret;
}
1;
} # --- END Cpanel/Autodie/More.pm
{ # --- BEGIN Cpanel/Config/TouchFileBase.pm
package Cpanel::Config::TouchFileBase;
use strict;
use Try::Tiny;
# use Cpanel::Autodie ();
# use Cpanel::Autodie::More ();
# use Cpanel::Exception ();
# use Cpanel::Fcntl ();
# use Cpanel::Umask ();
sub _TOUCH_FILE { die Cpanel::Exception::create('AbstractClass') }
sub _MODE { return 0600 }
sub is_on {
my ( $self, @args ) = @_;
my $exists = Cpanel::Autodie::More::exists( $self->_TOUCH_FILE(@args) );
if ( $exists && !-f _ ) {
die Cpanel::Exception->create( '“[_1]” exists but is not a file!', [ $self->_TOUCH_FILE(@args) ] );
}
return $exists;
}
sub set_on {
my ( $self, @args ) = @_;
my $path = $self->_TOUCH_FILE(@args);
my $mode = $self->_MODE(@args);
my $created;
try {
my $umask = Cpanel::Umask->new(0);
Cpanel::Autodie::sysopen(
my $fh,
$path,
Cpanel::Fcntl::or_flags(qw( O_WRONLY O_CREAT O_EXCL )),
$mode,
);
$created = 1;
}
catch {
if ( !try { $_->error_name() eq 'EEXIST' } ) {
local $@ = $_;
die;
}
Cpanel::Autodie::chmod( $mode, $path );
$created = 0;
};
return $created;
}
sub set_off {
my ( $self, @args ) = @_;
return Cpanel::Autodie::More::unlink_if_exists( $self->_TOUCH_FILE(@args) );
}
1;
} # --- END Cpanel/Config/TouchFileBase.pm
{ # --- BEGIN Cpanel/Email/MTAAuthIsExternal.pm
package Cpanel::Email::MTAAuthIsExternal;
use strict;
# use Cpanel::Config::TouchFileBase();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Config::TouchFileBase); }
sub _TOUCH_FILE {
return '/var/cpanel/mail_has_external_auth';
}
sub _MODE { return 0644 }
1;
} # --- END Cpanel/Email/MTAAuthIsExternal.pm
{ # --- BEGIN Cpanel/PasswdStrength/Check.pm
package Cpanel::PasswdStrength::Check;
use strict;
# use Cpanel::Fcntl ();
# use Cpanel::StringFunc::Case ();
# use Cpanel::Config::LoadCpConf ();
my @bad_passwords;
sub MAX_STRENGTH { return 100 }
my %app_mapping = (
'pop' => 'virtual',
'ftp' => 'virtual',
'webdisk' => 'virtual',
);
sub valid_strength {
return if $_[0] =~ m{\D};
if ( !$_[0] ) {
return 0;
}
elsif ( $_[0] > 0 && $_[0] <= MAX_STRENGTH() ) {
return $_[0];
}
return;
}
sub get_required_strength {
my $app = shift;
return 0 if !$app;
$app = $app_mapping{$app} ? $app_mapping{$app} : $app;
my $required_strength;
if ( ( scalar keys %Cpanel::CONF ) ) {
$required_strength =
exists $Cpanel::CONF{ 'minpwstrength_' . $app }
? int $Cpanel::CONF{ 'minpwstrength_' . $app }
: ( exists $Cpanel::CONF{'minpwstrength'} ? int $Cpanel::CONF{'minpwstrength'} : 0 );
}
else {
my $cpconf_ref = Cpanel::Config::LoadCpConf::loadcpconf();
$required_strength =
exists $cpconf_ref->{ 'minpwstrength_' . $app }
? int $cpconf_ref->{ 'minpwstrength_' . $app }
: ( exists $cpconf_ref->{'minpwstrength'} ? int $cpconf_ref->{'minpwstrength'} : 0 );
}
return $required_strength;
}
sub verify_or_die {
my %OPTS = @_;
die "Invalid call!" if !$OPTS{'app'} || !defined $OPTS{'pw'};
if ( !check_password_strength(%OPTS) ) {
eval 'require Cpanel::Exception;' or die "Failed to load Cpanel::Exception: $@";
die 'Cpanel::Exception'->can('create')->( 'PasswordIsTooWeak', { application => $OPTS{'app'} } );
}
return 1;
}
sub check_password_strength {
my %OPTS = @_;
return ( int( get_required_strength( $OPTS{'app'} ) ) > int( get_password_strength( $OPTS{'pw'} ) ) ? 0 : 1 );
}
sub get_password_strength {
my ($password) = @_;
return 0 if !$password;
my $n_chars = length $password;
return 1 if $n_chars == 1;
my $first_char = substr( $password, 0, 1 );
my $repeat_count = 0;
$repeat_count++ while $password =~ /\Q$first_char\E/g;
return 1 if $repeat_count == $n_chars;
my $bad_passwords = get_bad_passwords_ref();
if ( $n_chars > 3 ) {
my $lc_password = Cpanel::StringFunc::Case::ToLower($password);
if ( grep { $lc_password eq $_ } @{$bad_passwords} ) {
return 1;
}
}
my $n_uppercase = 0;
my $n_lowercase = 0;
my $n_numbers = 0;
my $n_symbols = 0;
my $n_middle_number_symbol = 0;
my $n_variety_bonus = 0;
my $n_letters_only = 0;
my $n_numbers_only = 0;
my $n_repeat_chars = 0;
my $n_consec_uppercase = 0;
my $n_consec_lowercase = 0;
my $n_consec_numbers = 0;
my $n_worst_list = 0;
my @password_characters = split( //, $password );
my $counter = 0;
my $last_char;
my %repeats;
foreach my $character (@password_characters) {
if ( $character =~ m/[A-Z]/ ) {
$n_uppercase++;
if ($last_char) {
if ( $last_char =~ m/[A-Z]/ ) { $n_consec_uppercase++; }
}
}
if ( $character =~ m/[a-z]/ ) {
$n_lowercase++;
if ($last_char) {
if ( $last_char =~ m/[a-z]/ ) { $n_consec_lowercase++; }
}
}
if ( $character =~ m/\d/ ) {
$n_numbers++;
if ($last_char) {
if ( $last_char =~ m/\d/ ) { $n_consec_numbers++; }
}
}
if ( $character =~ m/\W/ ) {
$n_symbols++;
}
if ( $counter && $counter < ( $n_chars - 1 ) ) {
if ( $character =~ m/\d/ || $character =~ m/\W/ ) {
$n_middle_number_symbol++;
}
}
if ( !exists $repeats{$character} ) {
$repeats{$character} = 1;
}
else {
$n_repeat_chars++;
}
$last_char = $character;
$counter++;
}
if ( $n_numbers == 0 && $n_symbols == 0 ) { $n_letters_only = $n_lowercase + $n_uppercase; }
if ( $n_lowercase == 0 && $n_uppercase == 0 && $n_symbols == 0 ) { $n_numbers_only = $n_numbers; }
my $variety = 0;
if ( $n_uppercase != 0 ) { $variety++; }
if ( $n_lowercase != 0 ) { $variety++; }
if ( $n_numbers != 0 ) { $variety++; }
if ( $n_symbols != 0 ) { $variety++; }
if ( $n_chars >= 8 && $variety >= 3 ) {
$n_variety_bonus = $n_chars;
}
foreach my $bad_password ( @{$bad_passwords} ) {
if ( $password =~ m/\Q$bad_password\E/i ) {
$n_worst_list++;
}
}
my $strength = 0;
$strength += $n_chars * 4;
$strength += ( $n_chars - $n_uppercase ) * 2;
$strength += ( $n_chars - $n_lowercase ) * 2;
$strength += $n_numbers * 4;
$strength += $n_symbols * 6;
$strength += $n_middle_number_symbol * 2;
$strength += $n_variety_bonus * 2;
$strength -= $n_letters_only;
$strength -= $n_numbers_only;
$strength -= $n_repeat_chars * ( $n_repeat_chars - 1 );
$strength -= $n_consec_uppercase * 2;
$strength -= $n_consec_lowercase * 2;
$strength -= $n_consec_numbers * 2;
$strength -= $n_worst_list * int( $strength / 5 );
if ( $strength < 0 ) { $strength = 0; }
elsif ( $strength > MAX_STRENGTH() ) { $strength = MAX_STRENGTH(); }
return $strength;
}
sub get_bad_passwords_ref {
return \@bad_passwords if @bad_passwords;
foreach my $list ( '/etc/bad_passwords_list', '/usr/local/cpanel/etc/bad_passwords_list' ) {
local $/;
if ( -r $list && sysopen( my $list_fh, $list, Cpanel::Fcntl::or_flags(qw( O_RDONLY O_NOFOLLOW )) ) ) {
push @bad_passwords, grep ( !m/^[ \t]*$/, split( m{\s}, readline($list_fh) ) );
close $list_fh;
}
}
return \@bad_passwords;
}
1;
} # --- END Cpanel/PasswdStrength/Check.pm
{ # --- BEGIN Cpanel/MD5/Lite.pm
package Cpanel::MD5::Lite;
sub md5_hex {
my ($data_to_hash) = @_;
my $hashed_data;
if ( exists $INC{'Digest/MD5.pm'} ) {
eval '$hashed_data = Digest::MD5::md5_hex($data_to_hash);';
no warnings 'redefine';
*md5_hex = \&Digest::MD5::md5_hex;
return $hashed_data if $hashed_data;
}
if ( exists $INC{'Cpanel/CPAN/Digest/Perl/MD5.pm'} ) { # nomunge
eval '$hashed_data = Cpanel::CPAN::Digest::Perl::MD5::md5_hex($data_to_hash);'; # nomunge
return $hashed_data if $hashed_data;
}
local @INC = ( '/usr/local/cpanel', '/usr/local/cpanel/scripts' );
eval 'local $SIG{__DIE__}; local $SIG{__WARN__}; require Cpanel::CPAN::Digest::Perl::MD5;';
if ( exists $INC{'Cpanel/CPAN/Digest/Perl/MD5.pm'} ) {
eval '$hashed_data = Cpanel::CPAN::Digest::Perl::MD5::md5_hex($data_to_hash);';
}
return $hashed_data if $hashed_data;
}
1;
} # --- END Cpanel/MD5/Lite.pm
{ # --- BEGIN Cpanel/PwFileCache.pm
package Cpanel::PwFileCache;
use strict;
use Fcntl (); #required
# use Cpanel::AccessIds::SetUids ();
# use Cpanel::Auth::Digest::Realm ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::PasswdStrength::Check ();
our $VERSION = 1.6;
our $DEBUG = 0;
sub load_pw_cache {
my $opref = shift;
my $passwd_cache_file = $opref->{'passwd_cache_file'};
die "Invalid cache file: “$passwd_cache_file”!" if $passwd_cache_file =~ tr</><>;
if ( !length $passwd_cache_file ) { die "save_pw_cache called without a file"; }
my $passwd_cache_dir = $opref->{'passwd_cache_dir'};
my $passwd_cache_file_mtime = $opref->{'passwd_cache_file_mtime'};
if ( !defined $passwd_cache_file_mtime ) {
$passwd_cache_file_mtime = ( stat( $passwd_cache_dir . '/' . $passwd_cache_file ) )[9];
}
my $quota_file_mtime = $opref->{'quota_file_mtime'} || 0;
my $passwd_file_mtime = $opref->{'passwd_file_mtime'} || 0;
my $now = $opref->{'now'} || time();
my %cache;
if ( $passwd_cache_file_mtime > $passwd_file_mtime
&& $passwd_cache_file_mtime > $quota_file_mtime
&& $passwd_cache_file_mtime <= $now ) {
syswrite( STDERR, "[load_pw_cache] HIT [dir=$passwd_cache_dir] [file=$passwd_cache_file] [passwd_cache_file_mtime=$passwd_cache_file_mtime] [quota_file_mtime=$quota_file_mtime] [passwd_file_mtime=$passwd_file_mtime]\n" ) if $DEBUG;
if ( open( my $pwcache_fh, '<', $passwd_cache_dir . '/' . $passwd_cache_file ) ) {
local $/;
%cache = map { ( split( /:/, $_, 2 ) )[ 0, 1 ] } split( /\n/, readline($pwcache_fh) );
close($pwcache_fh);
}
}
else {
syswrite( STDERR, "[load_pw_cache] MISS [dir=$passwd_cache_dir] [file=$passwd_cache_file] [passwd_cache_file_mtime=$passwd_cache_file_mtime] [quota_file_mtime=$quota_file_mtime] [passwd_file_mtime=$passwd_file_mtime]\n" ) if $DEBUG;
}
return \%cache;
}
sub save_pw_cache {
my $opref = shift;
my $passwd_cache_file = $opref->{'passwd_cache_file'};
$passwd_cache_file =~ s/\///g;
my $passwd_cache_dir = $opref->{'passwd_cache_dir'};
my $uid = $opref->{'uid'} || 0;
my $gid = $opref->{'gid'} || 0;
if ( !$passwd_cache_file ) { die "save_pw_cache called without a file"; }
require Cpanel::MD5::Lite;
syswrite( STDERR, "[save_pw_cache] [dir=$passwd_cache_dir] [file=$passwd_cache_file]\n" ) if $DEBUG;
my $needs_fork = 0;
if ( $uid != $> ) { $needs_fork = 1; }
my $pid;
if ($needs_fork) {
$pid = fork();
if ( !defined $pid ) {
return; #fork failed
}
if ($pid) {
waitpid( $pid, 0 );
die "setuid to [uid=$uid], [gid=$gid] failed" if ( ( $? >> 8 ) != 0 );
}
else {
local $SIG{'__DIE__'} = 'DEFAULT'; # if we are called from cpsrvd we will
Cpanel::AccessIds::SetUids::setuids( $uid, $gid );
}
}
if ( !$pid ) {
if ( !-e $passwd_cache_dir ) {
mkdir( $passwd_cache_dir, 0770 );
}
my $cache_fh;
if ($needs_fork) {
sysopen( $cache_fh, $passwd_cache_dir . '/' . $passwd_cache_file, &Fcntl::O_WRONLY | &Fcntl::O_TRUNC | &Fcntl::O_CREAT, 0640 );
}
else {
sysopen( $cache_fh, $passwd_cache_dir . '/' . $passwd_cache_file, &Fcntl::O_WRONLY | &Fcntl::O_TRUNC | &Fcntl::O_CREAT, 0600 );
}
if ($cache_fh) {
print {$cache_fh} 'passwd:' . $opref->{'keys'}->{'encrypted_pass'} . "\n" if $opref->{'keys'}->{'encrypted_pass'};
print {$cache_fh} 'quota:' . ( $opref->{'keys'}->{'quota'} || 0 ) . "\n";
print {$cache_fh} 'homedir:' . ( $opref->{'keys'}->{'homedir'} || '' ) . "\n";
if ( $opref->{'keys'}->{'digest-ha1'} || ( $opref->{'calculate-digest-ha1'} && $opref->{'keys'}->{'pass'} ) ) { # only save it if we have it
my $realm = Cpanel::Auth::Digest::Realm::get_realm();
print {$cache_fh} 'digest-ha1:' . ( $opref->{'keys'}->{'digest-ha1'} || Cpanel::MD5::Lite::md5_hex( $passwd_cache_file . ':' . ( $opref->{'keys'}->{'realm'} || $realm ) . ':' . $opref->{'keys'}->{'pass'} ) ) . "\n";
}
print {$cache_fh} 'strength:' . Cpanel::PasswdStrength::Check::get_password_strength( $opref->{'keys'}->{'pass'} ) . "\n" if $opref->{'keys'}->{'pass'};
print {$cache_fh} 'lastchanged:' . ( $opref->{'keys'}->{'lastchanged'} || -1 ) . "\n";
print {$cache_fh} 'perms:' . ( $opref->{'keys'}->{'perms'} ) . "\n" if $opref->{'keys'}->{'perms'};
close($cache_fh);
}
exit if $needs_fork;
}
}
sub clearcache {
my ($opref) = @_;
my $passwd_cache_file = $opref->{'passwd_cache_file'};
$passwd_cache_file =~ s/\///g;
my $fname = "$opref->{'passwd_cache_dir'}/$passwd_cache_file";
if ( -e $fname ) {
unlink($fname);
}
}
1;
} # --- END Cpanel/PwFileCache.pm
{ # --- BEGIN Cpanel/AcctUtils/Lookup/MailUser.pm
package Cpanel::AcctUtils::Lookup::MailUser;
use strict;
# use Cpanel::AccessIds::ReducedPrivileges ();
# use Cpanel::AcctUtils::DomainOwner ();
# use Cpanel::AcctUtils::Lookup ();
# use Cpanel::Auth::Digest::Realm ();
# use Cpanel::ConfigFiles ();
# use Cpanel::Email::MTAAuthIsExternal ();
# use Cpanel::Hostname ();
# use Cpanel::PwCache ();
# use Cpanel::PwFileCache ();
my $user_domain_cache_mtime = 0;
our $ALLOW_CACHE_REBUILD = 0;
our $PREVENT_CACHE_REBUILD = 1;
sub does_mail_user_exist {
my ( $user, $prevent_cache_rebuild ) = @_;
my $account_info = lookup_mail_user( $user, q{}, $prevent_cache_rebuild );
return 0 if !$account_info->{'status'};
return 0 if !defined $account_info->{'user_info'}{'shadow'}{'user'};
return 1;
}
sub lookup_mail_user {
my ( $user, $addbox, $prevent_cache_rebuild ) = @_;
Cpanel::PwCache::no_uid_cache();
my $accttype = Cpanel::AcctUtils::Lookup::is_webmail_user($user) ? 'mail' : 'system';
my $response = {
'status' => 0,
'statusmsg' => 'Unknown error',
'accttype' => $accttype,
};
my ( $encrypted_pass, $domainowner_encrypted_pass );
my ( $cache_uid, $cache_gid, $passwd_cache_file, $passwd_cache_dir, $passwd_cache_file_mtime );
my ( $passwd_file, $passwd_file_key, $passwd_file_mtime, $username, $uid, $gid, $homedir, $maildir, $address, $pass_change_time );
my ( $quota_file, $quota_exists, $quota, $quota_file_mtime );
my $now = time();
if ( $accttype eq 'mail' ) {
$user = Cpanel::AcctUtils::Lookup::normalize_webmail_user($user);
my ( $subuser, $domain ) = split( m{@}, $user, 2 );
$domain =~ s{/}{}g;
$domain =~ s{[.]+}{.}g;
$address = "$subuser\@$domain";
$response->{'normalized_user'} = $address;
if ( $prevent_cache_rebuild ne $PREVENT_CACHE_REBUILD ) {
_rebuild_userdomain_cache($now);
}
my $domainowner = Cpanel::AcctUtils::DomainOwner::getdomainowner( $domain, { 'skiptruelookup' => 1, 'default' => '' } );
if ( !$domainowner ) {
$response->{'statusmsg'} = "Failed to lookup domain owner of $domain";
return $response;
}
$username = $domainowner;
my $ownerhomedir;
( $domainowner_encrypted_pass, $uid, $gid, $ownerhomedir ) = ( Cpanel::PwCache::getpwnam($domainowner) )[ 1, 2, 3, 7 ];
if ( !$uid || !$gid || !$ownerhomedir || !-d $ownerhomedir ) {
$response->{'statusmsg'} = "Failed to getpwnam for domainowner $domainowner";
return $response;
}
$passwd_cache_file = $subuser;
$passwd_cache_dir = "$ownerhomedir/etc/$domain/\@pwcache";
$passwd_file = "$ownerhomedir/etc/$domain/shadow";
$quota_file = "$ownerhomedir/etc/$domain/quota";
$maildir = "$ownerhomedir/mail/$domain/$subuser" . $addbox;
$homedir = "$ownerhomedir/mail/$domain/$subuser" . $addbox;
$passwd_file_key = $subuser;
}
else {
$response->{'normalized_user'} = $user;
$passwd_file = '/etc/shadow';
( $encrypted_pass, $uid, $gid, $homedir, $pass_change_time ) = ( Cpanel::PwCache::getpwnam($user) )[ 1, 2, 3, 7, 10 ];
if ( !$uid ) {
$response->{'statusmsg'} = "Failed to getpwnam for user $user";
return $response;
}
$username = $user;
$passwd_cache_file = $user;
$passwd_cache_dir = '/var/cpanel/@pwcache';
$cache_uid = 0;
$cache_gid = 0;
$maildir = "$homedir/mail" . $addbox;
$address = $user . '@' . ( Cpanel::Hostname::gethostname() || 'localhost' );
$passwd_file_key = $user;
}
my $quota_file_exists = 0;
my $read_code_ref = sub {
$passwd_cache_file_mtime = ( stat("$passwd_cache_dir/$passwd_cache_file") )[9];
if ( $quota_file && -e $quota_file ) {
$quota_file_exists = 1;
$quota_file_mtime = ( stat(_) )[9];
}
$passwd_file_mtime = ( stat($passwd_file) )[9];
if ( $passwd_cache_file && !defined $encrypted_pass ) { # for accttype eq mail
my $cache_ref = Cpanel::PwFileCache::load_pw_cache(
{
'passwd_cache_file' => $passwd_cache_file,
'passwd_cache_dir' => $passwd_cache_dir,
'passwd_cache_file_mtime' => $passwd_cache_file_mtime || 0,
'quota_file_mtime' => $quota_file_mtime || 0,
'passwd_file_mtime' => $passwd_file_mtime || 0,
}
);
if ( defined $cache_ref->{'passwd'} ) { $encrypted_pass = $cache_ref->{'passwd'}; }
if ( defined $cache_ref->{'quota'} ) { $quota = $cache_ref->{'quota'}; }
if ( defined $cache_ref->{'lastchanged'} ) { $pass_change_time = $cache_ref->{'lastchanged'}; }
}
if ( $quota_file_exists && !defined $quota ) {
$quota = int( Cpanel::PwCache::_get_keyvalue_from_pwfile( $quota_file, 1, $passwd_file_key ) || 0 );
}
if ( !defined $encrypted_pass || !defined $pass_change_time ) {
my $pwref = Cpanel::PwCache::_get_line_from_pwfile( $passwd_file, $passwd_file_key );
if ( $pwref && @{$pwref} ) {
if ( $pwref->[1] ) {
$encrypted_pass = $pwref->[1];
}
if ( $pwref->[2] ) {
$pass_change_time = $pwref->[2];
}
}
}
};
{
my $privs = ( $accttype eq 'mail' ) && ( Cpanel::PwCache::getusername() ne $username );
$privs &&= Cpanel::AccessIds::ReducedPrivileges->new($username);
$read_code_ref->();
}
if ( $passwd_cache_file && length $encrypted_pass ) {
my $safe_quota_file_mtime = $quota_file_mtime || 0;
my $safe_passwd_file_mtime = $passwd_file_mtime || 0;
my $safe_passwd_cache_file_mtime = $passwd_cache_file_mtime || 0;
if ( $safe_passwd_cache_file_mtime > $now || $safe_passwd_cache_file_mtime < $safe_passwd_file_mtime || $safe_passwd_cache_file_mtime < $safe_quota_file_mtime ) {
my $mail_has_external_auth = _mail_has_external_auth();
Cpanel::PwFileCache::save_pw_cache(
{
'passwd_cache_file' => $passwd_cache_file,
'passwd_cache_dir' => $passwd_cache_dir,
'uid' => ( defined $cache_uid ? $cache_uid : $uid ),
'gid' => ( defined $cache_gid ? $cache_gid : ( $mail_has_external_auth ? $gid : ( getgrnam('mail') )[2] ) ),
'keys' => {
'encrypted_pass' => $encrypted_pass,
'quota' => $quota,
'realm' => ( $accttype eq 'system' ? Cpanel::Auth::Digest::Realm::get_realm() : 'mail' ),
'homedir' => $homedir,
'lastchanged' => $pass_change_time,
}
}
);
}
}
$response->{'status'} = 1;
$response->{'statusmsg'} = 'success';
$response->{'user_info'} = {
'shadow' => {
'user' => $encrypted_pass,
'domainowner' => $domainowner_encrypted_pass,
},
'cache' => {
'passwd' => {
'uid' => $cache_uid,
'gid' => $cache_gid,
'file' => $passwd_cache_file,
'dir' => $passwd_cache_dir,
'mtime' => $passwd_cache_file_mtime,
'exists' => ( $passwd_cache_file_mtime ? 1 : 0 ),
},
},
'passwd' => {
'file' => $passwd_file,
'key' => $passwd_file_key,
'exists' => 1,
'mtime' => $passwd_file_mtime,
'user' => $username,
'uid' => $uid,
'gid' => $gid,
'homedir' => $homedir,
'maildir' => $maildir,
'address' => $address,
'pass_change_time' => $pass_change_time,
},
'quota' => {
'file' => $quota_file,
'exists' => $quota_file_exists,
'value' => $quota,
'mtime' => $quota_file_mtime,
}
};
return $response;
}
sub _rebuild_userdomain_cache {
my $now = shift;
if ( ( stat($Cpanel::ConfigFiles::USERDOMAINS_FILE) )[9] > $user_domain_cache_mtime || ( stat(_) )[9] > $now ) {
$user_domain_cache_mtime = ( stat(_) )[9];
return Cpanel::AcctUtils::DomainOwner::build_domain_cache( 'noreversecache' => 1, 'nowwwcache' => 1 );
}
return undef;
}
sub _mail_has_external_auth {
return Cpanel::Email::MTAAuthIsExternal->is_on();
}
1;
} # --- END Cpanel/AcctUtils/Lookup/MailUser.pm
{ # --- BEGIN Cpanel/MultiUserDirStore/VirtualUser.pm
package Cpanel::MultiUserDirStore::VirtualUser;
use strict;
# use Cpanel::AcctUtils::DomainOwner ();
# use Cpanel::AcctUtils::Lookup::MailUser ();
# use Cpanel::Exception ();
# use Cpanel::PwCache ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::Validate::FilesystemNodeName ();
# 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::getdomainowner( $domain, { 'default' => q{} } ) ne $user ) {
die Cpanel::Exception::create( 'DomainOwnership', 'The account “[_1]” does not own the domain “[_2]”.', [ $user, $domain ] );
}
if ( !Cpanel::AcctUtils::Lookup::MailUser::does_mail_user_exist( "$virtual_user\@$domain", $Cpanel::AcctUtils::Lookup::MailUser::ALLOW_CACHE_REBUILD ) ) {
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::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::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 Try::Tiny;
# use Cpanel::Autodie ();
# use Cpanel::AcctUtils::DomainOwner ();
# use Cpanel::Email::Object ();
# use Cpanel::Exception ();
# use Cpanel::FHUtils::Tiny ();
# use Cpanel::iContact::EventImportance ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::Hostname ();
# use Cpanel::Validate::EmailCpanel ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Validate::Domain::Tiny ();
# use Cpanel::Validate::VirtualUsername ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::StringFunc::Trim ();
# use Cpanel::Config::LoadCpUserFile ();
# use Cpanel::Config::LoadWwwAcctConf ();
# use Cpanel::iContact::Email ();
# use Cpanel::PwCache ();
my $NON_ROOT_EVENT_PRIORITY = $Cpanel::iContact::EventImportance::DEFAULT_IMPORTANCE;
our $VERSION = '1.3';
my $logger;
my $LOG_KEEP_DAYS = 30;
my %CONTACTS;
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 = (
'CONTACTAIM' => 'Oscar',
'CONTACTUIN' => 'Oscar',
'CONTACTPUSHBULLET' => 'Pushbullet',
'CONTACTPOSTURL' => 'Posturl',
'CONTACTEMAIL' => 'Email',
'CONTACTPAGER' => 'Pager',
);
sub icontact {
my %AGS = @_;
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 $from = delete $AGS{'from'};
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';
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 $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 ( $from, $subject );
my $contactshash_ref;
my $event_priority;
if ( length $to && !length $subaccount ) {
if ( $to ne 'root' && $to !~ m/\@/ ) {
require Cpanel::Validate::Username;
$username = Cpanel::Validate::Username::normalize($to);
if ( !Cpanel::Config::LoadCpUserFile::has_cpuser_file($username) ) {
die "Nonexistent cPanel user specified in the “to” field: “$username”";
}
$contactshash_ref = _load_user_contactsettings($username);
}
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 );
}
else {
$contactshash_ref = _loadcontactsettings();
}
if ( !$event_priority ) {
my $importance_obj = Cpanel::iContact::EventImportance->new();
if ( 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";
}
if ( !length $from ) {
if ( length $username ) {
if ( $username =~ m{@} ) {
my $virtual_user = ( split( m{@}, $username, 2 ) )[0];
$from = "cPanel for $virtual_user on $from_domain";
}
else {
$from = "cPanel for $username on $from_domain";
}
}
else {
$from = "cPanel on $from_domain";
}
$from .= " <cpanel\@$from_domain>";
}
if ( $from !~ /\@/ ) {
$from = "\"$from\" <cpanel\@$from_domain>";
}
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};
foreach my $contact_type (@keys) {
next if $contact_type eq 'mtime';
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 'CONTACTAIM' || $contact eq 'CONTACTUIN' ) {
push @required, 'user', 'password';
}
for my $req (@required) {
if ( ( ref $contactshash_ref->{$contact}{$req} && !@{ $contactshash_ref->{$contact}{$req} } )
|| !length $contactshash_ref->{$contact}{$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,
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 {
_save_notification_to_log(
'log_user' => ( $username || 'root' ),
'app' => $app,
'email_args_hr' => \%email_args,
);
}
catch {
$logger ||= Cpanel::Logger->new();
$logger->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) {
$logger ||= Cpanel::Logger->new();
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';
$logger->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";
};
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];
}
$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::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 {
Cpanel::Logger->new()->warn( "Failed to send notification of type “$type”: " . Cpanel::Exception::get_string($_) );
};
delete $contactshash_ref->{$type}{'send'};
}
return \@NOTIFICATIONS;
}
sub reloadcontacts {
%CONTACTS = %{ _loadcontactsettings(1) };
}
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 $two_gibibytes = 2 * ( 2**30 );
return (
'Accounts' => scalar $locale->maketext('Digest Authentication Disabled Due to Account Rename'),
'AdminBin' => scalar $locale->maketext('Backup Failure'),
'Backup' => scalar $locale->maketext('[asis,cPanel] Backup'),
'Backup::Delayed' => scalar $locale->maketext('Backup Delayed'),
'Backup::Disabled' => scalar $locale->maketext('[asis,cPanel] Backup Destination Disabled'),
'Backup::Failure' => scalar $locale->maketext('Backup Failed To Finish'),
'Backup::PreBackupNotice' => scalar $locale->maketext('Scheduled Backup Will Start Soon'),
'Backup::Success' => scalar $locale->maketext('Backup Successful'), # case 192249 ensure the word backup comes first for sort order
'Backup::Transport' => scalar $locale->maketext('Backup Transport Error'),
'BandwidthUsageExceeded' => scalar $locale->maketext('Bandwidth Limits'),
'ChangePassword' => scalar $locale->maketext('[asis,cPanel] Account Password'),
'ChangePassword::ResetRequest' => scalar $locale->maketext('[asis,cPanel] Account Forgot Password Request'),
'Check::Biglog' => scalar $locale->maketext( 'System Log Approaches [format_bytes,_1]', $two_gibibytes ),
'Check::PopBeforeSMTPEnabled' => scalar $locale->maketext('[asis,POP] before [asis,SMTP] enabled'),
'Check::CpanelRPMs' => scalar $locale->maketext('Altered [asis,RPMs] Check'),
'Check::EximConfig' => scalar $locale->maketext('[asis,Exim] Update Failures'),
'Check::Hack' => scalar $locale->maketext('Root Compromise Checks'),
'Check::IP' => scalar $locale->maketext('[asis,IP] Address [asis,DNS] Check'),
'Check::ImmutableFiles' => scalar $locale->maketext('Update Failure Due to Immutable Files'),
'Check::InvalidDomains' => scalar $locale->maketext('Invalid Domains'),
'Check::MySQL' => scalar $locale->maketext('Corrupt Database Tables'),
'Check::MysqlConnection' => scalar $locale->maketext('Remote [asis,MySQL] Connection Failure'),
'Check::Oops' => scalar $locale->maketext('Kernel Crash Check'),
'Check::SSLCertExpired' => scalar $locale->maketext('[asis,SSL] Certificate Expiration'),
'Check::SSLCertExpiresSoon' => scalar $locale->maketext('[asis,SSL] Certificate Expires Soon'),
'Check::Smart' => scalar $locale->maketext('Disk Integrity Check'),
'Check::ValidServerHostname' => scalar $locale->maketext('Invalid Hostname For Main [asis,IP] Address'),
'Check::UnmonitoredEnabledServices' => scalar $locale->maketext('Unmonitored Services'),
'Check::SecurityAdvisorStateChange' => scalar $locale->maketext('Security Advisor State Change'),
'Check::HostnameOwnedByUser' => scalar $locale->maketext('Hostname conflicts with a cPanel user account'),
'Check::Resolvers' => scalar $locale->maketext('[asis,DNS] Resolver Performance Issues'),
'Check::WarnIfPerl514TargetEnabled' => scalar $locale->maketext('[asis,cPanel] [asis,Perl] Configuration Check'),
'CloudLinux' => scalar $locale->maketext('[asis,CloudLinux] License Detected'),
'Config' => scalar $locale->maketext('[asis,cPanel] Configuration Checks'),
'ConvertAddon' => scalar $locale->maketext('Convert Addon Domain to Account Notifications'),
'DAV::ChangeHostname' => scalar $locale->maketext('Hostname Change Notifications'),
'dbindex::Warn' => scalar $locale->maketext('[asis,dbindex] Cache File Out of Date'),
'DigestAuth' => scalar $locale->maketext('Forced Disable of Digest Auth'),
'DnsAdmin::ClusterError' => scalar $locale->maketext('[asis,DNS] Cluster Error'),
'DnsAdmin::UnreachablePeer' => scalar $locale->maketext('Lost Contact With [asis,DNS] Cluster'),
'EasyApache' => scalar $locale->maketext('[asis,EasyApache] Configuration'),
'Horde' => scalar $locale->maketext('[asis,Horde] Maintenance Notifications'),
'Notice' => scalar $locale->maketext('Uncategorized'),
'Greylist' => scalar $locale->maketext('[asis,Greylist] System Changes'),
'ImportMyDNSdb::Failure' => scalar $locale->maketext('[asis,MyDNS] Zone Import Failure'),
'ImportMyDNSdb::InProgress' => scalar $locale->maketext('[asis,MyDNS] Zone Import In Progress'),
'ImportMyDNSdb::Success' => scalar $locale->maketext('[asis,MyDNS] Zone Import Successful'),
'Install::ClamavConnector' => scalar $locale->maketext('[asis,ClamAV] Upgrade Changes'),
'Install::Horde' => scalar $locale->maketext('[asis,Horde] Table Conversion Failure'),
'Install::PackageExtension' => scalar $locale->maketext('Package Extension Name Conflicts'),
'Install::FixcPHulkConf' => scalar $locale->maketext('[asis,cPHulk] Configuration Issues'),
'Logd' => scalar $locale->maketext('Bandwidth Data Processing Timeout'),
'Logger' => scalar $locale->maketext('Script Terminated Due to Deprecated Call'),
'Market' => scalar $locale->maketext('Notices concerning goods and services purchased via the [asis,cPanel] Market'),
'Market::SSLWebInstall' => scalar $locale->maketext('Installation of purchased [asis,SSL] certificates'),
'Notice' => scalar $locale->maketext('Generic Notifications'),
'NSD' => scalar $locale->maketext('[asis,NSD] DNS Zones Corrupted'),
'OutdatedSoftware::Notify' => scalar $locale->maketext('Notifications of Outdated Software'),
'OverLoad::CpuWatch' => scalar $locale->maketext('Stalled Process Notifications'),
'OverLoad::LogRunner' => scalar $locale->maketext('Stalled Statistics and Bandwidth Process Notifications'),
'Quota::DiskWarning' => scalar $locale->maketext('User Disk Usage Warning'),
'Quota::RebootRequired' => scalar $locale->maketext('Reboot To Enable Filesystem Quotas Reminder'),
'Quota::SetupComplete' => scalar $locale->maketext('Filesystem Quotas Ready'),
'RPMVersions' => scalar $locale->maketext('Conversion of [asis,cpupdate.conf] settings to [asis,local.versions]'),
'StuckScript' => scalar $locale->maketext('Stuck Script'),
'TwoFactorAuth::UserEnable' => scalar $locale->maketext('User Enabled Two-Factor Authentication'),
'TwoFactorAuth::UserDisable' => scalar $locale->maketext('User Disabled Two-Factor Authentication'),
'Update::Blocker' => scalar $locale->maketext('Update Version Blocker'),
'Update::ServiceDeprecated' => scalar $locale->maketext('Update Blocker - Service Deprecation Notice'),
'Update::UpgradeRequired' => scalar $locale->maketext('Upgrade Required - Service Is Outdated'),
'Update::Now' => scalar $locale->maketext('Update Failures'),
'appconfig' => scalar $locale->maketext('[asis,AppConfig] Registration Notifications'),
'cPHulk' => scalar $locale->maketext('[asis,cPHulkd] Notifications'),
'cPHulk::BruteForce' => scalar $locale->maketext('[asis,cPHulkd] Brute Force'),
'cPHulk::Login' => scalar $locale->maketext('[asis,cPHulkd] Login Notifications'),
'chkservd' => scalar $locale->maketext('Service failures ([asis,ChkServd])'),
'chkservd::DiskUsage' => scalar $locale->maketext('Disk Usage Warnings'),
'chkservd::Hang' => scalar $locale->maketext('Hung Service Checks'),
'chkservd::OOM' => scalar $locale->maketext('Out of Memory'),
'cpbackup' => scalar $locale->maketext('[asis,cPanel] Backup (legacy notification)'),
'cpbackupdisabled' => scalar $locale->maketext('[asis,cPanel] Backup Destination Disabled (legacy notification)'),
'iContact' => scalar $locale->maketext('Instant Message Failure'),
'installbandwidth' => scalar $locale->maketext('Bandwidth File Conversion Disk Space Failure'),
'killacct' => scalar $locale->maketext('Account Removal'),
'migrate_branding' => scalar $locale->maketext('Branding Migration'),
'newmailcgi' => scalar $locale->maketext('Recently Uploaded [asis,CGI] Script Mail'),
'parkadmin' => scalar $locale->maketext('Notification of New Addon Domains'),
'queueprocd' => scalar $locale->maketext('[asis,queueprocd] Critical Errors'),
'rpm.versions' => scalar $locale->maketext('Conversion of [asis,cpupdate.conf] Settings to [asis,local.versions] (legacy notification)'),
'suspendacct' => scalar $locale->maketext('Account Suspensions'),
'sysup' => scalar $locale->maketext('System Update Failures'),
'unsuspendacct' => scalar $locale->maketext('Account UnSuspensions'),
'upacct' => scalar $locale->maketext('Account Upgrades/Downgrades'),
'upcp' => scalar $locale->maketext('[asis,cPanel] Update Failures'),
'wwwacct' => scalar $locale->maketext('Account Creation'),
'Stats' => scalar $locale->maketext('Stats and Bandwidth Processing Errors'),
'PaperLantern::UpdateUsers' => scalar $locale->maketext('User Theme Update'),
'Application' => scalar $locale->maketext('Uncategorized Notifications'),
);
}
sub _load_user_contactsettings {
my $user = shift;
require Cpanel::ContactInfo::Email;
require Cpanel::AcctUtils::GetHomeDir;
my $homedir = Cpanel::AcctUtils::GetHomeDir::gethomedir($user);
my ( $uid, $gid ) = ( Cpanel::PwCache::getpwnam($user) )[ 2, 3 ];
my %USER_CONTACTS;
return {} if !$uid;
$USER_CONTACTS{'CONTACTEMAIL'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'All'};
my @contacts = Cpanel::ContactInfo::Email::getcontactemail( $user, $homedir, $uid, $gid );
$USER_CONTACTS{'CONTACTEMAIL'}{'contact'} = \@contacts;
my $cpuser_data = Cpanel::Config::LoadCpUserFile::loadcpuserfile($user);
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::AcctUtils::GetHomeDir;
require Cpanel::AccessIds::ReducedPrivileges;
require Cpanel::DataStore;
my $homedir = Cpanel::AcctUtils::GetHomeDir::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_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_email) = Cpanel::AccessIds::do_as_user( # do not use call_as_user; only do_as_user
$owner_of_subaccount,
sub {
eval 'require Cpanel::UserManager::Storage'; # hide from perlpkg
my $annotation_list = Cpanel::UserManager::Storage::list_annotations( ( full_username => $full_username ) );
my $email_annotation = $annotation_list->lookup_by( $full_username, 'email' );
my $subaccounts_local_email_address;
if ( $email_annotation && $email_annotation->merged ) {
$subaccounts_local_email_address = $full_username;
}
my $record_obj = Cpanel::UserManager::Storage::lookup_user(
username => $username,
domain => $domain,
);
my $alternate_email = $record_obj->alternate_email;
if ( $use_alternate_email || !$subaccounts_local_email_address ) {
return $alternate_email;
}
return $subaccounts_local_email_address;
}
);
if ($contact_email) {
$SUBACCOUNT_CONTACTS{'CONTACTEMAIL'} = {
'contact' => [$contact_email],
'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} ) ) ];
}
}
}
if ( length $wwwacct_ref->{'AIMPASS'} && length $wwwacct_ref->{'AIMUSER'} ) {
$CONTACTS{'CONTACTAIM'}{'password'} = $wwwacct_ref->{'AIMPASS'};
$CONTACTS{'CONTACTAIM'}{'user'} = $wwwacct_ref->{'AIMUSER'};
}
if ( length $wwwacct_ref->{'ICQPASS'} && length $wwwacct_ref->{'ICQUSER'} ) {
$CONTACTS{'CONTACTUIN'}{'password'} = $wwwacct_ref->{'ICQPASS'};
$CONTACTS{'CONTACTUIN'}{'user'} = $wwwacct_ref->{'ICQUSER'};
}
$CONTACTS{'CONTACTEMAIL'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'All'};
$CONTACTS{'CONTACTPAGER'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'HighOnly'};
$CONTACTS{'CONTACTAIM'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'HighAndMediumOnly'};
$CONTACTS{'CONTACTPUSHBULLET'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'HighAndMediumOnly'};
$CONTACTS{'CONTACTPOSTURL'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'All'};
$CONTACTS{'CONTACTUIN'}{'level'} = $RECEIVES_NAME_TO_NUMBER{'HighAndMediumOnly'};
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[EPUA]+\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 _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::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;
my $fh = $datastore_obj->get_entry_write_fh(
'time' => time(),
'fields' => [ $app, $RESERVED, $RESERVED, $filesys_safe_subject_header ],
'type' => 'eml'
);
return Cpanel::iContact::Email::write_email_to_fh( $fh, %{$email_args_hr} );
}
1;
} # --- END Cpanel/iContact.pm
{ # --- BEGIN Cpanel/Logger.pm
package Cpanel::Logger;
use strict;
# use Cpanel::Time::Local ();
# use Cpanel::FileUtils::Open ();
# use Cpanel::Server::Utils ();
my $is_sandbox;
our $VERSION = 1.3;
our $ENABLE_BACKTRACE = 1;
our $STD_LOG_FILE = '/usr/local/cpanel/logs/error_log';
our $PANIC_LOG_FILE = '/usr/local/cpanel/logs/PANIC_LOG_FILE';
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();
}
}
return $self;
}
sub __Logger_pushback {
if ( @_ && index( ref( $_[0] ), __PACKAGE__ ) == 0 ) {
return @_;
}
else {
return ( __PACKAGE__->new(), @_ );
}
}
sub invalid {
my ( $self, @list ) = &__Logger_pushback(@_);
my %log = (
'message' => $list[0],
'level' => 'invalid',
'output' => 0,
'service' => $self->find_progname(),
'backtrace' => $ENABLE_BACKTRACE,
'die' => 0,
);
if ( is_sandbox() ) {
if ( !-e '/var/cpanel/DEBUG' ) {
require Cpanel::SafeRun::Errors;
$self->notify( 'invalid', \%log );
}
$log{'output'} = -t STDIN ? 2 : 1;
}
return $self->logger( \%log );
} # end of invalid
sub is_sandbox {
return $is_sandbox if defined $is_sandbox;
$is_sandbox = -e '/var/cpanel/dev_sandbox' ? 1 : 0;
}
sub deprecated {
my ( $self, @list ) = &__Logger_pushback(@_);
my %log = (
'message' => $list[0],
'level' => 'deprecated',
'output' => 0,
'service' => $self->find_progname(),
'backtrace' => $ENABLE_BACKTRACE,
'die' => 0,
);
unless ( is_sandbox() ) {
$self->logger( \%log );
return;
}
$self->notify( 'deprecated', \%log );
$log{'output'} = -t STDIN ? 2 : 1;
$log{'die'} = 1;
$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 );
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::CPAN::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' => 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' => -t STDIN ? 2 : 0,
'backtrace' => $ENABLE_BACKTRACE
}
);
} # end of warn
sub die {
my ( $self, @list ) = &__Logger_pushback(@_);
my %log = (
'message' => $list[0],
'level' => 'die',
'output' => -t STDIN ? 2 : 0,
'backtrace' => $ENABLE_BACKTRACE
);
$self->logger( \%log );
} # end of die
sub panic {
my ( $self, @list ) = &__Logger_pushback(@_);
my %log = (
'message' => $list[0],
'level' => 'panic',
'output' => 2,
'backtrace' => $ENABLE_BACKTRACE
);
$self->logger( \%log );
} # end of panic
sub raw {
my ( $self, @list ) = @_;
return $self->logger(
{
'message' => $list[0],
'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 } );
} # 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;
if ( !exists $hr->{'backtrace'} ) {
$hr->{'backtrace'} = $ENABLE_BACKTRACE;
}
$hr->{'use_no_files'} ||= 0;
$hr->{'use_fullmsg'} ||= 0;
return $hr;
}
sub _write {
syswrite( $_[0], $_[1] );
}
sub get_fh {
my ($self) = @_;
return $self->{'log_fh'};
}
sub set_fh {
my ( $self, $fh ) = @_;
$self->{'log_fh'} = $fh;
return 1;
}
sub logger {
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'} ) {
$self->_open_logfile() if !$self->{'log_fh'} || ( !UNIVERSAL::isa( $self->{'log_fh'}, 'IO::Scalar' ) && !fileno( $self->{'log_fh'} ) );
_write( $self->{'log_fh'}, $msg ) or $status = 0;
if ( $hr->{'level'} eq 'panic' || $hr->{'level'} eq 'invalid' || $hr->{'level'} eq 'deprecated' ) {
my $panic_fh;
if ( Cpanel::FileUtils::Open::sysopen_with_real_perms( $panic_fh, $PANIC_LOG_FILE, 'O_WRONLY|O_APPEND|O_CREAT', 0640 ) ) {
$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'};
no strict 'subs';
if ( $hr->{'output'} == 3 ) {
_write( STDOUT, $out ) or $status = 0;
_write( STDERR, $out ) or $status = 0;
}
elsif ( $hr->{'output'} == 1 && ( -t STDOUT || $self->{'use_stdout'} ) ) {
_write( STDOUT, $out ) or $status = 0;
}
elsif ( $hr->{'output'} == 2 ) {
_write( STDERR, $out ) or $status = 0;
}
}
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 find_progname {
if ( $cached_progname && $cached_prog_pid == $$ ) {
return $cached_progname;
}
my $s;
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@;
$s =~ s@\..+$@@;
$cached_progname = $s;
$cached_prog_pid = $$;
$s;
}
sub backtrace {
my ( $self, @list ) = &__Logger_pushback(@_);
return (@list) if ( ref $list[0] );
require Cpanel::Carp;
local $_; # Protect surrounding program - just in case...
local $Carp::Internal{ (__PACKAGE__) } = 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 $logfile = qq{$time [$log_ref->{'service'}] } . $self->backtrace( $log_ref->{'message'} );
if ( eval { require Cpanel::LoadModule; Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Logger::Notify'); 1; } ) {
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'},
]
);
}
else {
require Cpanel::iContact;
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,
);
}
return;
}
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'} && Cpanel::Server::Utils::is_subprocess_of_cpsrvd() ) {
$log_fh = \*STDERR;
$usingstderr = 1;
}
else {
if ( !Cpanel::FileUtils::Open::sysopen_with_real_perms( $log_fh, $self->{'alternate_logfile'}, 'O_WRONLY|O_APPEND|O_CREAT', 0640 ) ) {
( $usingstderr, $log_fh ) = ( 1, \*STDERR );
}
}
$self->{'log_fh'} = $log_fh;
$self->{'usingstderr'} = $usingstderr;
return 1;
}
1;
} # --- END Cpanel/Logger.pm
{ # --- BEGIN Cpanel/SafeRun/Timed.pm
package Cpanel::SafeRun::Timed;
use strict;
our $VERSION = '1.1';
sub timedsaferun {
my ( $timer, @PROGA ) = @_;
return if ( substr( $PROGA[0], 0, 1 ) eq '/' && !-x $PROGA[0] );
my $output;
my $complete = 0;
my $pid;
my $fh; # Case 63723: must declare $fh before eval block in order to avoid unwanted implicit waitpid on die
eval {
local $SIG{'__DIE__'} = 'DEFAULT';
local $SIG{'ALRM'} = sub { die "Timeout while execting: " . join( ' ', @PROGA ) . "\n"; };
alarm($timer);
if ( $pid = open( $fh, '-|' ) ) {
local $/;
$output = readline($fh);
close($fh);
}
elsif ( defined $pid ) {
open( STDIN, '<', '/dev/null' );
exec(@PROGA) or exit 1;
}
else {
warn 'Error while executing: [' . join( ' ', @PROGA ) . ']: ' . $!;
alarm(0);
return;
}
$complete = 1;
alarm 0;
};
alarm 0;
if ( !$complete && $pid && $pid > 0 ) {
kill( 15, $pid ); #TERM
sleep(1); # Give the process a chance to die 'nicely'
kill( 9, $pid ); #KILL
}
return $output;
}
1;
} # --- END Cpanel/SafeRun/Timed.pm
{ # --- BEGIN Cpanel/SafeRun/Env.pm
package Cpanel::SafeRun::Env;
use strict;
# use Cpanel::Env ();
# use Cpanel::Logger ();
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' );
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::Logger::logger( { 'message' => 'Cannot execute a null program', 'level' => 'warn', 'service' => __PACKAGE__, 'output' => 2, 'backtrace' => 1 } );
return \$output if $return_reference;
return $output;
}
require Cpanel::Env;
local ( $/, *PROG, *RNULL );
open( RNULL, '<', '/dev/null' );
my $pid = open( PROG, "-|" );
if ( $pid > 0 ) {
$output = <PROG>;
}
elsif ( $pid == 0 ) {
open( STDIN, '<&RNULL' );
if ($error_output) {
open STDERR, '>&STDOUT';
}
Cpanel::Env::cleanenv(%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::Logger::logger( { 'message' => 'Could not fork new process', 'level' => 'warn', 'service' => __PACKAGE__, 'output' => 2, 'backtrace' => 1 } );
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/QuotaMtime.pm
package Cpanel::QuotaMtime;
my %MOUNT_POINTS;
my $mount_points_mtime;
sub get_quota_mtime {
my $mtime_to_beat = shift;
my $maxmtime = 0;
my $fstab_mtime = ( stat('/etc/fstab') )[9];
if ( !$mount_points_mtime || $mount_points_mtime != $fstab_mtime ) {
if ( open my $fh_fstab, '<', '/etc/fstab' ) {
%MOUNT_POINTS = ();
$mount_points_mtime = $fstab_mtime;
my ( $mntpoint, $fstype, $options );
while ( my $line = <$fh_fstab> ) {
next if ( $line =~ /^\s*#/ ); # skip comments
if ( ( ( $mntpoint, $fstype, $options ) = $line =~ /\S+[\t\s]+(\S+)\s+(\S+)\s*(\S*)/ )[0] ) {
if (
( $options && $options !~ /quota/i ) || # do not check fses without quota
( $mntpoint =~ m/\/virtfs\// || $mntpoint eq 'swap' || $mntpoint !~ /^\// || $mntpoint =~ m/^\/(?:mnt\/|swap|proc|dev|boot|sys)/ ) || #why waste a stat() ?
( $fstype eq 'nfs' || $fstype eq 'coda' || $fstype eq 'smb' ) #do not check network filesystems as they may be slow
) {
next;
}
$mntpoint =~ s/\/+$//;
$MOUNT_POINTS{$mntpoint} = undef;
}
}
close($fh_fstab);
}
}
foreach my $quota_file ( map { $_ . '/aquota.user', $_ . '/quota.user' } keys %MOUNT_POINTS ) {
next if !-e $quota_file;
my $qmtime = ( stat(_) )[9];
return $qmtime if ( $mtime_to_beat && $qmtime > $mtime_to_beat );
if ( $qmtime > $maxmtime ) { $maxmtime = $qmtime; }
}
return $maxmtime;
}
1;
} # --- END Cpanel/QuotaMtime.pm
{ # --- BEGIN Cpanel/CachedCommand/Save.pm
package Cpanel::CachedCommand::Save;
# use Cpanel::CachedCommand::Utils ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::Logger ();
use Errno qw[EDQUOT];
use Try::Tiny;
my $logger = Cpanel::Logger->new();
sub _savefile {
my ( $filename, $content ) = @_;
return if !defined $content; #should be able to store 0
$filename =~ s{//+}{/}g;
my @path = split( /\//, $filename );
my $file = pop(@path);
my $dir = join( '/', @path );
my $dir_uid = ( stat($dir) )[4];
if ( !defined $dir_uid ) {
$logger->warn("Unable to write datastore file: $filename: target directory: $dir does not exist.");
return;
}
elsif ( $dir_uid != $> ) {
$logger->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 = $_;
if ( try { $err->get('error') == EDQUOT } ) {
$logger->warn( Cpanel::Exception::get_string($err) );
}
else {
local $@ = $err;
die;
}
};
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/CachedCommand.pm
package Cpanel::CachedCommand;
# use Cpanel::StatCache ();
# use Cpanel::Logger ();
# use Cpanel::LoadFile ();
# use Cpanel::SafeRun::Timed ();
# use Cpanel::SafeRun::Env ();
# use Cpanel::SafeRun::Errors ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::FindBin ();
# use Cpanel::QuotaMtime ();
# use Cpanel::CachedCommand::Utils ();
# use Cpanel::CachedCommand::Save ();
# use Cpanel::Debug ();
our $VERSION = '2.5';
my %MEMORY_CACHE;
my $logger = Cpanel::Logger->new();
*_get_datastore_filename = \&Cpanel::CachedCommand::Utils::_get_datastore_filename;
*destroy = \&Cpanel::CachedCommand::Utils::destroy;
*store = \&Cpanel::CachedCommand::Save::store;
*_savefile = \&Cpanel::CachedCommand::Save::_savefile;
sub _getquota_mtime {
if ( exists $Cpanel::CONF{'disablequotacache'}
&& $Cpanel::CONF{'disablequotacache'} eq '1' ) {
return ( time() + 10000 );
}
return Cpanel::QuotaMtime::get_quota_mtime();
}
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 _is_cache_valid {
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 '/' ) {
$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;
}
sub invalidate_cache {
my $ds_file = Cpanel::CachedCommand::Utils::_get_datastore_filename(@_);
unlink $ds_file;
delete $MEMORY_CACHE{$ds_file};
return;
}
sub _cached_cmd {
my %OPTS = @_;
my ( $cleanenv, $cleanenv2, $binary, $ttl, $mtime, $timer, $exact, $regexcheck, $args_hr, $min_expire_time, $suppress_errors ) = (
( $OPTS{'cleanenv'} || 0 ),
( $OPTS{'cleanenv2'} || 0 ),
( $OPTS{'binary'} || '' ),
( $OPTS{'ttl'} || 0 ),
( $OPTS{'mtime'} || 0 ),
( $OPTS{'timer'} || 0 ),
( $OPTS{'exact'} || 0 ),
( $OPTS{'regexcheck'} || '' ),
( $OPTS{'args_hr'} || {} ),
( $OPTS{'min_expire_time'} || 0 ),
( $OPTS{'suppress_errors'} || 0 ),
);
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 && $#SAFEAG > 3 ) {
splice( @SAFEAG, 3 );
}
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 (
_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();
if ($suppress_errors) {
$res = Cpanel::SafeRun::Errors::saferunnoerror( $binary, @AG );
}
elsif ( int($timer) > 0 ) {
$res = Cpanel::SafeRun::Timed::timedsaferun( $timer, $binary, @AG );
}
elsif ($cleanenv) {
$res = Cpanel::SafeRun::Env::saferun_r_cleanenv( $binary, @AG );
}
elsif ($cleanenv2) {
$res = Cpanel::SafeRun::Env::saferun_cleanenv2($args_hr);
}
else {
$res = Cpanel::SafeRun::Simple::saferun_r( $binary, @AG );
}
if ( !$regexcheck || ( ref $res ? $$res : $res ) =~ m/$regexcheck/ ) {
print STDERR "_cached_command: writing datastore file: $datastore_file " . ( $regexcheck ? "regex_check: $regexcheck" : '' ) . "\n" if $Cpanel::Debug::level;
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;
}
}
if ( ref $res ) {
if ( $ttl && length($$res) < 32768 ) { $MEMORY_CACHE{$datastore_file} = { 'mtime' => $data_mtime, 'contents' => $res }; }
return $res;
}
else {
if ( $ttl && length($res) < 32768 ) { $MEMORY_CACHE{$datastore_file} = { 'mtime' => $data_mtime, 'contents' => \$res }; }
return \$res;
}
}
sub has_cache {
my ( $ttl, $bin, @AG ) = @_;
my @SAFEAG = @AG;
if ( $#SAFEAG > 3 ) {
splice( @SAFEAG, 3 );
}
my $datastore_file = Cpanel::CachedCommand::Utils::_get_datastore_filename( $bin, @SAFEAG );
return (
_is_cache_valid(
'datastore_file' => $datastore_file,
'binary' => $bin,
'ttl' => $ttl
)
) ? 1 : 0;
}
sub cachedcommand {
my $binary = shift;
my @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_multifile {
my $test_file_ar = shift;
my $binary = shift;
my @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 = shift;
my $binary = shift;
my @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 = shift;
my $binary = shift;
my @ARGS = @_;
my $cache_ref = _cached_cmd(
'cleanenv' => 1,
'ttl' => $ttl,
'binary' => $binary,
'args' => \@ARGS
);
if ( ref $cache_ref ne 'SCALAR' ) { return \$cache_ref; }
return $cache_ref;
}
sub cachedmcommand_cleanenv2 {
my $ttl = shift;
my $args_hr = shift;
my @cmd = @{ $args_hr->{'command'} };
my $binary = shift @cmd;
my @ARGS = @cmd;
my $cache_ref = _cached_cmd(
'cleanenv2' => 1,
'ttl' => $ttl,
'binary' => $binary,
'args' => \@ARGS,
'args_hr' => $args_hr,
);
return $cache_ref;
}
sub cachedmcommand_r {
my $ttl = shift;
my $binary = shift;
my @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 cachedquotacommand {
my $binary = shift;
my @ARGS = @_;
my $mtime = _getquota_mtime();
my $cache_ref = _cached_cmd(
'ttl' => 900,
'min_expire_time' => ( ( exists $Cpanel::CONF{'disablequotacache'} && $Cpanel::CONF{'disablequotacache'} eq '1' ) ? 0 : 300 ),
'binary' => $binary,
'args' => \@ARGS,
'mtime' => $mtime
);
if ( ref $cache_ref eq 'SCALAR' ) { return $$cache_ref; }
return;
}
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,
'timer' => $timer,
'exact' => $exact,
'regexcheck' => $regexcheck,
'args' => \@AG
);
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 Cpanel::SafeRun::Simple::saferun( $bin, @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/OSSys/Env.pm
package Cpanel::OSSys::Env;
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);
if ( !$envtype ) {
require Cpanel::Logger;
Cpanel::Logger->new()->warn('Failed to load envtype. Defaulting to "standard".');
return 'standard';
}
}
return $envtype;
}
1;
} # --- END Cpanel/OSSys/Env.pm
{ # --- BEGIN Cpanel/Sys/GetOS.pm
package Cpanel::Sys::GetOS;
our $VERSION = '1.2';
use strict;
my ( $cached_os, $cached_os_release_file );
sub getos {
defined $cached_os ? $cached_os : ( getos_and_release_file() )[0];
}
sub getos_and_release_file {
return ( $cached_os, $cached_os_release_file ) if defined $cached_os;
if ( ( my $os_cache_fs_mtime = ( stat('/var/cpanel/GetOS.cache') )[9] ) && open( my $os_fh, '<', '/var/cpanel/GetOS.cache' ) ) {
local $/;
my ( $fs_os_release_file, $fs_os, $fs_version ) = split( /\n/, readline($os_fh) );
my ( $fs_os_release_file_mtime, $fs_os_release_file_ctime ) = ( stat($fs_os_release_file) )[ 9, 10 ];
if ( $fs_version eq $VERSION && $os_cache_fs_mtime > $fs_os_release_file_mtime && $os_cache_fs_mtime > $fs_os_release_file_ctime ) {
return ( $cached_os = $fs_os, $cached_os_release_file = $fs_os_release_file );
}
}
my ( $os_release_file, $os );
foreach my $test_release_file ( 'CentOS-release', 'redhat-release', 'system-release' ) {
if ( -e '/etc/' . $test_release_file ) {
if ( ( ($os) = $test_release_file =~ m/^([^\-_]+)/ )[0] ) {
$os = lc $os; #lc ok here as no danger of utf-8 data
$os_release_file = '/etc/' . $test_release_file;
if ( $os eq 'system' ) {
$os = 'amazon';
}
last;
}
}
}
if ( !$os ) {
require Cpanel::Logger;
Cpanel::Logger::cplog( 'Unsupported operating system', 'die', __PACKAGE__ );
}
if ( $os eq 'redhat' || $os eq 'amazon' ) {
if ( open my $release_fh, '<', $os_release_file ) {
local $/;
if ( readline($release_fh) =~ /(centos|cloudlinux|amazon)/i ) { $os = lc $1; }
close $release_fh;
}
else {
require Cpanel::Logger;
Cpanel::Logger::cplog( 'Cannot open ' . $os_release_file, 'die', __PACKAGE__ );
}
}
if ( $> == 0 && open( my $os_fh, '>', '/var/cpanel/GetOS.cache' ) ) {
print {$os_fh} $os_release_file . "\n" . $os . "\n" . $VERSION;
}
return ( $cached_os = $os, $cached_os_release_file = $os_release_file );
}
1;
} # --- END Cpanel/Sys/GetOS.pm
{ # --- BEGIN Cpanel/Sys/OS.pm
package Cpanel::Sys::OS;
use strict;
# use Cpanel::Sys::GetOS ();
our $VERSION = '1.3';
my $cached_release_version;
my $cached_ises;
{
no warnings 'once';
*getos = \&Cpanel::Sys::GetOS::getos;
}
sub getreleaseversion {
if ( defined $cached_release_version && $cached_release_version ) {
return wantarray ? ( $cached_release_version, $cached_ises ) : $cached_release_version;
}
my ( $os, $releasefile ) = Cpanel::Sys::GetOS::getos_and_release_file();
if ( !$releasefile ) {
require Cpanel::Logger;
Cpanel::Logger::cplog( "Unsupported OS: $os", 'die', __PACKAGE__ );
}
( $cached_release_version, $cached_ises ) = getversionfromfile($releasefile);
return wantarray ? ( $cached_release_version, $cached_ises ) : $cached_release_version;
}
sub getversionfromfile {
my $file = shift;
my $ises = 0;
my $version = '';
if ( !defined($file) ) {
require Cpanel::Logger;
Cpanel::Logger::cplog( "No file argument", 'die', __PACKAGE__ );
}
if ( open my $fh, '<', $file ) {
my $line = readline $fh;
close $fh;
chomp $line;
if ( $line =~ m/(?:Corporate|Advanced\sServer|Enterprise|Amazon)/i ) { $ises = 1; }
elsif ( $line =~ /CloudLinux|CentOS/i ) { $ises = 2; }
if ( $line =~ /(\d+\.\d+)/ ) { $version = $1; }
elsif ( $line =~ /(\d+)/ ) { $version = $1; }
}
else {
require Cpanel::Logger;
Cpanel::Logger::cplog( "Cannot open file $file", 'die', __PACKAGE__ );
}
if ( $version eq '' ) {
require Cpanel::Logger;
Cpanel::Logger::cplog( 'Can not find distro version', 'die', __PACKAGE__ );
}
return wantarray ? ( $version, $ises ) : $version;
}
sub is_booting {
if ( getreleaseversion() < 7 || !_has_systemctl() ) {
chomp( my $runlevel = _run_runlevel() );
return 1 if !$runlevel;
return 1 if $runlevel !~ m/(\b[0-9]$)/;
return 1 if $1 < 3;
}
else {
return 1 if 'active' ne _run_systemctl(qw{ is-active multi-user.target });
}
return 0;
}
sub _run_runlevel {
chomp( my $runlevel = qx{/sbin/runlevel} );
return $runlevel;
}
sub _has_systemctl {
return !!-x '/bin/systemctl';
}
sub _run_systemctl {
my (@args) = @_;
my $cmd = join ' ', '/bin/systemctl', @args;
chomp( my $res = qx/$cmd/ );
return $res || 'unknown';
}
1;
} # --- END Cpanel/Sys/OS.pm
{ # --- BEGIN Cpanel/GenSysInfo.pm
package Cpanel::GenSysInfo;
use strict;
use warnings;
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::FlushConfig ();
# use Cpanel::Sys::OS ();
# use Cpanel::SafeRun::Errors ();
our $sys_info_dir = '/var/cpanel';
our $sys_info_file = "$sys_info_dir/sysinfo.config";
our $amazon_release_file = '/etc/system-release';
our %run_cache; # run only needs to execute once in any given process.
sub run {
return \%run_cache if (%run_cache);
mkdir $sys_info_dir if ( !-d $sys_info_dir );
my $old_conf = {};
Cpanel::Config::LoadConfig::loadConfig( $sys_info_file, $old_conf, '=' );
if ( $> != 0 && keys %$old_conf ) {
%run_cache = %$old_conf;
}
else {
my $new_conf = _get_new_conf($old_conf);
if ( _conf_changed( $old_conf, $new_conf ) ) {
Cpanel::Config::FlushConfig::flushConfig( $sys_info_file, $new_conf, '=', _config_file_header(), { 'sort' => 1 } );
print "$sys_info_file updated.\n";
}
%run_cache = %$new_conf;
}
return \%run_cache; # Useful when not called from gensysinfo
}
sub get_rpm_distro {
return run()->{'rpm_dist'} || 'unknown'; # run() ALWAYS will return a hash ref (or die)
}
sub get_rpm_arch {
return run()->{'rpm_arch'} || 'unknown'; # run() ALWAYS will return a hash ref (or die)
}
sub get_rpm_distro_version {
return run()->{'rpm_dist_ver'} || 0; # run() ALWAYS will return a hash ref (or die)
}
sub get_system_release_file {
my @supported_files = ( '/etc/redhat-release', $amazon_release_file );
my $release_file;
foreach my $check_file (@supported_files) {
if ( defined($release_file) || !-e $check_file ) {
next;
}
else {
$release_file = $check_file;
}
}
return $release_file;
}
sub _get_new_conf {
my $old_conf = shift or die;
my %new_conf = %$old_conf;
$new_conf{'lock'} ||= '';
my %locked_values = map { ( $_ => 1 ) } split( qr/\s*,\s*/, $new_conf{'lock'} );
$new_conf{'rpm_arch'} = _get_rpm_arch() unless ( $locked_values{'rpm_arch'} );
$new_conf{'rpm_dist'} = _get_rpm_distro() unless ( $locked_values{'rpm_dist'} );
$new_conf{'rpm_dist_ver'} = _get_rpm_distro_version() unless ( $locked_values{'rpm_dist_ver'} );
if ( -e $sys_info_file && ( !$locked_values{'rpm_dist_ver'} && !$new_conf{'rpm_dist_ver'} or $new_conf{'rpm_dist'} eq 'unknown' ) ) {
print "ERROR: The system cannot update the $sys_info_file file because it cannot determine your distribution's major version.\n";
print "Run the following command: " . q{rpm -qf --queryformat '%{VERSION}\n' /etc/redhat-release} . "\n";
print "Output other than the numbers 5 or 6 indicates a problem. Open a support ticket or resolve the issue manually.\n\n";
die("The system cannot update the $sys_info_file file.");
}
my ( $release, $ises ) = Cpanel::Sys::OS::getreleaseversion();
$new_conf{'ises'} = $ises unless ( $locked_values{'ises'} );
$new_conf{'release'} = $release unless ( $locked_values{'release'} );
return \%new_conf;
}
sub _config_file_header {
return
"# This values in this file are calculated and updated if necessary nightly. If you wish to override\n"
. "# these values, populate lock= with a comma delimited list of keys you don't want updated.\n"
. "# This will allow you to change those values to suit your needs.\n" . "#\n"
. "# Example: if you set lock like this, then rpm_dist and rpm_arch will not be updated nightly:\n"
. "# lock=rpm_dist,rpm_arch\n" . "#";
}
sub _conf_changed {
my $old = shift or die;
my $new = shift or die;
return 1 if ( scalar keys %$old != scalar keys %$new );
foreach my $key ( keys %$old ) {
return 1 if ( $old->{$key} ne $new->{$key} );
}
return 0;
}
sub _get_rpm_distro {
my $release_file = get_system_release_file();
if ( !defined($release_file) ) {
die("The system detected an unsupported operating system, and could not find the distro release file.");
}
my $os = Cpanel::SafeRun::Errors::saferunallerrors( qw{/bin/rpm -qf}, $release_file );
return 'rhel' if ( $os =~ m/^redhat|enterprise-release/i );
return 'cloudlinux' if ( $os =~ m/^cloud/i );
return 'amazon' if ( $os =~ m/^system/i );
return 'centos';
}
sub _get_rpm_arch {
my $rpm_arch = Cpanel::SafeRun::Errors::saferunallerrors(qw{/bin/rpm --eval=%_arch});
chomp $rpm_arch;
return $rpm_arch;
}
sub _get_rpm_distro_version {
my $release_file = get_system_release_file();
if ( !defined($release_file) ) {
die("The system detected an unsupported operating system, and could not find the distro release file.");
}
my $distro_version = 0;
my @version_output = Cpanel::SafeRun::Errors::saferunallerrors( qw{/bin/rpm -qf --queryformat}, '%{VERSION}\n', $release_file );
my $version = shift @version_output or return $distro_version;
if ( $release_file eq $amazon_release_file ) {
$distro_version = 6;
}
else {
return $distro_version if ( @version_output && grep { $_ ? ( substr( $_, 0, 1 ) ne substr( $version, 0, 1 ) ) : 0 } @version_output );
if ( $version =~ m/^([567])/ ) {
$distro_version = $1;
}
}
return "$distro_version";
}
1;
} # --- END Cpanel/GenSysInfo.pm
{ # --- BEGIN Cpanel/CloudLinux.pm
package Cpanel::CloudLinux;
# use Cpanel::CachedCommand ();
# use Cpanel::OSSys::Env ();
# use Cpanel::GenSysInfo ();
my $spacewalk = '/usr/sbin/spacewalk-channel';
sub enabled {
if ( has_channel() && installed() ) {
return 1;
}
return 0;
}
sub nocloudlinux {
return -e '/var/cpanel/nocloudlinux';
}
sub licensed {
my $cpanel_bin = '/usr/local/cpanel/cpanel';
my $cpanel_flags = Cpanel::CachedCommand::cachedcommand_multifile( ['/usr/local/cpanel/cpanel.lisc'], $cpanel_bin, '-F' );
chomp $cpanel_flags;
if ($cpanel_flags) {
my @flags = split( /,/, $cpanel_flags );
if ( grep { $_ eq 'cloudlinux' } @flags ) {
return 1;
}
}
return 0;
}
sub has_channel {
if ( !-x $spacewalk ) {
return 0;
}
my $rhn_channel_list = Cpanel::CachedCommand::cachedcommand_multifile( ['/etc/redhat-release'], $spacewalk, '--list' );
if ( $rhn_channel_list =~ m/\bcloudlinux\b/m ) {
return 1;
}
return 0;
}
sub installed {
if ( -x '/usr/sbin/lvectl' && -x '/usr/sbin/lveinfo' ) {
return 1;
}
return 0;
}
sub kernel_support {
if ( open my $proc_modules_fh, '<', '/proc/modules' ) {
while ( my $line = readline $proc_modules_fh ) {
if ( $line =~ m/^lve\s/ ) {
close $proc_modules_fh;
return 1;
}
}
close $proc_modules_fh;
}
return 0;
}
sub supported_os {
my $v = Cpanel::GenSysInfo::get_rpm_distro_version();
return 0 if !$v || $v eq 'unknown';
$v = int($v);
if ( 5 <= $v && $v <= 7 ) {
return 1;
}
return 0;
}
sub supported_envtype {
my $envtype = Cpanel::OSSys::Env::get_envtype();
if ( $envtype eq 'standard'
|| $envtype eq 'hyper-v'
|| $envtype eq 'kvm'
|| $envtype eq 'smartos'
|| $envtype eq 'parallels'
|| $envtype eq 'vmware'
|| $envtype eq 'virtualbox'
|| $envtype =~ /^xen/ ) {
return 1;
}
return 0;
}
sub set_spacewalk_bin {
$spacewalk = $_[0];
}
1;
} # --- END Cpanel/CloudLinux.pm
{ # --- BEGIN Cpanel/SafeDir/RM.pm
package Cpanel::SafeDir::RM;
# use Cpanel::LoadModule ();
our $NO_FALLBACK = 0;
sub safermdir {
return if !-d $_[0];
if ($NO_FALLBACK) {
Cpanel::LoadModule::lazy_load_module('File::Copy::Recursive');
if ( exists $INC{'File/Copy/Recursive.pm'} ) {
goto &File::Copy::Recursive::pathrmdir;
}
else {
return; # NO FALLBACK when we cannot load module
}
}
system( 'rm', '-rf', '--', $_[0] );
if ( !-d $_[0] ) {
$? = 0;
return 1;
}
return;
}
1;
} # --- END Cpanel/SafeDir/RM.pm
{ # --- BEGIN Cpanel/TempFile.pm
package Cpanel::TempFile;
use strict;
# use Cpanel::Rand ();
# use Cpanel::PwCache ();
# use Cpanel::Logger ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeDir::RM ();
# use Cpanel::Fcntl ();
# use Cpanel::Debug ();
# use Cpanel::Destruct ();
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 {
get_safe_tmp_file_or_dir( $Cpanel::Rand::TYPE_FILE, @_ );
}
sub get_safe_tmpdir {
get_safe_tmp_file_or_dir( $Cpanel::Rand::TYPE_DIR, @_ );
}
sub get_safe_tmp_file_or_dir {
my $file_or_dir = shift;
my $homedir = $Cpanel::homedir || ( Cpanel::PwCache::getpwuid($>) )[7];
if ( !-d $homedir . '/tmp' ) {
if ( !mkdir( $homedir . '/tmp', 0755 ) ) {
my $logger = Cpanel::Logger->new();
$logger->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->{'logger'} = Cpanel::Logger->new();
$self->set_opts($opts);
$self->{'needunlink'} = [];
$self->{'_pid'} = $$;
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;
for my $key ( keys %{$opts} ) {
my $notfound = !grep { $key eq $_ } @valid_keys;
if ($notfound) {
$self->_warn("Disallowing invalid opt '$key' passed in opts hash");
}
$err |= $notfound;
}
return if $err;
$opts = {}
unless defined $opts;
$self->{'opts'} = {}
unless defined $self->{'opts'};
my @debug;
while ( ( my ( $k, $v ) ) = each %{$opts} ) {
$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;
if ( defined $path ) {
substr $prefix, 0, 0, "$path/";
}
if ( !-e $path ) {
my $nonexist = "Non-existent path '$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 to rightmost position, leaving as is");
$fname = $orig;
}
}
}
else {
printf STDERR "no change to $orig\n";
}
}
return $fname;
}
sub _info {
my ( $self, $msg ) = @_;
$self->{'logger'}->info($msg);
}
sub _warn {
my ( $self, $msg ) = @_;
$self->{'logger'}->warn($msg);
}
sub _debug {
my ( $self, $msg ) = @_;
return unless $Cpanel::Debug::level;
$self->{'logger'}->debug($msg);
}
sub _die {
my ( $self, $msg ) = @_;
$self->{'logger'}->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;
my @needunlink = sort { length $b <=> length $a } @{ $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 $file;
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 ( -d $file ) {
local $?;
Cpanel::SafeDir::RM::safermdir($file);
$file_or_dir = "dir";
}
else {
unlink($file);
$file_or_dir = "file";
}
my $intro = $existed && !-e $file ? "R" : "Not r";
$self->_debug("${intro}emoved: $file_or_dir $file");
}
}
}
@{ $self->{'needunlink'} } = ();
}
sub needunlink {
my ( $self, $item ) = @_;
push @{ $self->{'needunlink'} }, $item;
return;
}
sub DESTROY {
my $self = shift;
return if Cpanel::Destruct::in_dangerous_global_destruction();
return unless $self->{'_pid'} == $$;
$self->cleanup;
}
1;
} # --- END Cpanel/TempFile.pm
{ # --- BEGIN Cpanel/Crypt/GPG.pm
package Cpanel::Crypt::GPG;
use strict;
# use Cpanel::TempFile ();
# use Cpanel::SafeRun::Object ();
sub new {
my ( $class, %args ) = @_;
my $bin = _find_gpg_bin();
if ( !$bin ) {
return wantarray ? ( undef, "Failed to find the GnuPG binary." ) : undef;
}
my $tmp = Cpanel::TempFile->new;
my $path = $tmp->dir();
my $obj = {
tmp => $tmp,
path => $path,
bin => $bin,
};
return bless $obj, $class;
}
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} );
}
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);
}
}
else {
return wantarray ? ( undef, "Arguments 'files' or 'files_data' must be provided." ) : undef;
}
my @args = (
'--logger-fd', '1',
'--status-fd', '1',
'--homedir', $self->{path},
'--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 ) : $sig_data;
}
sub add_pub_key {
my ( $self, %args ) = @_;
if ( !$args{key} ) {
return wantarray ? ( undef, "No key provided." ) : undef;
}
my $key = $self->_write_data_to_temp_file( $args{key} );
my @args = (
'--logger-fd', '1',
'--status-fd', '1',
'--homedir', $self->{path},
$args{dry_run} ? '--dry-run' : (),
'--import', $key,
);
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 @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, dry_run => 1 ) ) {
@r = ( $id, "Successfully parsed key id." );
}
return wantarray ? @r : shift @r;
}
sub _find_gpg_bin {
for my $path (qw ( /usr/bin/gpg )) {
if ( -x $path ) {
return $path;
}
}
return undef;
}
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.pm
{ # --- BEGIN Cpanel/CPAN/YAML/Tiny.pm
package Cpanel::CPAN::YAML::Tiny;
use strict;
sub HAVE_UTF8 () { $] >= 5.007003 }
BEGIN {
if (HAVE_UTF8) {
eval "require utf8;";
die "Failed to load UTF-8 support" if $@;
}
require 5.004;
require Exporter;
require Carp;
$Cpanel::CPAN::YAML::Tiny::VERSION = '1.48';
@Cpanel::CPAN::YAML::Tiny::ISA = qw{ Exporter };
@Cpanel::CPAN::YAML::Tiny::EXPORT = qw{ Load Dump };
@Cpanel::CPAN::YAML::Tiny::EXPORT_OK = qw{ LoadFile DumpFile freeze thaw };
$Cpanel::CPAN::YAML::Tiny::errstr = '';
}
my @UNPRINTABLE = qw(
z x01 x02 x03 x04 x05 x06 a
x08 t n v f r x0e x0f
x10 x11 x12 x13 x14 x15 x16 x17
x18 x19 x1a e x1c x1d x1e x1f
);
my %UNESCAPES = (
z => "\x00", a => "\x07", t => "\x09",
n => "\x0a", v => "\x0b", f => "\x0c",
r => "\x0d", e => "\x1b", '\\' => '\\',
);
my %QUOTE = map { $_ => 1 } qw{
null Null NULL
y Y yes Yes YES n N no No NO
true True TRUE false False FALSE
on On ON off Off OFF
};
sub new {
my $class = shift;
bless [@_], $class;
}
sub read {
my $class = ref $_[0] ? ref shift : shift;
my $file = shift or return $class->_error('You did not specify a file name');
return $class->_error("File '$file' does not exist") unless -e $file;
return $class->_error("'$file' is a directory, not a file") unless -f _;
return $class->_error("Insufficient permissions to read '$file'") unless -r _;
local $/ = undef;
local *CFG;
unless ( open( CFG, $file ) ) {
return $class->_error("Failed to open file '$file': $!");
}
my $contents = <CFG>;
unless ( close(CFG) ) {
return $class->_error("Failed to close file '$file': $!");
}
$class->read_string($contents);
}
sub read_string {
my $class = ref $_[0] ? ref shift : shift;
my $self = bless [], $class;
my $string = $_[0];
eval {
unless ( defined $string ) {
die \"Did not provide a string to load";
}
if ( $string =~ /^(?:\376\377|\377\376|\377\376\0\0|\0\0\376\377)/ ) {
die \"Stream has a non UTF-8 BOM";
}
else {
$string =~ s/^\357\273\277//;
}
utf8::decode($string) if HAVE_UTF8;
return $self unless length $string;
unless ( $string =~ /[\012\015]+\z/ ) {
die \"Stream does not end with newline character";
}
my @lines = grep { !/^\s*(?:\#.*)?\z/ }
split /(?:\015{1,2}\012|\015|\012)/, $string;
@lines and $lines[0] =~ /^\%YAML[: ][\d\.]+.*\z/ and shift @lines;
while (@lines) {
if ( $lines[0] =~ /^---\s*(?:(.+)\s*)?\z/ ) {
shift @lines;
if ( defined $1 and $1 !~ /^(?:\#.+|\%YAML[: ][\d\.]+)\z/ ) {
push @$self, $self->_read_scalar( "$1", [undef], \@lines );
next;
}
}
if ( !@lines or $lines[0] =~ /^(?:---|\.\.\.)/ ) {
push @$self, undef;
while ( @lines and $lines[0] !~ /^---/ ) {
shift @lines;
}
}
elsif ( $lines[0] =~ /^\s*\-/ ) {
my $document = [];
push @$self, $document;
$self->_read_array( $document, [0], \@lines );
}
elsif ( $lines[0] =~ /^(\s*)\S/ ) {
my $document = {};
push @$self, $document;
$self->_read_hash( $document, [ length($1) ], \@lines );
}
else {
die \"Cpanel::CPAN::YAML::Tiny failed to classify the line '$lines[0]'";
}
}
};
if ( ref $@ eq 'SCALAR' ) {
Carp::confess ${$@};
return $self->_error( ${$@} );
}
elsif ($@) {
require Carp;
Carp::croak($@);
}
return $self;
}
sub _read_scalar {
my ( $self, $string, $indent, $lines ) = @_;
$string =~ s/\s*\z//;
return undef if $string eq '~';
if ( $string =~ /^\'(.*?)\'(?:\s+\#.*)?\z/ ) {
return '' unless defined $1;
$string = $1;
$string =~ s/\'\'/\'/g;
return $string;
}
if ( $string =~ /^\"([^\\"]*(?:\\.[^\\"]*)*)\"(?:\s+\#.*)?\z/ ) {
$string = $1;
$string =~ s/\\"/"/g;
$string =~ s/\\([never\\fartz]|x([0-9a-fA-F]{2}))/(length($1)>1)?pack("H2",$2):$UNESCAPES{$1}/gex;
return $string;
}
if ( $string =~ /^[\'\"!&]/ ) {
die \"Cpanel::CPAN::YAML::Tiny does not support a feature in line '$string'";
}
return {} if $string =~ /^{}(?:\s+\#.*)?\z/;
return [] if $string =~ /^\[\](?:\s+\#.*)?\z/;
if ( $string !~ /^[>|]/ ) {
if ( $string =~ /^(?:-(?:\s|$)|[\@\%\`])/
or $string =~ /:(?:\s|$)/ ) {
die \"Cpanel::CPAN::YAML::Tiny found illegal characters in plain scalar: '$string'";
}
$string =~ s/\s+#.*\z//;
return $string;
}
die \"Cpanel::CPAN::YAML::Tiny failed to find multi-line scalar content" unless @$lines;
$lines->[0] =~ /^(\s*)/;
$indent->[-1] = length("$1");
if ( defined $indent->[-2] and $indent->[-1] <= $indent->[-2] ) {
die \"Cpanel::CPAN::YAML::Tiny found bad indenting in line '$lines->[0]'";
}
my @multiline = ();
while (@$lines) {
$lines->[0] =~ /^(\s*)/;
last unless length($1) >= $indent->[-1];
push @multiline, substr( shift(@$lines), length($1) );
}
my $j = ( substr( $string, 0, 1 ) eq '>' ) ? ' ' : "\n";
my $t = ( substr( $string, 1, 1 ) eq '-' ) ? '' : "\n";
return join( $j, @multiline ) . $t;
}
sub _read_array {
my ( $self, $array, $indent, $lines ) = @_;
while (@$lines) {
if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
while ( @$lines and $lines->[0] !~ /^---/ ) {
shift @$lines;
}
return 1;
}
$lines->[0] =~ /^(\s*)/;
if ( length($1) < $indent->[-1] ) {
return 1;
}
elsif ( length($1) > $indent->[-1] ) {
die \"Cpanel::CPAN::YAML::Tiny found bad indenting in line '$lines->[0]'";
}
if ( $lines->[0] =~ /^(\s*\-\s+)[^\'\"]\S*\s*:(?:\s+|$)/ ) {
my $indent2 = length("$1");
$lines->[0] =~ s/-/ /;
push @$array, {};
$self->_read_hash( $array->[-1], [ @$indent, $indent2 ], $lines );
}
elsif ( $lines->[0] =~ /^\s*\-(\s*)(.+?)\s*\z/ ) {
shift @$lines;
push @$array, $self->_read_scalar( "$2", [ @$indent, undef ], $lines );
}
elsif ( $lines->[0] =~ /^\s*\-\s*\z/ ) {
shift @$lines;
unless (@$lines) {
push @$array, undef;
return 1;
}
if ( $lines->[0] =~ /^(\s*)\-/ ) {
my $indent2 = length("$1");
if ( $indent->[-1] == $indent2 ) {
push @$array, undef;
}
else {
push @$array, [];
$self->_read_array( $array->[-1], [ @$indent, $indent2 ], $lines );
}
}
elsif ( $lines->[0] =~ /^(\s*)\S/ ) {
push @$array, {};
$self->_read_hash( $array->[-1], [ @$indent, length("$1") ], $lines );
}
else {
die \"Cpanel::CPAN::YAML::Tiny failed to classify line '$lines->[0]'";
}
}
elsif ( defined $indent->[-2] and $indent->[-1] == $indent->[-2] ) {
return 1;
}
else {
die \"Cpanel::CPAN::YAML::Tiny failed to classify line '$lines->[0]'";
}
}
return 1;
}
sub _read_hash {
my ( $self, $hash, $indent, $lines ) = @_;
while (@$lines) {
if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
while ( @$lines and $lines->[0] !~ /^---/ ) {
shift @$lines;
}
return 1;
}
$lines->[0] =~ /^(\s*)/;
if ( length($1) < $indent->[-1] ) {
return 1;
}
elsif ( length($1) > $indent->[-1] ) {
die \"Cpanel::CPAN::YAML::Tiny found bad indenting in line '$lines->[0]'";
}
unless ( $lines->[0] =~ s/^\s*([^\'\" ][^\n]*?)\s*:(\s+(?:\#.*)?|$)// ) {
if ( $lines->[0] =~ /^\s*[?\'\"]/ ) {
die \"Cpanel::CPAN::YAML::Tiny does not support a feature in line '$lines->[0]'";
}
die \"Cpanel::CPAN::YAML::Tiny failed to classify line '$lines->[0]'";
}
my $key = $1;
if ( length $lines->[0] ) {
$hash->{$key} = $self->_read_scalar( shift(@$lines), [ @$indent, undef ], $lines );
}
else {
shift @$lines;
unless (@$lines) {
$hash->{$key} = undef;
return 1;
}
if ( $lines->[0] =~ /^(\s*)-/ ) {
$hash->{$key} = [];
$self->_read_array( $hash->{$key}, [ @$indent, length($1) ], $lines );
}
elsif ( $lines->[0] =~ /^(\s*)./ ) {
my $indent2 = length("$1");
if ( $indent->[-1] >= $indent2 ) {
$hash->{$key} = undef;
}
else {
$hash->{$key} = {};
$self->_read_hash( $hash->{$key}, [ @$indent, length($1) ], $lines );
}
}
}
}
return 1;
}
sub write {
my $self = shift;
my $file = shift or return $self->_error('No file name provided');
open( CFG, '>' . $file ) or return $self->_error("Failed to open file '$file' for writing: $!");
print CFG $self->write_string;
close CFG;
return 1;
}
sub write_string {
my $self = shift;
return '' unless @$self;
my $indent = 0;
my @lines = ();
foreach my $cursor (@$self) {
push @lines, '---';
if ( !defined $cursor ) {
}
elsif ( !ref $cursor ) {
$lines[-1] .= ' ' . $self->_write_scalar( $cursor, $indent );
}
elsif ( ref $cursor eq 'ARRAY' ) {
unless (@$cursor) {
$lines[-1] .= ' []';
next;
}
push @lines, $self->_write_array( $cursor, $indent, {} );
}
elsif ( ref $cursor eq 'HASH' ) {
unless (%$cursor) {
$lines[-1] .= ' {}';
next;
}
push @lines, $self->_write_hash( $cursor, $indent, {} );
}
else {
Carp::croak( "Cannot serialize " . ref($cursor) );
}
}
join '', map { "$_\n" } @lines;
}
sub _write_scalar {
my $string = $_[1];
return '~' unless defined $string;
return "''" unless length $string;
if ( $string =~ /[\x00-\x08\x0b-\x0d\x0e-\x1f\"\'\n]/ ) {
$string =~ s/\\/\\\\/g;
$string =~ s/"/\\"/g;
$string =~ s/\n/\\n/g;
$string =~ s/([\x00-\x1f])/\\$UNPRINTABLE[ord($1)]/g;
return qq|"$string"|;
}
if ( $string =~ /(?:^\W|\s)/ or $QUOTE{$string} ) {
return "'$string'";
}
return $string;
}
sub _write_array {
my ( $self, $array, $indent, $seen ) = @_;
if ( $seen->{ refaddr($array) }++ ) {
die "Cpanel::CPAN::YAML::Tiny does not support circular references";
}
my @lines = ();
foreach my $el (@$array) {
my $line = ( ' ' x $indent ) . '-';
my $type = ref $el;
if ( !$type ) {
$line .= ' ' . $self->_write_scalar( $el, $indent + 1 );
push @lines, $line;
}
elsif ( $type eq 'ARRAY' ) {
if (@$el) {
push @lines, $line;
push @lines, $self->_write_array( $el, $indent + 1, $seen );
}
else {
$line .= ' []';
push @lines, $line;
}
}
elsif ( $type eq 'HASH' ) {
if ( keys %$el ) {
push @lines, $line;
push @lines, $self->_write_hash( $el, $indent + 1, $seen );
}
else {
$line .= ' {}';
push @lines, $line;
}
}
else {
die "Cpanel::CPAN::YAML::Tiny does not support $type references";
}
}
@lines;
}
sub _write_hash {
my ( $self, $hash, $indent, $seen ) = @_;
if ( $seen->{ refaddr($hash) }++ ) {
die "Cpanel::CPAN::YAML::Tiny does not support circular references";
}
my @lines = ();
foreach my $name ( sort keys %$hash ) {
my $el = $hash->{$name};
my $line = ( ' ' x $indent ) . "$name:";
my $type = ref $el;
if ( !$type ) {
$line .= ' ' . $self->_write_scalar( $el, $indent + 1 );
push @lines, $line;
}
elsif ( $type eq 'ARRAY' ) {
if (@$el) {
push @lines, $line;
push @lines, $self->_write_array( $el, $indent + 1, $seen );
}
else {
$line .= ' []';
push @lines, $line;
}
}
elsif ( $type eq 'HASH' ) {
if ( keys %$el ) {
push @lines, $line;
push @lines, $self->_write_hash( $el, $indent + 1, $seen );
}
else {
$line .= ' {}';
push @lines, $line;
}
}
else {
die "Cpanel::CPAN::YAML::Tiny does not support $type references";
}
}
@lines;
}
sub _error {
$Cpanel::CPAN::YAML::Tiny::errstr = $_[1];
undef;
}
sub errstr {
$Cpanel::CPAN::YAML::Tiny::errstr;
}
sub Dump {
Cpanel::CPAN::YAML::Tiny->new(@_)->write_string;
}
sub Load {
my $self = Cpanel::CPAN::YAML::Tiny->read_string(@_);
unless ($self) {
Carp::croak("Failed to load YAML document from string");
}
if (wantarray) {
return @$self;
}
else {
return $self->[-1];
}
}
BEGIN {
*freeze = *Dump;
*thaw = *Load;
}
sub DumpFile {
my $file = shift;
Cpanel::CPAN::YAML::Tiny->new(@_)->write($file);
}
sub LoadFile {
my $self = Cpanel::CPAN::YAML::Tiny->read( $_[0] );
unless ($self) {
Carp::confess( "Failed to load YAML document from '" . ( $_[0] || '' ) . "'" );
}
if (wantarray) {
return @$self;
}
else {
return $self->[-1];
}
}
BEGIN {
local $@;
eval { require Scalar::Util; };
if ( $@ or $Scalar::Util::VERSION < 1.18 ) {
eval <<'END_PERL' if $@;
sub refaddr {
my $pkg = ref($_[0]) or return undef;
if ( !! UNIVERSAL::can($_[0], 'can') ) {
bless $_[0], 'Scalar::Util::Fake';
} else {
$pkg = undef;
}
"$_[0]" =~ /0x(\w+)/;
my $i = do { local $^W; hex $1 };
bless $_[0], $pkg if defined $pkg;
$i;
}
END_PERL
}
else {
*refaddr = *Scalar::Util::refaddr;
}
}
1;
} # --- END Cpanel/CPAN/YAML/Tiny.pm
{ # --- BEGIN Cpanel/CachedDataStore.pm
package Cpanel::CachedDataStore;
use strict;
use Try::Tiny;
use IO::Handle ();
# use Cpanel::AdminBin::Serializer ();
# use Cpanel::CPAN::YAML::Syck ();
# use Cpanel::Fcntl ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::SafeFile ();
# use Cpanel::Logger ();
# use Cpanel::Umask ();
our $LOCK = 1; #const
my $logger = Cpanel::Logger->new();
my %DATASTORE_CACHE;
my $now;
sub store_ref {
return savedatastore( $_[0], { 'data' => $_[1], ( ref $_[2] ? %{ $_[2] } : () ) } );
}
sub fetch_ref {
my ( $file, $is_array ) = @_;
my $ref = $is_array ? [] : {};
if ( load_ref( $file, $ref ) ) {
return $ref;
}
else {
return $is_array ? [] : {};
}
}
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 ) = @_;
my $use_cache_file = !defined $opts->{'cache_file'} || $opts->{'cache_file'};
if ( !exists $opts->{'data'} || !defined $opts->{'data'} ) {
$logger->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'};
$DATASTORE_CACHE{$file}->{'cache'} = $opts->{'data'} if $use_memory_cache;
my $original_file = $file;
$file =~ s/\.yaml$//g;
my $yaml = YAML::Syck::Dump( $opts->{'data'} );
my $custom_perms = exists $opts->{'mode'} ? $opts->{'mode'} & 00777 : undef;
if ( $opts->{'fh'} ) {
die "Filehandle already closed!" if !defined fileno $opts->{'fh'};
}
else {
my $perms = defined $custom_perms ? $custom_perms : 0644; #0644 is the default
my $umask = Cpanel::Umask->new(0);
sysopen( $opts->{'fh'}, $original_file, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_TRUNC O_CREAT )), $perms ) or do {
$logger->warn("Failed to write $original_file: $!");
return;
};
}
if ( defined $custom_perms ) {
chmod( $custom_perms, $opts->{'fh'} );
}
seek( $opts->{'fh'}, 0, 0 );
print { $opts->{'fh'} } $yaml;
truncate( $opts->{'fh'}, tell( $opts->{'fh'} ) );
my $data_fh_perms = ( stat( $opts->{'fh'} ) )[2] & 00777;
if ($use_cache_file) {
_write_cache_file( "$file.cache", $opts->{'data'}, $data_fh_perms );
}
my $ok;
if ( $opts->{'fh'} ) {
if ( $opts->{'safefile_lock'} ) {
$ok = Cpanel::SafeFile::safeclose( $opts->{'fh'}, $opts->{'safefile_lock'} );
}
else {
$ok = close( $opts->{'fh'} );
}
}
else {
die "Should never get here!";
}
return $ok;
}
sub loaddatastore {
my ( $datastore_file, $lock_required, $copy_data_ref, $opts ) = @_;
my ( $loaded_data, $filesys_mtime );
if ( !$datastore_file ) {
$logger->warn('No datastore file specified');
return;
}
my $use_memory_cache = !defined $opts->{'enable_memory_cache'} || $opts->{'enable_memory_cache'};
if ( !$now ) { $now = time; }
my $datastore_cache_file = $datastore_file;
$datastore_cache_file = $datastore_cache_file =~ s/\.yaml$/.cache/g ? $datastore_cache_file : "$datastore_cache_file.cache";
if ( !$lock_required ) {
if ( !( $filesys_mtime = ( stat($datastore_file) )[9] ) ) {
return;
}
if ( $use_memory_cache && $DATASTORE_CACHE{$datastore_file}->{'mtime'} && $filesys_mtime <= $DATASTORE_CACHE{$datastore_file}->{'mtime'} ) {
if ($copy_data_ref) {
_copy_ref_data( $DATASTORE_CACHE{$datastore_file}->{'cache'}, $copy_data_ref, $datastore_file );
}
return bless { 'data' => $DATASTORE_CACHE{$datastore_file}->{'cache'} };
}
my $filesys_cache_mtime;
if ( open( my $datastore_cache_fh, '<', $datastore_cache_file ) ) { #ok if the file does not exist
$filesys_cache_mtime = ( stat($datastore_cache_fh) )[9]; # stat the file handle to prevent a race condition
if ( $filesys_mtime && $filesys_cache_mtime >= $filesys_mtime && $filesys_cache_mtime < $now ) {
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);
};
}
close($datastore_cache_fh);
if ( $copy_data_ref && $loaded_data ) {
_copy_ref_data( $loaded_data, $copy_data_ref, $datastore_file );
}
}
if ($loaded_data) {
@{ $DATASTORE_CACHE{$datastore_file} }{ 'mtime', 'cache' } = ( $filesys_cache_mtime, $loaded_data ) if $use_memory_cache;
return bless { 'data' => $loaded_data };
}
}
my $datastore_not_writable;
my $data_fh = IO::Handle->new();
my $custom_perms = exists $opts->{'mode'} ? $opts->{'mode'} & 00777 : undef;
my $perms = defined $custom_perms ? $custom_perms : 0644; #0644 is the default
my $orig_umask;
if ( defined $perms ) {
$orig_umask = umask();
umask( $perms ^ 07777 );
}
if ( !-e $datastore_file ) {
if ( !sysopen( $data_fh, $datastore_file, Cpanel::Fcntl::or_flags(qw( O_WRONLY O_APPEND O_CREAT )), $perms ) ) {
}
else {
close($data_fh);
}
}
my $rlock;
my $lock_failed;
if ( $opts->{donotlock} ) {
open( $data_fh, '<', $datastore_file ) or do {
$logger->warn("Unable open $datastore_file for reading: $!");
};
$datastore_not_writable = 1;
}
else {
my $open_mode = -w $datastore_file ? '+<' : '<';
$rlock = Cpanel::SafeFile::safeopen( $data_fh, $open_mode, $datastore_file );
$lock_failed = !$rlock || 1 == $rlock;
if ($lock_failed) {
$logger->warn("Unable get a write lock on datastore $datastore_file: $!") if $lock_required;
$datastore_not_writable = 1;
}
}
umask($orig_umask) if defined $orig_umask;
my $can_chmod_a_fh = $] >= 5.008008;
my $data_fh_perms = ( stat( $data_fh && defined fileno($data_fh) ? $data_fh : $datastore_file ) )[2] || 0600;
if ( defined $custom_perms && ( $data_fh_perms & 00777 ) != $custom_perms ) {
chmod( $custom_perms, $can_chmod_a_fh ? $data_fh : $datastore_file );
$data_fh_perms = ( stat( $data_fh ? $data_fh : $datastore_file ) )[2] || 0600;
}
if ( $data_fh && fileno $data_fh ) {
my $yaml_sr = \do { local $/; readline($data_fh); };
if ( length $$yaml_sr ) {
eval {
local $SIG{'__WARN__'};
local $SIG{'__DIE__'};
$loaded_data = ( YAML::Syck::Load($$yaml_sr) )[0];
$loaded_data = undef unless ref $loaded_data;
if ( $copy_data_ref && $loaded_data ) {
_copy_ref_data( $loaded_data, $copy_data_ref, $datastore_file );
}
};
}
seek( $data_fh, 0, 0 );
}
if ( !$lock_required || $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 && -w $datastore_cache_file && ( stat($datastore_cache_file_dir) )[4] == $> ) {
_write_cache_file( $datastore_cache_file, $loaded_data, $data_fh_perms );
if ($use_memory_cache) {
$DATASTORE_CACHE{$datastore_file}->{'mtime'} = $filesys_mtime;
$DATASTORE_CACHE{$datastore_file}->{'cache'} = $loaded_data;
}
}
if ( $opts->{'donotlock'} ) {
close($data_fh);
}
else {
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.
}
return bless { 'data' => $loaded_data, 'file' => $datastore_file, ( $datastore_not_writable ? () : ( 'safefile_lock' => $rlock, 'fh' => $data_fh ) ) };
}
sub _write_cache_file {
my ( $path, $data, $perms ) = @_;
try {
Cpanel::FileUtils::Write::overwrite(
$path,
Cpanel::AdminBin::Serializer::Dump($data),
$perms,
);
}
catch {
my $str = Cpanel::Exception::get_string($_);
$logger->warn("Failed to write the cache file “$path” ($_); this file will not be saved.");
};
return;
}
sub file {
return $_[0]->{'file'};
}
sub fh {
return $_[0]->{'fh'};
}
sub clear_data {
$_[0]->{'data'} = undef;
return;
}
sub data {
if ( defined $_[1] ) {
$_[0]->{'data'} = $_[1];
return 1;
}
return $_[0]->{'data'};
}
sub save {
savedatastore( $_[0]->{'file'}, $_[0] );
}
sub abort {
unlockdatastore( $_[0] );
}
sub unlockdatastore {
my ($datastore) = @_;
return 0 if !$datastore->{'fh'} || !$datastore->{'safefile_lock'};
Cpanel::SafeFile::safeclose( $datastore->{'fh'}, $datastore->{'safefile_lock'} );
}
sub _copy_ref_data {
my ( $src_ref, $dest_ref, $file ) = @_;
if ( ref $src_ref eq 'HASH' ) {
%{$dest_ref} = %{$src_ref};
}
elsif ( ref $src_ref eq 'ARRAY' ) {
@{$dest_ref} = @{$src_ref};
}
else {
if ($file) {
$logger->warn("YAML in '$file' is not a hash or array reference");
}
else {
$logger->warn('Asked to duplicate a reference that is not a hash or array');
}
$dest_ref = $src_ref;
}
}
sub get_cache {
\%DATASTORE_CACHE;
}
sub clear_cache {
%DATASTORE_CACHE = ();
$now = undef;
}
sub clear_one_cache {
my ($file) = @_;
delete $DATASTORE_CACHE{$file};
}
sub verify {
my ($file) = @_;
my $data = YAML::Syck::LoadFile($file);
return ref $data ? 1 : 0;
}
1;
} # --- END Cpanel/CachedDataStore.pm
{ # --- BEGIN Cpanel/Crypt/GPG/VendorKeys.pm
package Cpanel::Crypt::GPG::VendorKeys;
use strict;
# use Cpanel::Crypt::GPG ();
# use Cpanel::Logger ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeRun::Object ();
use File::Basename ();
use IPC::Open3 ();
our $VERSION = 1;
my $yaml_fallback = undef;
eval { require YAML::Syck; require JSON::XS; };
if ($@) {
require Cpanel::CPAN::YAML::Tiny;
$yaml_fallback = 1;
}
else {
require Cpanel::CachedDataStore;
}
sub _get_config_file {
return '/var/cpanel/gpg/vendorkeys.yaml';
}
sub _get_vendor_keys {
if ($yaml_fallback) {
my $yaml = {};
eval { $yaml = Cpanel::CPAN::YAML::Tiny::LoadFile( _get_config_file() ) };
return $yaml;
}
else {
return Cpanel::CachedDataStore::fetch_ref( _get_config_file() );
}
}
sub _save_vendor_keys {
my ($vk_ref) = @_;
my $keydir = File::Basename::dirname( _get_config_file() );
if ( !-d $keydir ) {
Cpanel::SafeDir::MK::safemkdir( $keydir, 0700 );
}
if ($yaml_fallback) {
if ( eval { Cpanel::CPAN::YAML::Tiny::DumpFile( _get_config_file(), $vk_ref ) } ) {
chmod 0600, _get_config_file();
return 1;
}
else {
return 0;
}
}
else {
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->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 $wget_data = eval { _wget_url( url => $url, noverify => $args{noverify} ) };
if ( !defined($wget_data) ) {
$@ = ${$@} if ( defined $@ && ref $@ eq 'SCALAR' );
return wantarray ? ( undef, $@ ) : undef;
}
my ( $success, $msg ) = set_keys(
vendor => $args{vendor},
category => $args{category},
url => $args{url},
keys => $wget_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 ( $vendor =~ /^__/ ) {
next;
}
foreach my $type ( keys %{ $keys->{$vendor} } ) {
return ( $vendor, $type ) if grep { $keyid eq $_ } keys %{ $keys->{$vendor}->{$type}->{keychain} };
}
}
return ( 'UNKNOWN', 'UNKNOWN' );
}
sub _find_wget_bin {
for my $path (qw ( /usr/bin/wget )) {
if ( -x $path ) {
return $path;
}
}
return undef;
}
sub _wget_timeout {
return 60;
}
sub _wget_url {
my (%args) = @_;
my @cmd_args = (
'-O', '-',
( $args{noverify} ? '--no-check-certificate' : () ),
$args{url},
);
my $wget_bin = _find_wget_bin();
if ( !$wget_bin ) {
die \"Failed to find 'wget' binary.";
}
my $run = Cpanel::SafeRun::Object->new(
program => $wget_bin,
args => \@cmd_args,
timeout => _wget_timeout(),
);
if ( !$run ) {
die \"Failed to invoke 'wget' binary.";
}
my $rc = $run->CHILD_ERROR() >> 8;
if ( $rc != 0 ) {
my $stderr = "Error encountered while running 'wget' command.\n" . $run->stderr();
$stderr =~ s/\n+\z//s;
die \$stderr;
}
my $stdout = $run->stdout();
if ( !$stdout ) {
die \"Response returned by 'wget' was empty.";
}
return $stdout;
}
sub download_public_keys {
my %opts = @_;
$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 { !/^__/ } 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/SafeRun/Full.pm
package Cpanel::SafeRun::Full;
use strict;
use Cwd ();
use IO::Handle ();
use IO::Select ();
use IPC::Open3 ();
# 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::cleanenv( %{$env_hr} );
}
sub run {
my %OPTS = @_;
my $output = _get_default_output_hash();
my ( $user, $homedir ) = ( Cpanel::PwCache::getpwuid($>) )[ 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 $basepath;
if ( $OPTS{'chdir'} ) {
if ( !-d $OPTS{'chdir'} ) {
$output->{'message'} = 'chdir directory is not a directory';
return $output;
}
$basepath = Cwd::fastcwd();
chdir $OPTS{'chdir'} or do {
$output->{'message'} = "chdir into $OPTS{'chdir'} failed";
$output->{'stderr'} = $!;
return $output;
};
}
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 $stdout = IO::Handle->new();
my $stderr = IO::Handle->new();
my $stdin = IO::Handle->new();
if ( !$OPTS{'stdin'} ) {
open $stdin, '<', '/dev/null' or die "Unable to open /dev/null: $!";
}
my $pid = IPC::Open3::open3( $stdin, $stdout, $stderr, $OPTS{'program'}, @{ $OPTS{'args'} } );
if ( !$pid ) {
$output->{'stderr'} = $!;
close $stderr;
close $stdin;
close $stdout;
$output->{'message'} = "Failed to execute $OPTS{'program'}";
return $output;
}
if ( length $OPTS{'stdin'} ) {
local $SIG{'PIPE'} = 'IGNORE';
if ( ref $OPTS{'stdin'} eq 'SCALAR' ) {
print {$stdin} ${ $OPTS{'stdin'} };
}
else {
print {$stdin} $OPTS{'stdin'};
}
}
close $stdin;
my $read_set = IO::Select->new();
$stdout->blocking(0);
$stderr->blocking(0);
$read_set->add($stdout);
$read_set->add($stderr);
my $buffer;
my $finished = 0;
while ( my @ready = $read_set->can_read( defined $OPTS{'timeout'} ? $OPTS{'timeout'} : () ) ) {
foreach my $fh (@ready) {
sysread( $fh, $buffer, 32768 );
$output->{ ( $fh == $stdout ) ? 'stdout' : 'stderr' } .= $buffer;
if ( !defined $buffer || $buffer eq '' ) {
$read_set->remove($fh);
if ( !$read_set->handles() ) { $finished = 1; }
}
}
}
close($stdout);
close($stderr);
if ( !$finished ) {
kill 'TERM', $pid;
sleep(1); # Give the process a chance to die 'nicely'
kill 'KILL', $pid;
waitpid( $pid, 0 );
$output->{'timeout'} = $OPTS{'timeout'};
_augment_with_process_status($output);
return $output;
}
waitpid( $pid, 0 );
_augment_with_process_status($output);
if ( $OPTS{'chdir'} ) {
chdir $basepath;
}
$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 Cpanel::Logger ();
# use Cpanel::CachedDataStore ();
# use Cpanel::SafeRun::Full ();
# use Cpanel::JSON ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::AdminBin ();
# use Cpanel::Debug ();
my $logger = Cpanel::Logger->new();
our $HOOKS_DATASTORE = '/var/cpanel/hooks.yaml';
our $hooks_list = {};
my $cpconf;
my $debughooks;
my $init = 0;
sub init_hooks {
$debughooks = Cpanel::Debug::debug_hooks_value();
$hooks_list = Cpanel::CachedDataStore::load_ref($HOOKS_DATASTORE) || {};
$init = 1;
}
sub hook {
my ( $context, $data ) = @_;
init_hooks if !$init;
my @ran_hooks;
my $result = 1;
my @msgs;
local $SIG{'__DIE__'};
if ( ref $data eq "HASH" ) {
delete @{$data}{ grep { tr/\r\n\0// } keys %$data };
}
foreach my $hook ( _get_hooks_list($context) ) {
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 ($@) {
push @msgs, $@;
if ( $@ =~ /BAILOUT/ ) {
$logger->warn( "An exception was thrown in the hook " . $hook->{'hook'} . " for " . $context->{'category'} . '::' . $context->{'event'} );
if ( $hook->{'blocking'} ) {
exec_rollback( $hook, $context, $data, \@ran_hooks );
return 0, \@msgs;
}
next;
}
}
if ( $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 );
$logger->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;
}
}
sub _get_hooks_list {
my ($context) = @_;
return () if ref $context ne 'HASH';
my ( $category, $event ) = @{$context}{qw( category event )};
return () unless defined $event && defined $category;
my $contextual_hook_list = $hooks_list->{$category} && $hooks_list->{$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) {
$logger->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 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 {
$logger->warn( 'invalid hook type called for ' . $context->{'category'} . "::" . $context->{'event'} );
}
return $result, $msg;
}
sub debug {
my ( $msg, $point, $hook, $context, $data, $result ) = @_;
return if !$debughooks;
$logger->info('---debug_hooks---');
$logger->info( ' msg: ' . $msg );
$logger->info( ' context: ' . $context->{'category'} . '::' . $context->{'event'} );
$logger->info( ' stage: ' . $context->{'stage'} );
$logger->info( ' result: ' . $result ) if defined $result;
$logger->info( ' point: ' . $point ) if defined $point;
if ( defined $hook && ref $hook eq 'HASH' ) {
$logger->info( ' id: ' . $hook->{'id'} ) if exists $hook->{'id'};
$logger->info( ' hook: ' . $hook->{'hook'} ) if exists $hook->{'hook'};
$logger->info( ' escalateprivs: ' . $hook->{'escalateprivs'} ) if exists $hook->{'escalateprivs'};
$logger->info( ' weight: ' . $hook->{'weight'} ) if exists $hook->{'weight'};
$logger->info( ' rollback: ' . $hook->{'rollback'} ) if exists $hook->{'rollback'};
$logger->info( ' check: ' . $hook->{'check'} ) if exists $hook->{'check'};
}
if ( $debughooks > 1 && defined $data ) {
$logger->info( ' data: ' . Cpanel::JSON::Dump($data) );
}
}
sub set_debug {
$debughooks = $_[0];
}
sub exec_script {
my ( $point, $hook, $context, $data ) = @_;
my ( $script, @script_args );
if ( $point eq 'main' ) {
( $script, @script_args ) = split( /\s/, $hook->{'hook'} );
}
elsif ( $point eq 'check' ) {
( $script, @script_args ) = split( /\s/, $hook->{'check'} );
}
elsif ( $point eq 'rollback' ) {
( $script, @script_args ) = split( /\s/, $hook->{'rollback'} );
}
else {
$logger->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 ( $hook->{'escalateprivs'} && $< != 0 ) {
if ( $context->{'escalateprivs'} ) {
$output = Cpanel::AdminBin::adminstor( 'hooks2', $context->{'category'} . "::" . $context->{'event'}, $input );
$output = Cpanel::JSON::Load($output);
}
else {
$msg = 'A script hook attempted to escalate privileges when escalation was not permitted in ' . $context->{'category'} . '::' . $context->{'event'} . ' with the script ' . $script;
$logger->info($msg);
return 0, $msg;
}
}
else {
$output = Cpanel::SafeRun::Full::run(
'program' => $script,
'stdin' => Cpanel::JSON::Dump($input),
'args' => \@script_args,
);
}
if ( exists $output->{'message'} && $output->{'message'} !~ /Executed / ) {
$logger->warn( $output->{'message'} );
}
if ($debughooks) {
if ( $output->{'stdout'} ne '' ) {
$logger->info( 'STDOUT output from hook: ' . $hook->{'hook'} );
$logger->info( $output->{'stdout'} );
$logger->info('End STDOUT from hook');
}
else {
$logger->info( 'HOOK INFO: hook ' . $hook->{'hook'} . ' did not output any data' );
}
}
if ( exists $output->{'stderr'} && $output->{'stderr'} ne '' ) {
$logger->info( 'STDERR output from hook: ' . $hook->{'hook'} );
$logger->info( $output->{'stderr'} );
$logger->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' ) {
$logger->info('Script hook returned an invalid response: ');
$logger->info( ' script: ' . $hook->{'hook'} );
$logger->info( ' response: ' . $output->{'stdout'} );
$logger->info(' -- End Garbage output -- ');
}
return $result, $msg;
}
sub exec_module {
my ( $point, $hook, $context, $data ) = @_;
my ( $module, $subroutine );
if ( $point eq 'main' ) {
( $module, $subroutine ) = $hook->{'hook'} =~ /(^[a-zA-Z0-9\:_]+)\:\:([a-zA-Z0-9_]+)$/;
}
elsif ( $point eq 'check' ) {
( $module, $subroutine ) = $hook->{'check'} =~ /(^[a-zA-Z0-9\:_]+)\:\:([a-zA-Z0-9_]+)$/;
}
elsif ( $point eq 'rollback' ) {
( $module, $subroutine ) = $hook->{'rollback'} =~ /(^[a-zA-Z0-9\:_]+)\:\:([a-zA-Z0-9_]+)$/;
}
else {
$logger->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; ";
if ($@) {
$logger->warn($@);
return 1;
}
my $return = 1;
my $msg = undef;
eval {
if ( my $cr = $module->can($subroutine) ) {
( $return, $msg ) = $cr->( $context, $data );
}
else {
$logger->warn("Could not find $subroutine in module $module");
}
};
if ( $@ =~ /BAILOUT/ && $point ne 'rollback' ) {
die $@;
}
$logger->warn($@) if $@;
return $return, $msg;
}
sub hook_halted_msg {
my ($hook_msgs) = @_;
if ($hook_msgs) {
if ( ref($hook_msgs) eq 'ARRAY' && @{$hook_msgs} ) {
return "A hook halted this operation: " . join( "\n", @{$hook_msgs} );
}
elsif ( !ref($hook_msgs) && $hook_msgs ) {
return "A hook halted this operation: $hook_msgs";
}
}
return "A hook halted this operation.";
}
1;
} # --- END Cpanel/Hooks.pm
{ # --- BEGIN Cpanel/Crypt/GPG/VendorKeys/TimestampCache.pm
package Cpanel::Crypt::GPG::VendorKeys::TimestampCache;
use strict;
my $yaml_fallback = undef;
eval { require YAML::Syck; require JSON::XS; };
if ($@) {
require Cpanel::CPAN::YAML::Tiny;
$yaml_fallback = 1;
}
else {
require Cpanel::CachedDataStore;
}
sub _cache_file {
return '/var/cpanel/gpg/timestamp.cache';
}
sub new {
my ( $obj, %OPTS ) = @_;
my $self = {};
bless $self, $obj;
$self->{'cache'} = _load_cache();
return $self;
}
sub _load_cache {
if ($yaml_fallback) {
my $yaml = {};
eval { $yaml = Cpanel::CPAN::YAML::Tiny::LoadFile( _cache_file() ) };
return $yaml;
}
else {
return Cpanel::CachedDataStore::fetch_ref( _cache_file() );
}
}
sub _save_cache {
my ($cache_data) = @_;
if ($yaml_fallback) {
if ( eval { Cpanel::CPAN::YAML::Tiny::DumpFile( _get_config_file(), $cache_data ) } ) {
chmod 0600, _cache_file();
return 1;
}
else {
return 0;
}
}
else {
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 ();
# 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->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/UrlTools.pm
package Cpanel::UrlTools;
use strict;
# use Cpanel::Logger ();
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 {
my $logger = Cpanel::Logger->new();
$logger->warn( 'Invalid URL: ' . $url );
}
}
return wantarray ? @HOSTS : \@HOSTS;
}
sub extract_host_uri {
my ($url) = @_;
if ( $url =~ m/https?\:\/\/([^\/]+)(\/.*)/ ) {
return ( $1, $2 );
}
else {
my $logger = Cpanel::Logger->new();
$logger->warn( 'Invalid URL: ' . $url );
}
return;
}
sub build_http_get {
my ( $destination, %query ) = @_;
eval 'require Carp' if !$INC{'Carp.pm'};
Cpanel::Logger->new()->warn( "Call to deprecated function " . __PACKAGE__ . "::build_http_get.\n" . Carp::longmess() );
eval 'require Cpanel::CPAN::URI::Escape' if !$INC{'Cpanel/CPAN/URI/Escape.pm'};
my @query_parts;
for my $query_key ( keys %query ) {
my $query_value = $query{$query_key};
$query_key = Cpanel::CPAN::URI::Escape::fast_uri_escape($query_key);
my $new_query_part;
if ( ref $query_value eq 'ARRAY' ) {
$new_query_part = join( '&', map { $query_key . '=' . Cpanel::CPAN::URI::Escape::fast_uri_escape($_) } @{$query_value} );
}
else {
$new_query_part = $query_key . '=' . Cpanel::CPAN::URI::Escape::fast_uri_escape($query_value);
}
push @query_parts, $new_query_part;
}
my $security_token_prefix =
( $destination =~ m{\A/} )
? $ENV{'cp_security_token'}
: q{};
return $security_token_prefix . $destination . '?' . join( '&', @query_parts );
}
1;
} # --- END Cpanel/UrlTools.pm
{ # --- BEGIN Cpanel/Alarm.pm
package Cpanel::Alarm;
use strict;
# 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 { shift->{'local_alarm_length'} }
sub set {
my $self = shift or die;
$self->{'local_alarm_length'} = $_[0];
$self->{'local_alarm_start'} = time();
alarm( $_[0] ); # 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;
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, ( $p_options{'ipv6'} ? &Socket::AF_INET6 : &Socket::AF_INET ) );
}
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'};
$address = Socket::inet_ntop( $r->{'family'}, ( Socket::unpack_sockaddr_in6( $r->{'addr'} ) )[1] );
}
elsif ( $r->{'family'} == &Socket::AF_INET ) {
next if $p_options{'ipv6'};
$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/HttpTimer.pm
package Cpanel::HttpTimer;
our $VERSION = 1.2;
our $MAX_SIZE = ( 4096 * 4096 );
our $TIMEOUT = 30;
use strict;
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'} = $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 {
my (%REQ) = @_;
my $url = $REQ{'url'};
my ( $host, $uri ) = Cpanel::UrlTools::extract_host_uri($url);
my $self = {};
bless $self;
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 ( $REQ{'filename'} eq '' ) { $filename = Cpanel::UrlTools::urltofile($uri); }
else { $filename = $REQ{'filename'}; }
open( $storef_fh, '>', $filename );
}
my $bytes = 0;
my $start_time = Cpanel::TimeHiRes::time();
my $buffer = '';
eval {
local $SIG{'__DIE__'} = 'DEFAULT';
local $SIG{'PIPE'} = $SIG{'ALRM'} = sub {
print STDERR '..Timeout on receive..' if !$REQ{'quiet'};
die;
};
alarm(20); #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(20);
}
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 =~ m/SSL-enabled/ || $headers =~ m/location: https:\/\//i ) {
}
elsif ( $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);
}
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/PipeHandler.pm
package Cpanel::PipeHandler;
# use Cpanel::Carp ();
my @FDLIST;
my $hasPIPE = 0;
my $lastpipe = 0;
my $pipetime = 0;
sub register_fds {
push( @FDLIST, @_ );
}
sub pipeBGMgr {
$hasPIPE++;
$pipetime = time();
if ( $hasPIPE == 1 ) {
$0 .= " - running in background (disconnected)";
foreach my $fd (@FDLIST) {
if ( fileno($fd) != 1 ) {
close($fd);
}
}
print STDERR "$0 [$$]: " . Cpanel::Carp::safe_longmess('SIGPIPE received, process going into background');
open( STDOUT, ">", "/dev/null" );
$lastpipe = time();
}
elsif ( $pipetime > $lastpipe + 1 ) {
print STDERR "$0 [$$]: " . Cpanel::Carp::safe_longmess('Fatal SIGPIPE received');
die "$$";
}
return;
}
sub pipeMgr {
$hasPIPE++;
if ( $hasPIPE > 2 ) { die "$$"; }
print STDERR "$0 [$$]: " . Cpanel::Carp::safe_longmess('SIGPIPE received');
if ( $hasPIPE > 1 ) { die "$$"; }
return;
}
1;
} # --- END Cpanel/PipeHandler.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/HttpRequest.pm
package Cpanel::HttpRequest;
use strict;
# use Cpanel::ArrayFunc ();
# use Cpanel::Crypt::GPG::Settings ();
# use Cpanel::Crypt::GPG::VendorKeys::Verify ();
# use Cpanel::Encoder::URI ();
# use Cpanel::FileUtils::Copy ();
# use Cpanel::Hostname ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::MirrorSearch ();
# use Cpanel::PipeHandler ();
# use Cpanel::Rand ();
# use Cpanel::SocketIP ();
# use Cpanel::URL ();
# use Cpanel::UrlTools ();
use HTTP::Tiny ();
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;
our %COMPRESSION = ( 'extension' => 'xz', 'compress' => 'xz', 'decompress' => 'unxz' );
my $logger;
my $buffer_size = 131070;
my $has_cpanel_dnsRoots = 0;
sub new {
my ( $obj, %OPTS ) = @_;
my $self = {};
bless $self;
$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->{'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_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'} || 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;
Cpanel::LoadModule::load_perl_module('Cpanel::Sync::Common');
return $self;
}
sub _output {
my ( $self, @args ) = @_;
return if $self->{'hideOutput'};
return print @args;
}
sub request {
my ( $self, %OPTS ) = @_;
$OPTS{'uncompress'} = 1 if ( length $OPTS{'uncompress_bzip2'} && $OPTS{'url'} =~ m{\.bz2$} );
my $check_signature = defined $OPTS{'signed'} ? $OPTS{'signed'} : $self->{'signed'};
my $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_vendor = defined $OPTS{'vendor'} ? $OPTS{'vendor'} : $self->{'vendor'};
my $gpg_category = defined $OPTS{'categories'} ? $OPTS{'categories'} : $self->{'categories'};
Cpanel::LoadModule::load_perl_module('Cpanel::Crypt::GPG::VendorKeys::Verify');
my ( $gpg, $gpg_msg ) = Cpanel::Crypt::GPG::VendorKeys::Verify->new(
vendor => $gpg_vendor,
categories => $gpg_category,
);
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 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::getranddata(8) . ".$compressed_ext";
my $tmp_file_b = $basename . '_' . Cpanel::Rand::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 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' ) {
Cpanel::Sync::Common::unbzip2($tmp_file_b);
$tmp_file_b =~ s/\.bz2$//;
}
elsif ( $compressed_ext eq 'xz' ) {
system( 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::getranddata(8);
$OPTS{'url'} = $file_url;
$OPTS{'destfile'} = $tmp_file;
my $req = $self->_request_file(%OPTS);
if ( !$req ) {
$self->_die( "Failed to download 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}" );
}
sub _fetcher {
my ( $self, $timeout, %params ) = @_;
my $fetcher = $self->{fetcher};
return HTTP::Tiny->new( timeout => $timeout, %params ) if !$fetcher || $fetcher->{timeout} != $timeout;
return $fetcher;
}
sub _request_file {
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 = ( 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 && !$Cpanel::Sync::Common::hasbzip2 && $uncompress_ext eq 'bz2' ) {
$destfile .= '.bz2';
}
my $complete = 0;
my $keepalive = 1;
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) {
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 ($data) = @_;
my $status = $compress_raw_bzip2_obj->bzinflate( $data, 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 ($data) = @_;
my $status = $compress_raw_lzma_obj->code( $data, 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 {
my ($data) = @_;
print {$fh} $data;
};
}
$reqargs{'data_callback'} = $callback;
}
else {
$reqargs{'data_callback'} = sub {
my ($data) = @_;
$page .= $data;
};
}
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 $@;
$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': $!";
system( '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();
$self->{'connected'} = 0;
}
sub make_http_query_string {
my ($query) = @_;
return $_[0] unless ref $_[0]; # If query is a string, return it.
my ( $querystr, $delim, $enckey ) = ( '', '' );
if ( ref $query eq 'ARRAY' ) {
if ( @{$query} & 1 ) {
$logger ||= Cpanel::Logger->new();
$logger->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 ] );
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);
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 {
$logger ||= Cpanel::Logger->new();
$logger->invalid('Unrecognized type for query parameter.');
return;
}
return $querystr;
}
sub http_post_req {
my ( $self, $args_hr ) = @_;
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;
}
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();
}
sub _getAddressList {
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 = $Cpanel::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( \@trueaddresses );
if ( scalar @trueaddresses == 0 ) {
$logger ||= Cpanel::Logger->new();
$logger->warn("$host could not be resolved to an ip adddress, please check your /etc/resolv.conf");
return wantarray ? () : [];
}
elsif ( !$self->{'speed_test_enabled'} ) {
@trueaddresses = ( $trueaddresses[0] );
}
elsif ( scalar @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)..." );
my @goodurls = Cpanel::MirrorSearch::findfastest(
'days' => ( 2.0 / 24 ),
'key' => $host,
'count' => 10,
'urls' => [ Cpanel::UrlTools::buildurlfromuri( \@trueaddresses, $self->{'speed_test_file'} ) ],
'quiet' => $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'} } } );
}
Cpanel::MirrorSearch::remove_mirror( 'key' => $self->{'connectedHostname'}, 'addr' => $addr );
if ( !$self->{'host'} || !@{ $self->{'hostIps'}{ $self->{'host'} } } && $self->{'use_dns_cache'} ) {
$self->_destroy_ip_cache();
}
}
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
}
}
sub _destroy_ip_cache {
my $self = shift;
my $cache_key = shift || $self->{'connectedHostname'};
my $homedir = $Cpanel::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
}
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 {
my $self = shift;
$self->{'last_status'} = undef;
my %OPTS = @_;
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;
open( $self->{'destfile_fh'}, '>', $destfile ) if length $destfile;
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 ( !$local_logger ) {
$logger ||= Cpanel::Logger->new();
$local_logger = $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.' );
}
1;
} # --- END Cpanel/HttpRequest.pm
{ # --- BEGIN Cpanel/RPM/Versions/File/YAML.pm
package Cpanel::RPM::Versions::File::YAML;
use strict;
my $use_syck = 1;
eval {
require YAML::Syck;
$YAML::Syck::LoadBlessed = 0;
$YAML::Syck::SortKeys = 1;
};
if ($@) {
require Cpanel::CPAN::YAML::Tiny;
$use_syck = 0;
}
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'},
use_syck => $use_syck,
};
return $self;
}
sub _use_syck {
my ($self) = @_;
return $self->{'use_syck'};
}
sub _loadfile {
my ($self) = @_;
my $file = $self->yaml_file();
if ( !-e $file || -z _ ) {
$self->{'data'} = {};
return 0;
}
eval {
if ( $self->_use_syck ) {
$self->{'data'} = YAML::Syck::LoadFile($file);
}
else {
$self->{'data'} = Cpanel::CPAN::YAML::Tiny::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 {
my %all = map { $_ => $self->{'data'}->{$section}->{$_} } keys %{ $self->{'data'}->{$section} };
return \%all;
}
}
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();
}
if ( $self->_use_syck() ) {
YAML::Syck::DumpFile( $self->yaml_file(), $self->{'data'} );
}
else {
Cpanel::CPAN::YAML::Tiny::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};
}
}
sub _delete_hash {
my ( $keys, $hash_accumulator, $value ) = @_;
while (@$keys) {
my $key = shift @$keys;
if ( !@$keys ) {
if ( ref $hash_accumulator eq 'HASH' ) {
delete $hash_accumulator->{$key};
return;
}
}
$hash_accumulator = $hash_accumulator->{$key};
}
}
1;
} # --- END Cpanel/RPM/Versions/File/YAML.pm
{ # --- BEGIN Cpanel/Update/Config.pm
package Cpanel::Update::Config;
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::FlushConfig ();
use File::Spec ();
our $VERSION = '2.1';
our $cpanel_update_conf = '/etc/cpupdate.conf';
sub _default_preferences {
return {
'CPANEL' => is_dnsonly() ? 'stable' : '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 ( !-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';
sanitize( $conf_ref, $die_on_failure );
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_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_dnsonly {
return -e '/var/cpanel/dnsonly';
}
sub _is_valid_filepath {
my $filepath = shift;
return 1 if $filepath =~ m{^/} && File::Spec->file_name_is_absolute($filepath);
return;
}
1;
} # --- END Cpanel/Update/Config.pm
{ # --- BEGIN Cpanel/Update/Logger.pm
package Cpanel::Update::Logger;
use strict;
use warnings;
# use Cpanel::SafeDir::MK ();
# use Cpanel::Time::Local ();
use File::Basename;
sub DEBUG { 0 }
sub INFO { 25 }
sub WARN { 50 }
sub ERROR { 75 }
sub FATAL { 100 }
our $VERSION = '1.1';
sub new {
my $class = shift;
my $self = shift || {};
ref($self) eq 'HASH' or die("hashref not passed to new");
bless( $self, $class );
$self->{'stdout'} = 1 if ( !defined $self->{'stdout'} );
$self->{'timestamp'} = 1 if ( !defined $self->{'timestamp'} );
$self->{'backlog'} = [] if ( $self->{'to_memory'} );
eval { $self->set_logging_level( $self->{'log_level'} ); 1 }
or 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 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 );
umask($old_umask);
if ( !$fh ) {
die("Cannot open '$self->{logfile}' for append.");
}
my $orig_fh = select($fh);
$| = 1;
select($orig_fh);
$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);
}
sub close_log {
my $self = shift or 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 die("DESTROY called without an object");
$self->close_log if ( $self->{'fh'} );
}
sub log {
my $self = shift or die("log called as a class");
ref $self eq __PACKAGE__ or 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);
}
}
sub _die {
my $self = shift or die;
my $message = shift || '';
$self->log("***** DIE: $message");
die( "exit level [die] [pid=$$] ($message) " . join ' ', caller() );
}
sub fatal {
my $self = shift or die;
return if ( $self->{'log_level_numeric'} > FATAL );
my $message = shift || '';
$self->log("***** FATAL: $message");
$self->set_need_notify();
}
sub error {
my $self = shift or die;
return if ( $self->{'log_level_numeric'} > ERROR );
my $message = shift || '';
$self->log("E $message");
}
sub warning {
my $self = shift or die;
return if ( $self->{'log_level_numeric'} > WARN );
my $message = shift || '';
$self->log("W $message");
}
sub panic {
my $self = shift or 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();
}
sub info {
my $self = shift or die;
return if ( $self->{'log_level_numeric'} > INFO );
my $message = shift || '';
$self->log(" $message");
}
sub debug {
my $self = shift or die;
return if ( $self->{'log_level_numeric'} > DEBUG );
my $message = shift || '';
$self->log("D $message");
}
sub get_logging_level { shift->{'log_level'} }
sub set_logging_level {
my $self = shift or 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 {
die("Unknown logging level '$log_level' passed to set_logging_level");
}
return $old_log_level;
}
sub get_pbar { shift->{'pbar'} }
sub increment_pbar {
my $self = shift or die;
return if ( !exists $self->{'pbar'} );
my $amount = shift || 1;
my $new_value = $self->{'pbar'} + $amount;
$self->update_pbar($new_value);
}
sub update_pbar {
my $self = shift or 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 die("log called as a class");
$self->info("The Administrator will be notified to review this output when this script completes");
$self->{'need_notify'} = 1;
}
sub get_need_notify {
my $self = shift;
ref $self eq __PACKAGE__ or die("log called as a class");
return $self->{'need_notify'};
}
sub get_stored_log {
my $self = shift;
ref $self eq __PACKAGE__ or 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 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; }
1;
} # --- END Cpanel/Update/Logger.pm
{ # --- BEGIN Cpanel/MariaDB.pm
package Cpanel::MariaDB;
use strict;
sub version_is_mariadb {
my ($version) = @_;
if ( $version =~ m{\.} ) {
return ( $version >= 10.0 ? 1 : 0 );
}
return ( $version >= 100 ? 1 : 0 );
}
1;
} # --- END Cpanel/MariaDB.pm
{ # --- BEGIN Cpanel/MysqlUtils/Versions.pm
package Cpanel::MysqlUtils::Versions;
use strict;
# use Cpanel::MariaDB ();
# use Cpanel::Context ();
our @VERSIONS = ( '4.1', '5.0', '5.1', '5.5', '5.6', '10.0', '10.1' );
our %CANNOT_BE_INSTALLED = ( '4.1' => 1 ); # List all versions that have been removed from rpm.versions
sub get_rpm_target_names {
my (@versions) = @_;
Cpanel::Context::must_be_list();
if ( !@versions ) { @versions = @VERSIONS }
tr/.//d for @versions;
return map { Cpanel::MariaDB::version_is_mariadb($_) ? "MariaDB$_" : "MySQL$_" } @versions;
}
sub get_installable_versions {
return grep { !$CANNOT_BE_INSTALLED{$_} } @VERSIONS;
}
1;
} # --- END Cpanel/MysqlUtils/Versions.pm
{ # --- BEGIN Cpanel/RPM/Versions/Directory.pm
package Cpanel::RPM::Versions::Directory;
use strict;
use Carp;
use Try::Tiny;
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::RPM::Versions::File::YAML ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::Update::Config ();
# use Cpanel::Update::Logger ();
# use Cpanel::Services::Enabled ();
# use Cpanel::iContact ();
# use Cpanel::MariaDB ();
# use Cpanel::MysqlUtils::Versions ();
our $RPM_VERSIONS_DIRECTORY = '/var/cpanel/rpm.versions.d';
sub new {
my ( $class, $args ) = @_;
my $self = $class->init($args);
bless $self, $class;
if ( !-d $self->{'versions_directory'} ) {
Cpanel::SafeDir::MK::safemkdir( $self->{'versions_directory'}, '0700', 2 );
}
$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 init {
my ( $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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self->{'cpconfig'};
}
sub versions_directory {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self->{'versions_directory'};
}
sub local_file_name {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self->{'local_file_name'};
}
sub set {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $args = shift;
$self->{'local_file_data'}->set($args);
}
sub delete {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $args = shift;
$self->{'local_file_data'}->delete($args);
}
sub save {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $args = shift;
$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'} );
}
}
sub fetch {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $args = shift;
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $local_file = $self->{'versions_directory'} . '/' . $self->local_file_name();
$self->{'local_file_data'} = Cpanel::RPM::Versions::File::YAML->new( { file => $local_file } );
}
sub load_directory {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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 $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 ( exists $self->{'versions_store'}{$section}{$key} && !$in_local_file ) { # Not in the local file
if ( exists $self->{'versions_store'}{$section}{$key} && ( defined $self->{'versions_store'}{$section}{$key} && defined $data->{$section}{$key} ) ) {
my $message = "Conflict in section $section key $key";
$self->{'logger'}->fatal($message);
die;
}
}
$self->{'versions_store'}{$section}{$key} = $data->{$section}{$key};
}
}
}
}
sub _not_cpanel_initial_install_file { '/usr/local/cpanel/version' }
sub disable_mysql_deps_for_cpanel_bootstrap {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return undef unless ( !-e _not_cpanel_initial_install_file() && $ENV{'CPANEL_BASE_INSTALL'} );
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->set_dns_targets();
$self->set_ftp_targets();
$self->set_mysql_targets();
$self->set_mail_targets();
}
sub set_mysql_targets {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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' );
}
}
sub set_dns_targets {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $enabled_target = Cpanel::Services::Enabled::is_enabled('dns') ? ( $self->cpconfig()->{'local_nameserver_type'} || 'bind' ) : 'none';
foreach my $target (qw/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' );
}
}
sub set_mail_targets {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $enabled_target = Cpanel::Services::Enabled::is_enabled('mail') ? ( $self->cpconfig()->{'mailserver'} || '' ) : 'none';
my $local_setting = $self->fetch( { 'section' => 'target_settings', 'key' => 'dovecot' } );
$self->{'versions_store'}{'target_settings'}{'dovecot'} = $local_setting || ( $enabled_target eq 'dovecot' ? 'installed' : 'uninstalled' );
}
sub set_ftp_targets {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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' );
}
}
sub load_cpupdate_conf {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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 dovecot imap 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;
}
}
push @local_keys, 'dovecot' if ( ( $update_is_disabled{'dovecot'} || $update_is_disabled{'imap'} ) && $self->cpconfig()->{'mailserver'} eq 'dovecot' );
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 dovecot you would do: /usr/local/cpanel/scripts/update_local_rpm_versions -del target_settings.dovecot\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 {
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;
}
sub config_changed {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self->{'changed'} ? 1 : 0;
}
1;
} # --- END Cpanel/RPM/Versions/Directory.pm
{ # --- BEGIN Cpanel/RPM/Versions/Hooks.pm
package Cpanel::RPM::Versions::Hooks;
use strict;
# use Cpanel::Update::Logger ();
# use Cpanel::FileUtils ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::LoadModule ();
our $LEGACY_HOOK_VERSION = 2;
sub new {
my ( $class, $args ) = @_;
Cpanel::LoadModule::load_perl_module('Cpanel::Hooks::Manage'); # Load when needed as this gets included in updatenow.static
$args ||= {};
my $self = $class->init($args);
return bless $self, $class;
}
sub init {
my ( $class, $args ) = @_;
my $hooks_file = Cpanel::Hooks::Manage::hooksdb_file();
if ( !-e $hooks_file ) {
Cpanel::FileUtils::TouchFile::touchfile($hooks_file);
}
$args->{'logger'} ||= Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'debug' } );
return {
'logger' => $args->{'logger'},
'category' => 'RPM::Versions',
};
}
sub legacy_hook_file { '/var/cpanel/legacy_hooks' }
sub logger {
my $self = shift;
return $self->{'logger'};
}
sub hooks_dir { '/scripts/' }
sub legacy_hook_scripts_map {
my $self = shift;
return {
'dovecot' => {
'pre' => 'predovecotup',
'post' => [qw/postdovecotup/],
},
'exim' => {
'pre' => 'preeximup',
'post' => [qw/posteximup/],
},
'proftpd' => {
'pre' => 'preftpup',
'post' => [qw/postftpinstall postftpup/],
},
'pure-ftpd' => {
'pre' => 'preftpup',
'post' => [qw/postftpinstall postftpup/],
},
'MySQL50-server' => {
'pre' => 'premysqlup',
'post' => [qw/postmysqlinstall postmysqlup/],
},
'MySQL51-server' => {
'pre' => 'premysqlup',
'post' => [qw/postmysqlinstall postmysqlup/],
},
'MySQL55-server' => {
'pre' => 'premysqlup',
'post' => [qw/postmysqlinstall postmysqlup/],
},
'MySQL56-server' => {
'pre' => 'premysqlup',
'post' => [qw/postmysqlinstall postmysqlup/],
},
'MariaDB-server' => {
'pre' => 'premysqlup',
'post' => [qw/postmysqlinstall postmysqlup/],
},
'nsd' => {
'pre' => 'prensdup',
'post' => [qw/postnsdup/],
},
};
}
sub hooksdb {
my $self = shift;
$self->{'hooksdb'} ||= Cpanel::Hooks::Manage::get_hooksdb();
return $self->{'hooksdb'};
}
sub get_hook_id_for {
my $self = shift;
my $event = shift;
my $stage = shift;
my $hook = shift;
my $installed_hooks = $self->hooksdb();
return if ( !$installed_hooks->{ $self->{'category'} } );
return if ( !exists $installed_hooks->{ $self->{'category'} }{$event} );
foreach my $event_hash ( @{ $installed_hooks->{ $self->{'category'} }{$event} } ) {
return $event_hash->{'id'} if $event_hash->{'stage'} eq $stage && $event_hash->{'hook'} eq $hook;
}
return undef;
}
sub check_legacy_hook_version {
my $self = shift;
if ( -e $self->legacy_hook_file() ) {
my ($version) = Cpanel::FileUtils::get_last_lines( $self->legacy_hook_file, 1 );
$version = int( $version || 0 );
return $version == $LEGACY_HOOK_VERSION;
}
return;
}
sub setup_legacy_hooks {
my $self = shift;
my @packages = @_;
return if $self->check_legacy_hook_version();
my %pre_hooks = $self->pre_hook_scripts();
$self->_load_legacy_hooks( 'pre', \%pre_hooks );
my %post_hooks = $self->post_hook_scripts();
$self->_load_legacy_hooks( 'post', \%post_hooks );
Cpanel::FileUtils::writefile( $self->legacy_hook_file(), $LEGACY_HOOK_VERSION );
return;
}
sub _load_legacy_hooks {
my $self = shift;
my $stage = shift;
my $rpm_ref = shift;
foreach my $rpm ( sort keys %{$rpm_ref} ) {
my $scripts = ref $rpm_ref->{$rpm} eq 'ARRAY' ? $rpm_ref->{$rpm} : [ $rpm_ref->{$rpm} ];
foreach my $script ( sort @{$scripts} ) {
my $script_path = $self->hooks_dir() . $script;
my $todo = '/usr/local/cpanel/scripts/run_if_exists ' . $script_path;
my $hook_id = $self->get_hook_id_for( $rpm, $stage, $todo );
next if defined $hook_id;
my %OPTS = (
'hook' => $todo,
'event' => $rpm,
'exectype' => 'script',
'category' => $self->{'category'},
'stage' => $stage,
'force' => 1,
);
my $previous_hook_id = $self->get_hook_id_for( $rpm, $stage, $script_path );
if ( defined $previous_hook_id ) {
my $result = Cpanel::Hooks::Manage::delete( id => $previous_hook_id );
if ( !$result ) {
$self->logger->info( "Cannot remove hook id $previous_hook_id: " . $Cpanel::Hooks::Manage::ERRORMSG );
next;
}
$self->logger->info( "Remove hook for " . $OPTS{'category'} . "\:\:" . $OPTS{'event'} . " to hooks registry" );
}
my $result = Cpanel::Hooks::Manage::add(%OPTS);
if ($result) {
$self->logger->info( "Added hook for " . $OPTS{'category'} . "\:\:" . $OPTS{'event'} . " to hooks registry" );
}
else {
$self->logger->info($Cpanel::Hooks::Manage::ERRORMSG);
}
}
}
}
sub pre_hook_scripts {
my $self = shift;
return map { $_->[0] => $_->[1] }
grep { $_->[1] && ( defined $_->[1] ) }
map { [ $_->[0], $_->[1]->{'pre'} ] }
map { [ $_, $self->legacy_hook_scripts_map->{$_} ] } keys %{ $self->legacy_hook_scripts_map };
}
sub post_hook_scripts {
my $self = shift;
return map { $_->[0] => $_->[1] }
grep { $_->[1] && ( defined $_->[1] ) }
map { [ $_->[0], $_->[1]->{'post'} ] }
map { [ $_, $self->legacy_hook_scripts_map->{$_} ] } keys %{ $self->legacy_hook_scripts_map };
}
1;
} # --- END Cpanel/RPM/Versions/Hooks.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/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 ( defined $, ) {
$result = $self->WRITE( join( $,, @_ ) . $\ );
}
else {
$result = $self->WRITE( join( "", @_ ) . $\ );
}
}
else {
if ( 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/IOCallbackWriteLine.pm
package Cpanel::IOCallbackWriteLine;
use strict;
# use Cpanel::CPAN::IO::Callback::Write();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::CPAN::IO::Callback::Write); }
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;
}
package Cpanel::IOCallbackWriteLine::Buffer;
use strict;
my $recsep_idx;
sub new {
my ( $class, $line_callback ) = @_;
return bless [ q<>, $line_callback ], $class;
}
sub feed { ##no critic qw(RequireArgUnpacking)
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 {
my ($self) = @_;
if ( length $self->[0] ) {
$self->[1]->( substr( $self->[0], 0, length( $self->[0] ), q<> ) );
}
return 1;
}
sub DESTROY {
my ($self) = @_;
if ( length $self->[0] ) {
warn "DESTROY with content left in buffer: “$self->[0]”";
}
return;
}
1;
} # --- END Cpanel/IOCallbackWriteLine.pm
{ # --- BEGIN Cpanel/SafeRun/Dynamic.pm
package Cpanel::SafeRun::Dynamic;
use strict;
use IPC::Open3 ();
# use Cpanel::SafeRun::InOut ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::IOCallbackWriteLine ();
our $VERSION = '1.1';
sub saferundynamic {
my @PROGA = @_;
return if ( substr( $PROGA[0], 0, 1 ) eq '/' && !-x $PROGA[0] );
no strict 'subs';
open( RNULL, "</dev/null" );
my $pid = IPC::Open3::open3( "<&RNULL", ">&STDOUT", ">&STDERR", @PROGA ) || do {
warn 'Error while executing: [' . join( ' ', @PROGA ) . ']: ' . $!;
return;
};
waitpid( $pid, 0 );
close(RNULL);
}
sub livesaferun {
my %OPTS = @_;
my @PROGRAM_WITH_ARGS = @{ $OPTS{'prog'} };
my $formatter = $OPTS{'formatter'};
my $pre_exec_coderef = $OPTS{'pre_exec_coderef'};
my $buffer = $OPTS{'buffer'};
return if ( substr( $PROGRAM_WITH_ARGS[0], 0, 1 ) eq '/' && !-x $PROGRAM_WITH_ARGS[0] );
my $rdr = Symbol::gensym();
my $pid;
if ( $pid = open( $rdr, '-|' ) ) {
my $quit_saferun_loop = 0;
if ( ref $formatter eq 'CODE' ) {
while ( ( my $line = readline($rdr) ) ) {
next if $quit_saferun_loop;
print $formatter->( $line, \$quit_saferun_loop );
}
}
else {
if ($buffer) {
my $buf;
while ( read( $rdr, $buf, 65535 ) ) {
print $buf;
}
}
else {
print while readline($rdr);
}
}
}
elsif ( defined $pid ) {
if ($pre_exec_coderef) { $pre_exec_coderef->(); }
{
no strict 'subs';
open( STDERR, '>&STDOUT' );
}
{
no warnings 'exec';
exec(@PROGRAM_WITH_ARGS);
}
exit 1; # only if exec fails
}
else {
return;
}
close($rdr);
}
sub saferunnoerrordynamic {
my @PROGA = @_;
return if ( substr( $PROGA[0], 0, 1 ) eq '/' && !-x $PROGA[0] );
no strict 'subs';
open( WNULL, ">/dev/null" );
open( RNULL, "</dev/null" );
my $pid = IPC::Open3::open3( "<&RNULL", ">&STDOUT", ">&WNULL", @PROGA ) || do {
warn 'Error while executing: [' . join( ' ', @PROGA ) . ']: ' . $!;
return;
};
waitpid( $pid, 0 );
close(RNULL);
close(WNULL);
}
sub saferun_callback {
my %OPTS = @_;
my @PROGA = @{ $OPTS{'prog'} };
my $callback = $OPTS{'callback'};
return if ( substr( $PROGA[0], 0, 1 ) eq '/' && !-x $PROGA[0] );
my $program = shift @PROGA;
my @args = @PROGA;
my $quit_saferun_loop = 0;
my $out_fh = Cpanel::IOCallbackWriteLine->new(
sub {
if ( ref $callback eq 'CODE' ) {
die if $quit_saferun_loop;
$callback->( $_[0], \$quit_saferun_loop );
}
else {
print $_[0];
}
}
);
my $run = Cpanel::SafeRun::Object->new(
program => $program,
args => \@args,
stdout => $out_fh,
stderr => $out_fh,
);
$? = $run->CHILD_ERROR(); # needed for compat
return;
}
1;
} # --- END Cpanel/SafeRun/Dynamic.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/Version/Tiny.pm
package Cpanel::Version::Tiny;
our $VERSION = '11.56.0';
our $VERSION_BUILD = '11.56.0.52';
our $VERSION_TEXT = '56.0 (build 52)';
our $VERSION_DISPLAY = '56.0.52';
our $parent_version = 11;
our $major_version = 56;
our $minor_version = 0;
our $build_number = 52;
our $build_time_text = 'Tue Sep 12 12:35:59 2017';
our $buildtime = 1505237759;
1;
} # --- END Cpanel/Version/Tiny.pm
{ # --- BEGIN Cpanel/Version.pm
package Cpanel::Version;
use strict;
our ( $VERSION, $MAJORVERSION, $LTS ) = ( '4.0', '11.56', '11.56' );
my $bits;
sub setbits {
if ( !$bits ) { $bits = shift; }
}
sub getbits { $bits }
sub get_version_text {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::VERSION_TEXT;
}
sub get_version_parent {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::parent_version;
}
sub get_version_display {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::VERSION_DISPLAY;
}
sub get_version_full {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::VERSION_BUILD;
}
sub getversionnumber {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::VERSION;
}
sub get_lts {
return $LTS;
}
sub get_build_time {
require Cpanel::Version::Tiny;
$Cpanel::Version::Tiny::buildtime;
}
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 display_version {
my ($ver) = @_;
if ( defined $ver && $ver =~ /^(\d+)\.(\d+)\.(.*)$/ ) {
my $major = "$1.$2";
$major = $2 if $1 == 11 && $major >= 11.54;
return "$major.$3";
}
return;
}
1;
} # --- END Cpanel/Version.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/CPAN/Template/Tiny.pm
package Cpanel::CPAN::Template::Tiny;
use strict;
$Template::Tiny::VERSION = '1.12';
my $EXPR = qr/ [a-z_][\w.]* /xs;
my $LEFT = qr/
(?:
(?: (?:^|\n) [ \t]* )? \[\%\-
|
\[\% \+?
) \s*
/xs;
my $RIGHT = qr/
\s* (?:
\+? \%\]
|
\-\%\] (?: [ \t]* \n )?
)
/xs;
my $PREPARSE = qr/
$LEFT ( IF | UNLESS | FOREACH ) \s+
(
(?: \S+ \s+ IN \s+ )?
\S+ )
$RIGHT
(?!
.*?
$LEFT (?: IF | UNLESS | FOREACH ) \b
)
( .*? )
(?:
$LEFT ELSE $RIGHT
(?!
.*?
$LEFT (?: IF | UNLESS | FOREACH ) \b
)
( .+? )
)?
$LEFT END $RIGHT
/xs;
my $CONDITION = qr/
\[\%\s
( ([IUF])\d+ ) \s+
(?:
([a-z]\w*) \s+ IN \s+
)?
( $EXPR )
\s\%\]
( .*? )
(?:
\[\%\s \1 \s\%\]
( .+? )
)?
\[\%\s \1 \s\%\]
/xs;
sub new {
bless { @_[ 1 .. $#_ ] }, $_[0];
}
sub preprocess {
my $self = shift;
my $text = shift;
$self->_preprocess( \$text );
return $text;
}
sub process {
my $self = shift;
my $copy = ${ shift() };
my $stash = shift || {};
local $@ = '';
local $^W = 0;
$self->_preprocess( \$copy );
my $result = $self->_process( $stash, $copy );
if (@_) {
${ $_[0] } = $result;
}
elsif ( defined wantarray ) {
require Carp;
Carp::carp('Returning of template results is deprecated in Template::Tiny 0.11');
return $result;
}
else {
print $result;
}
}
sub _preprocess {
my $self = shift;
my $copy = shift;
my $id = 0;
1 while $$copy =~ s/
$PREPARSE
/
my $tag = substr($1, 0, 1) . ++$id;
"\[\% $tag $2 \%\]$3\[\% $tag \%\]"
. (defined($4) ? "$4\[\% $tag \%\]" : '');
/sex;
}
sub _process {
my ( $self, $stash, $text ) = @_;
$text =~ s/
$CONDITION
/
($2 eq 'F')
? $self->_foreach($stash, $3, $4, $5)
: eval {
$2 eq 'U'
xor
!! # Force boolification
$self->_expression($stash, $4)
}
? $self->_process($stash, $5)
: $self->_process($stash, $6)
/gsex;
$text =~ s/
$LEFT ( $EXPR ) $RIGHT
/
eval {
$self->_expression($stash, $1)
. '' # Force stringification
}
/gsex;
$text =~ s/^\s*(.+?)\s*\z/$1/s if $self->{TRIM};
return $text;
}
sub _foreach {
my ( $self, $stash, $term, $expr, $text ) = @_;
my $list = $self->_expression( $stash, $expr );
unless ( ref $list eq 'ARRAY' ) {
return '';
}
return join '', map { $self->_process( { %$stash, $term => $_ }, $text ) } @$list;
}
sub _expression {
my $cursor = $_[1];
my @path = split /\./, $_[2];
foreach (@path) {
return undef if substr( $_, 0, 1 ) eq '_';
my $type = ref $cursor;
if ( $type eq 'ARRAY' ) {
return '' unless /^(?:0|[0-9]\d*)\z/;
$cursor = $cursor->[$_];
}
elsif ( $type eq 'HASH' ) {
$cursor = $cursor->{$_};
}
elsif ($type) {
$cursor = $cursor->$_();
}
else {
return '';
}
}
return $cursor;
}
1;
} # --- END Cpanel/CPAN/Template/Tiny.pm
{ # --- BEGIN Cpanel/RPM/Versions/File.pm
package Cpanel::RPM::Versions::File;
use strict;
use Try::Tiny;
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::Config::Sources ();
# use Cpanel::Crypt::GPG::Settings ();
# use Cpanel::Exception ();
# use Cpanel::FileUtils ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::FindBin ();
# use Cpanel::GenSysInfo ();
# use Cpanel::Hooks ();
# use Cpanel::HttpRequest ();
# use Cpanel::RPM ();
# use Cpanel::RPM::Versions::Directory ();
# use Cpanel::RPM::Versions::File::YAML ();
# use Cpanel::RPM::Versions::Hooks ();
# use Cpanel::SafeChdir ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeRun::Dynamic ();
# use Cpanel::SafeRun::Errors ();
# use Cpanel::Sync::Digest ();
# use Cpanel::TempFile ();
# use Cpanel::URL ();
# use Cpanel::Update::Logger ();
# use Cpanel::Version ();
# use Cpanel::ConfigFiles::RpmVersions ();
my $use_template = 1;
eval { require Template };
if ($@) {
require Cpanel::CPAN::Template::Tiny;
$use_template = 0;
}
our $methods = [qw/url_templates rpm_groups srpm_sub_packages srpm_versions rpm_locations target_settings install_info file_format user_scripts location_keys/];
my $_has_defined_methods = 0;
sub new {
my ( $class, $args ) = @_;
my $self = $class->init($args);
bless $self, $class;
if ( !$_has_defined_methods ) {
foreach my $method (@$methods) {
no strict 'refs';
no warnings 'redefine';
*{$method} = sub {
my ( $self, $key ) = @_;
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 } );
foreach my $current_key ( keys %{$dir_section} ) {
$config_section->{$current_key} = $dir_section->{$current_key};
}
return $config_section;
}
};
*{ 'set_' . $method } = sub {
my ( $self, $args ) = @_;
my $key = $args->{'key'};
my $value = $args->{'value'};
return $self->dir_files()->set( { 'section' => $method, 'key' => $key, 'value' => $value } );
};
*{ 'delete_' . $method } = sub {
my ( $self, $args ) = @_;
my $key = $args->{'key'};
my $value = $args->{'value'};
return $self->dir_files()->delete( { 'section' => $method, 'key' => $key, 'value' => $value } );
};
}
$_has_defined_methods = 1;
}
return $self;
}
sub init {
my ( $class, $args ) = @_;
$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/mysql_targets only_targets temp_dir rpm_bin file directory rpm_qa logger old_rpm_versions_file rpm_install/ );
}
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 $request = Cpanel::HttpRequest->new(
'retry_dns' => 0,
'hideOutput' => 1,
'logger' => $args->{'logger'},
);
die "Failed to instantiate Cpanel::HttpRequest object." if ( !$request );
my @digest_algorithms = Cpanel::Crypt::GPG::Settings::allowed_digest_algorithms();
return {
'config_file' => Cpanel::RPM::Versions::File::YAML->new( { file => $file } ),
'dir_files' => 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'},
'temp_dir' => $args->{'temp_dir'} || '/usr/local/cpanel/tmp/rpm_downloads',
'request' => $request,
'rpm_object' => Cpanel::RPM->new(),
'use_template' => $use_template,
$args->{'old_rpm_versions_file'} ? ( 'old_rpm_versions_file' => $args->{'old_rpm_versions_file'} ) : (),
'digest_algorithms' => \@digest_algorithms,
'max_download_attempts' => 5,
};
}
sub logger { shift->{'logger'} }
sub rpm_bin {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
$self->{rpm_object} ||= Cpanel::RPM->new; # not required, here as a security
return $self->{rpm_object}->bin;
}
sub rpm_qa {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
return $self->{'rpm_qa'} if $self->{'rpm_qa'};
$self->{rpm_object} ||= Cpanel::RPM->new; # not required, here as a security
return $self->{'rpm_qa'} = $self->{rpm_object}->qa();
}
sub use_template {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
return $self->{'use_template'};
}
sub http_request {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
return $self->{'request'};
}
sub sysinfo {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
$self->{'sysinfo'} ||= Cpanel::GenSysInfo::run();
return $self->{'sysinfo'};
}
sub cpsources {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
$self->{'cpsources'} ||= Cpanel::Config::Sources::loadcpsources();
return $self->{'cpsources'};
}
sub config_file {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
return $self->{'config_file'};
}
sub dir_files {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
return $self->{'dir_files'};
}
sub set_install_targets {
my ( $self, $args ) = @_;
my $method = 'install_targets';
my $key = $args->{'key'};
my $value = $args->{'value'};
return $self->dir_files()->set( { 'section' => $method, 'key' => $key, 'value' => $value } );
}
sub delete_install_targets {
my ( $self, $args ) = @_;
my $method = 'install_targets';
my $key = $args->{'key'};
my $value = $args->{'value'};
return $self->dir_files()->delete( { 'section' => $method, 'key' => $key, 'value' => $value } );
}
sub install_targets {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
my $key = shift or die;
my $filter = shift or die;
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;
if ( ref $value->{'dependencies'} eq 'ARRAY' ) {
push @flat_list, @{ $value->{'dependencies'} || [] } unless $filter eq 'uninstalled';
}
else {
push @flat_list, $value->{'dependencies'} unless $filter eq 'uninstalled';
}
if ( ref $value->{'components'} eq 'ARRAY' ) {
push @flat_list, @{ $value->{'components'} || [] };
}
else {
push @flat_list, $value->{'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 expand_to_srpm_versions_from_target {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $target = shift or die;
my %package_map;
my $rpm_group = $self->rpm_groups($target);
my $need_srpm_versions = ( ref $rpm_group eq 'ARRAY' ) ? $rpm_group : [$target];
my $srpm_versions = $self->srpm_versions();
foreach my $package_name ( @{$need_srpm_versions} ) {
$package_map{$package_name} = $srpm_versions->{$package_name} if exists $srpm_versions->{$package_name};
}
return \%package_map;
}
sub expand_target_to_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $target = shift;
return if !$target;
my $package_map = $self->expand_to_srpm_versions_from_target($target);
my $temp_map = $self->find_from_srpm_sub_packages($target);
foreach my $package_name ( keys %{ $temp_map || {} } ) {
$package_map->{$package_name} = $temp_map->{$package_name};
}
return $package_map;
}
sub install_hash {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $ihash = $self->list_rpms_in_state('installed');
my $to_install = {};
foreach my $rpm ( keys %{$ihash} ) {
if ( !$self->_is_installed_in_os( $rpm, $ihash->{$rpm} ) ) { # If the RPM is already installed in the OS there is no need to reinstall.
$to_install->{$rpm} = $ihash->{$rpm};
}
}
$self->{'install_hash'} = $to_install;
return $to_install;
}
sub uninstall_hash {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $ulist = $self->list_rpms_in_state('uninstalled');
my $ilist = $self->list_rpms_in_state("installed");
my $to_uninstall = {};
foreach my $rpm ( keys %{$ulist} ) {
if ( !exists $ilist->{$rpm} && $self->_is_installed_in_os($rpm) ) { # Don't uninstall if the RPM is found in
$to_uninstall->{$rpm} = $ulist->{$rpm}; # the list of things to be installed
}
}
return $to_uninstall;
}
sub list_rpms_in_state {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $filter = shift;
$filter ||= 'installed';
my @targets = $self->get_all_targets_in_state($filter) or return {};
if ( $self->{'only_targets'} ) {
foreach my $target ( @{ $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'} ) {
foreach my $target ( @{ $self->{'rpm_install'} } ) {
my $srpm_versions = $self->srpm_versions();
if ( $srpm_versions->{$target} ) {
$packages{$target} = $srpm_versions->{$target};
}
else {
my $temp_map = $self->find_from_srpm_sub_packages($target);
foreach my $package_name ( keys %{ $temp_map || {} } ) {
$packages{$package_name} = $temp_map->{$package_name};
}
}
}
return \%packages;
}
foreach my $target (@targets) {
my $modules = $self->install_targets( $target, $filter );
if ( @{ $modules || [] } ) {
foreach my $module ( @{$modules} ) {
foreach my $sub_target ( $self->expand_target_to_rpms($module) ) {
@packages{ keys %{$sub_target} } = values %{$sub_target};
}
}
}
else {
foreach my $sub_target ( $self->expand_target_to_rpms($target) ) {
@packages{ keys %{$sub_target} } = values %{$sub_target};
}
}
}
return \%packages;
}
sub get_rpm_template {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $rpm = shift or die;
my $location;
if ( $self->srpm_versions->{$rpm} ) {
$location = $self->rpm_locations->{$rpm} || 'default';
}
else {
my $srpm_sub_packages = $self->srpm_sub_packages();
foreach my $srpm ( keys %{$srpm_sub_packages} ) {
next unless grep { $_ eq $rpm } @{ $srpm_sub_packages->{$srpm} };
$location = $self->rpm_locations->{$srpm} || 'default';
}
}
return $location || 'default';
}
sub url {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $rpm = shift or die;
my $version = shift or die("No version provided for $rpm");
if ( $self->use_template() ) {
$self->{'tt'} ||= Template->new();
}
else {
$self->{'tt'} ||= Cpanel::CPAN::Template::Tiny->new();
}
my $template_name = $self->get_rpm_template($rpm);
my $url_template = $self->url_templates($template_name) or die("The RPM '$rpm-$version' does not have a valid URL template '$template_name'"); ###doc###
my @urls;
my ( $package_version, $package_revision ) = split /-/, $version, 2;
if ( !$self->{'url_template_stash'} ) {
$self->{'url_template_stash'} = {
'httpupdate' => $self->cpsources->{'HTTPUPDATE'},
'lts' => Cpanel::Version::get_lts(),
'rpm_dist' => $self->sysinfo->{'rpm_dist'},
'rpm_dist_ver' => $self->sysinfo->{'rpm_dist_ver'},
'rpm_arch' => $self->sysinfo->{'rpm_arch'},
};
}
my $lowest_cpanel_version_supported = 'unknown';
if ( $package_revision =~ m/cp(\d\d)(\d\d)$/ ) {
$lowest_cpanel_version_supported = "$1.$2";
}
my $vars = {
%{ $self->{'url_template_stash'} },
'package' => $rpm,
'package_version' => $package_version,
'package_revision' => $package_revision,
'lowest_cpanel_version_supported' => $lowest_cpanel_version_supported,
};
my $output = '';
$self->{'tt'}->process( \$url_template, $vars, \$output );
return $output;
}
sub download {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my ( $url, $dest_file, $opts ) = @_;
return { 'status' => 0, 'file' => $dest_file } unless ( $url && $dest_file );
my $res;
$self->logger->info("Downloading $url");
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 $dest_file 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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $download_hash = shift or die;
my $algorithm = shift or die;
my $temp_dir = $self->{'temp_dir'};
unlink( glob( $temp_dir . '/*.' . $algorithm ) );
my %digests;
for my $rpm ( sort keys %{$download_hash} ) {
my $url = $download_hash->{$rpm}->{url};
my $location = $download_hash->{$rpm}->{location};
my $dest_file = $url;
$dest_file =~ s/^[^\/]+:\/\///;
$dest_file =~ s/\//_/g;
$dest_file = $temp_dir . '/' . $dest_file . '.' . $algorithm;
next if -e $dest_file;
my $download_url = $url . '/rpm.' . $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;
my $res = $self->download( $download_url, $dest_file, { signed => $signed, vendor => $vendor, categories => $categories, no_die_on_error => 1 } );
if ( $res->{'status'} ) {
$digests{$url} = $res->{'file'};
}
}
return \%digests;
}
sub init_digests {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $digest_urls = shift or die;
my %digests;
for my $url ( keys %{$digest_urls} ) {
my $digest_file = $digest_urls->{$url};
if ( !-e $digest_file ) {
next;
}
open( my $fh, '<', $digest_file ) or die "Failed to open digest file '$digest_file': $!";
my %rpm_digests;
while ( my $line = <$fh> ) {
chomp $line;
my ( $digest, $filename ) = split( /\s+/, $line, 2 );
$rpm_digests{$filename} = $digest;
}
close($fh);
$digests{$url} = \%rpm_digests;
}
return \%digests;
}
sub download_hash {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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 $rpm_file = $self->_get_rpm_name($url);
my $location = $self->get_rpm_template($package);
$url =~ s/\/$//;
$url =~ s/\/[^\/]+$//;
$download_hash{$rpm_file} = { url => $url, location => $location };
}
}
return \%download_hash;
}
sub download_all {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $temp_dir = $self->{'temp_dir'};
-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();
my %digest_files;
my %rpm_digests;
for my $alg ( @{ $self->{'digest_algorithms'} } ) {
$digest_files{$alg} = $self->stage_digests( $download_hash, $alg );
$rpm_digests{$alg} = $self->init_digests( $digest_files{$alg} );
}
my @rpms;
RPM:
for my $rpm_file ( keys %$download_hash ) {
my $download_to = $temp_dir . '/' . $rpm_file;
my %expected_digests;
for my $alg ( @{ $self->{'digest_algorithms'} } ) {
my $digest = $rpm_digests{$alg}->{ $download_hash->{$rpm_file}->{url} }{$rpm_file};
if ($digest) {
$expected_digests{$alg} = $digest;
}
}
unless ( keys %expected_digests ) {
my $err = "No digest data for $rpm_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("$rpm_file already downloaded");
push @rpms, $rpm_file;
next RPM;
}
}
}
my $url = $download_hash->{$rpm_file}->{url} . '/' . $rpm_file;
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: $rpm_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{$alg} ) {
push @rpms, $rpm_file;
$success = 1;
last DIGEST;
}
}
else {
$self->logger->warning("Failed to generate local digest for file: $rpm_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{$self->{'digest_algorithms'}[0]}; mirror IP $ip)";
}
}
catch {
$err = $_;
};
last ATTEMPT if !$err;
if ( $attempt == $self->{'max_download_attempts'} ) {
$self->logger->fatal($err);
die $err;
}
$self->logger->error( "Retrying download of $rpm_file (attempt " . ( $attempt + 1 ) . "/$self->{'max_download_attempts'}): $err" );
}
}
return \@rpms;
}
sub _get_rpm_name {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $url = shift;
my @url_parts = split /\//, $url;
my $file = $url_parts[-1];
return $file;
}
sub stage {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $rpms = $self->download_all();
if ( !@$rpms ) {
$self->logger->info("No new RPMS needed for install");
}
$self->determine_expired_rpms();
push @{ $self->{'to_install'} }, @{$rpms};
return scalar @{ $self->{'to_install'} } || '0E0';
}
sub determine_expired_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return unless $self->{'old_rpm_versions_file'};
return if ( $] < 5.013 );
my $previous_file = eval { Cpanel::RPM::Versions::File->new( { 'directory' => $self->dir_files()->{'versions_directory'}, 'file' => $self->{'old_rpm_versions_file'}, 'logger' => $self->logger } ) } or return;
my $previous_rpms = $previous_file->srpm_versions();
my $current_rpms = $self->srpm_versions();
my @removed_srpms;
foreach my $srpm ( keys %{$previous_rpms} ) {
if ( !$current_rpms->{$srpm} ) {
push @removed_srpms, $srpm;
}
}
my $keep_rpms = $self->list_rpms_in_state('installed');
my %missing_rpm_map;
foreach my $srpm (@removed_srpms) {
my $package_map = $previous_file->expand_target_to_rpms($srpm);
foreach my $rpm ( keys %{$package_map} ) {
next if ( $keep_rpms->{$rpm} ); # Something still wants it installed.
next unless ( $self->_is_installed_in_os($rpm) ); # It's not installed so no need to uninstall it.
$missing_rpm_map{$rpm} = $package_map->{$rpm};
}
}
$self->{'expired_rpms'} = [ keys %{missing_rpm_map} ];
return \%missing_rpm_map;
}
sub test_rpm_install {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my (@rpms) = @_;
$self->{'to_install'} ||= [];
if ( ( !@rpms ) ) {
@rpms = @{ $self->{'to_install'} };
}
if (@rpms) {
my $chdir = Cpanel::SafeChdir->new( $self->{'temp_dir'} );
my $rpm_bin = $self->rpm_bin();
$self->logger->info("Testing RPM transaction");
my $output = Cpanel::SafeRun::Errors::saferunallerrors( $rpm_bin, '-U', '--test', '--replacepkgs', '--oldpackage', @rpms );
my $exit_code = $!;
my $child_error = $? >> 8;
my $remove_perl514 = grep { $_ =~ m/cpanel-perl-514/ } keys %{ $self->uninstall_hash() };
if ( $remove_perl514 && ( $exit_code || $child_error ) ) {
$output =~ s{^\s+file /usr/local/cpanel/3rdparty/bin/perl from install of cpanel-perl-5\d\d\S+ conflicts with file from package cpanel-perl-5\d\d\S+}{};
$output =~ s{^\s+file /etc/systemd/system/spamd.service from install of cpanel-perl-5\d\d\S+ conflicts with file from package cpanel-perl-5\d\d\S+}{};
$exit_code = $child_error = 0 if ( $output !~ m/\S/ms );
}
$self->logger->info($output);
$self->logger->warning("Exit Code: $child_error") if $child_error > 0;
if ( ( $exit_code > 0 ) || ( $child_error > 0 ) ) {
my $err = "Test install failed: $output";
$self->logger->fatal($err);
die $err;
}
$self->logger->info("RPM transaction succeeded!");
return 1;
}
}
sub _output_hook {
my $self = shift or die;
ref $self eq __PACKAGE__ or die "must be called as a method";
my $output = shift or return;
$self->{'cmd_output'} ||= '';
$self->{'cmd_output'} .= $output;
$self->logger->info($output);
}
sub install_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
-d $self->{'temp_dir'} or Cpanel::SafeDir::MK::safemkdir( $self->{'temp_dir'}, '0700', 2 );
my $chdir = Cpanel::SafeChdir->new( $self->{'temp_dir'} );
$self->{'to_install'} ||= [];
my @rpms = @{ $self->{'to_install'} } or return;
my $rpm_bin = $self->rpm_bin();
my @cmd = ( $rpm_bin, '-Uv', '--replacepkgs', '--oldpackage', @rpms );
$self->logger->info( 'Installing new rpms: ' . join( ' ', sort @rpms ) );
Cpanel::SafeRun::Dynamic::livesaferun(
'prog' => \@cmd,
'formatter' => sub { $self->_output_hook(@_) },
);
my $errors = $self->_parse_rpm_errors( $self->{'cmd_output'} );
my $child_error = $? >> 8;
$self->logger->warning("Error Code: $child_error") if $child_error > 0;
if ( !$errors ) {
unlink( glob( $self->{'temp_dir'} . '/*.rpm' ) );
unlink( glob( $self->{'temp_dir'} . '/*.md5' ) );
return;
}
$self->logger->error("The following possible errors were detected while installing RPMs:");
$self->logger->error($errors);
if ( -e q{/var/cpanel/dev_sandbox} ) {
my $rpms_to_remove = $self->_parse_failed_dependencies( $self->{'cmd_output'} );
$self->logger->error( "Try to run:\n> rpm -e --nodeps " . join( ' ', @$rpms_to_remove ) ) if $rpms_to_remove && scalar @$rpms_to_remove;
}
$self->logger->set_need_notify(); # Notify on completion of these errors.
return;
}
sub uninstall_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my @rpms = @_;
if ( !@rpms ) {
@rpms = keys %{ $self->uninstall_hash() };
}
if ( $self->{'expired_rpms'} ) {
foreach my $rpm ( @{ $self->{'expired_rpms'} } ) {
push( @rpms, $rpm ) unless ( grep { $_ eq $rpm } @rpms );
}
}
if ( !@rpms ) {
$self->logger->info('No RPMS need to be uninstalled');
return;
}
$self->logger->info( 'Uninstalling unneeded rpms: ' . join( ' ', @rpms ) );
my @to_erase = $self->_rpm_q_dedup(@rpms);
Cpanel::SafeRun::Dynamic::livesaferun(
'prog' => [ $self->rpm_bin(), '-e', '--nodeps', @to_erase ],
'formatter' => sub { $self->_output_hook(@_) },
);
my $child_error = $? >> 8;
$self->logger->warning("Error Code: $child_error") if $child_error > 0;
my $errors = $self->_parse_rpm_errors( $self->{'cmd_output'} );
return if ( !$errors );
$self->logger->error("The following possible errors were detected while uninstalling RPMs:");
$self->logger->error($errors);
$self->logger->set_need_notify();
}
sub _disable_monitoring_file {
return q{/var/run/chkservd.suspend};
}
sub _restart_monitoring_service {
return Cpanel::SafeRun::Errors::saferunnoerror( '/usr/local/cpanel/scripts/restartsrv_tailwatchd', '--no-verbose' );
}
my $monitoring_disabled_from;
sub disable_monitoring {
my ($self) = @_; # self will not be defined when called from the END block
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();
return 1;
}
sub restore_monitoring {
my ($self) = @_; # self will not be defined when called from the END block
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::safeunlink($disable_file);
_restart_monitoring_service();
return;
}
sub commit_changes {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my @rpms = keys %{ $self->install_hash() };
my $disable = $self->disable_monitoring();
if ($disable) { # only when we disabled it
eval q{ END{ restore_monitoring() } };
}
if (@rpms) {
if ( !$ENV{CPANEL_BASE_INSTALL} ) {
run_hooks( $self->logger(), \@rpms, 'pre' );
}
else {
$self->logger->info("Hooks system NOT enabled");
my @error = split( "\n", "Hooks Error: $@" );
$self->logger->debug($_) foreach (@error);
}
}
$self->uninstall_rpms();
$self->install_rpms();
if ( @rpms && !$ENV{CPANEL_BASE_INSTALL} ) {
run_hooks( $self->logger(), [ keys %{ $self->{'install_hash'} } ], 'post' );
}
if ( $self->dir_files()->config_changed() ) {
$self->dir_files()->save();
}
$self->restore_monitoring() if $disable;
return;
}
sub run_hooks {
my ( $output_obj, $rpms, $stage ) = @_;
if ( $INC{'YAML/Syck.pm'} ) {
$output_obj->info("Hooks system enabled.");
}
else {
$output_obj->warn("Hooks system unavailable.");
return 0;
}
my $err;
try {
Cpanel::Hooks::init_hooks();
if ( $stage eq 'pre' ) {
Cpanel::RPM::Versions::Hooks->new( { 'logger' => $output_obj } )->setup_legacy_hooks();
}
$output_obj->info("Checking for and running RPM::Versions '$stage' hooks for any RPMs about to be installed");
foreach my $rpm ( @{$rpms} ) {
Cpanel::Hooks::hook(
{
'category' => 'RPM::Versions',
'event' => $rpm,
'stage' => $stage,
'blocking' => 1,
},
);
}
$output_obj->info("All required '$stage' hooks have been run");
}
catch {
$err = $_;
};
if ($err) {
$output_obj->warning( "Hooks system failure with RPMs ( " . join( ', ', @{$rpms} ) . " ) " . Cpanel::Exception::get_string($err) );
return 0;
}
return 1;
}
sub get_all_targets_in_state {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $filter = shift or die;
my @filtered_list;
my $target_settings = $self->target_settings();
foreach my $target ( keys %{$target_settings} ) {
if ( $target_settings->{$target} eq $filter ) {
push @filtered_list, $target;
}
}
return @filtered_list;
}
sub save {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self->dir_files()->save();
}
sub _is_installed_in_os {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $rpm = shift;
my $version = shift;
my $installed_in_os = $self->rpm_qa();
if ( defined $version ) {
return exists $installed_in_os->{$rpm} && $installed_in_os->{$rpm} eq $version ? 1 : 0;
}
return exists $installed_in_os->{$rpm} ? 1 : 0;
}
sub _parse_rpm_errors {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $output = shift;
return if !$output;
my @errors;
foreach my $line ( split( /\n/, $output ) ) {
if ( $line =~ /^error:\s*([^:]+)\s*/ ) {
push @errors, $1 if $1;
}
}
if (@errors) {
my $errors = join ' ', @errors;
return $errors;
}
else {
return;
}
}
sub _parse_failed_dependencies {
my $self = shift or die; # no really advantage of using a class method
ref $self eq __PACKAGE__ or die("must be called as a method");
my $output = shift;
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 _fetch_altered_files {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $skip_digest_check = shift;
my $rpm_bin = $self->rpm_bin();
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;
my %lock;
$self->logger->info("Looking for RPMs with modified files other than timestamp or permissions changes");
my @broken_files;
local $ENV{'LC_ALL'} = 'C';
my @rpm_options = ( $ENV{'CPANEL_RPM_NO_DIGEST'} || $skip_digest_check ) ? qw{ --nodigest --nomd5} : ();
open( my $out_fh, '-|', $rpm_bin, '-vV', @rpm_options, @cpanel_rpm_list );
while ( my $line = <$out_fh> ) {
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+[cd]\s/ ); # Skip config or doc files.
chomp $line;
next unless ( $line =~ m/^(\S{8,9}|missing\s+[cd]|missing)\s+(\S.*)$/ ); # Doesn't look like an rpm -vV row?
my ( $reason, $file ) = ( $1, $2 );
next if $lock{$file};
$lock{$file} = 1;
push @broken_files, [ $file, $reason ];
}
close $out_fh;
return \@broken_files;
}
sub _fetch_altered_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $broken_files = shift;
my $rpm_bin = $self->rpm_bin();
my %cpanel_rpm_list = %{ $self->list_rpms_in_state('installed') };
my %packages;
my $cache;
foreach my $data (@$broken_files) {
my $file = $data->[0];
if ( $cache && exists $cache->{files}->{$file} ) {
my $package = $cache->{package};
push @{ $packages{$package} }, $data;
next;
}
$cache = undef;
my (@belongs_to_rpms) = Cpanel::SafeRun::Errors::saferunallerrors( $rpm_bin, '-q', '--queryformat', '[%{NAME},%{VERSION},%{RELEASE}\\n]', '-f', $file );
if ( !scalar @belongs_to_rpms ) {
$self->logger->warning("Unable to determine owner of file '$file'");
next;
}
my $files = {};
foreach my $package (@belongs_to_rpms) {
chomp $package;
my $rpm = ( split /,/, $package )[0];
if ( scalar @belongs_to_rpms == 1 ) {
my @status = Cpanel::SafeRun::Errors::saferunallerrors( $rpm_bin, '-qVv', $rpm );
foreach my $st (@status) {
my ( $reason, $f ) = split( /\s+\//, $st, 2 );
$f = '/' . $f;
$reason =~ s/\s+$//;
$files->{$f} = $reason;
}
$cache = {
package => $package,
files => $files,
};
}
next unless ( exists $cpanel_rpm_list{$rpm} );
$packages{$package} ||= [];
push @{ $packages{$package} }, $data;
}
}
return \%packages;
}
sub get_dirty_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $skip_digest_check = shift;
my $broken_files = $self->_fetch_altered_files($skip_digest_check);
return {} if ( !@$broken_files );
return $self->_fetch_altered_rpms($broken_files);
}
sub reinstall_rpms {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my @reinstall = @_;
my $rpm_bin = $self->rpm_bin();
foreach my $rpm (@reinstall) {
($rpm) = split( ',', $rpm );
}
my @rpms_to_remove = $self->_rpm_q_dedup(@reinstall);
$self->logger->info( "Removing " . scalar @rpms_to_remove . " broken rpms: " . join( ', ', @rpms_to_remove ) );
Cpanel::SafeRun::Dynamic::livesaferun(
'prog' => [ $rpm_bin, qw{-e --nodeps --justdb}, @rpms_to_remove ],
'formatter' => sub { $self->_output_hook(@_) },
);
$self->stage();
$self->commit_changes();
}
sub find_from_srpm_sub_packages {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $name = shift;
my $srpm_versions = $self->srpm_versions();
my $srpm_sub_packages = $self->srpm_sub_packages();
foreach my $key ( keys %{$srpm_sub_packages} ) {
foreach my $srpm_name ( @{ $srpm_sub_packages->{$key} } ) {
if ( $srpm_name eq $name ) {
my $version_info = $srpm_versions->{$key};
if ($version_info) {
return { $name => $version_info };
}
}
}
}
return {};
}
sub _rpm_q_dedup {
my $self = shift;
my @rpms = @_;
my %seen;
my $rpm_q = Cpanel::SafeRun::Errors::saferunallerrors( $self->rpm_bin(), '-q', @rpms ) || '';
my @list = grep { !$seen{$_}++ } ( $rpm_q =~ /^(\S+)$/mg );
@list = @rpms if $? || !@list;
return @list;
}
1;
} # --- END Cpanel/RPM/Versions/File.pm
{ # --- BEGIN Cpanel/SafeDir.pm
package Cpanel::SafeDir;
use Cwd ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeDir::Read ();
# use Cpanel::SafeDir::RM ();
# use Cpanel::Logger ();
my %SAFEDIRCACHE;
our $VERSION = 1.0;
sub safedir {
my $odir = shift || '';
my $homedir = shift;
my $abshomedir = shift;
if ( !$homedir ) { $homedir = $Cpanel::homedir; }
if ( !$abshomedir ) { $abshomedir = $Cpanel::abshomedir; }
my $dir = $odir;
if ( defined $SAFEDIRCACHE{$odir} && $SAFEDIRCACHE{$odir} ne '' ) { return $SAFEDIRCACHE{$odir}; }
if ( defined $dir && defined $homedir && $dir eq $homedir || defined $dir && defined $abshomedir && $dir eq $abshomedir ) { return $abshomedir; }
$dir =~ s/[\r\n]//g;
$dir = homedirfixup( $dir, $homedir, $abshomedir );
my $testdir = safe_abs_path($dir);
if ($testdir) {
$dir = homedirfixup( $testdir, $homedir, $abshomedir );
}
if ( $dir !~ /^$abshomedir/ or test_path_for_links($dir) ) {
$dir = $abshomedir;
}
$SAFEDIRCACHE{$odir} = $dir;
return $dir;
}
sub test_path_for_links {
my $path = shift;
my @chunks = split( /\//, $path );
my $test_path = '';
foreach my $chunk (@chunks) {
next unless $chunk;
$test_path .= '/' . $chunk;
return 1 if ( -l $test_path );
}
return 0;
}
sub maildirfixup {
my $dir = shift;
my $homedir = shift;
my $abshomedir = shift;
my $acct = shift;
my $basedir = 'mail';
if ( defined $Cpanel::appname && $Cpanel::appname eq 'webmail' && $Cpanel::authuser =~ /\@/ ) {
$acct = $Cpanel::authuser;
}
if ( $acct && $acct =~ /\@/ ) {
my ( $user, $domain ) = split( /\@/, $acct );
$user =~ s/\///g;
$domain =~ s/\///g;
$domain =~ tr/\.//s;
$basedir = 'mail/' . $domain . '/' . $user;
}
if ( !$homedir ) { $homedir = $Cpanel::homedir; }
if ( !$abshomedir ) { $abshomedir = $Cpanel::abshomedir; }
$dir =~ s/^$basedir//;
my $did_strip_abshomedir = ( $dir =~ s/^$abshomedir(\/$basedir)?// );
if ( !$did_strip_abshomedir ) {
$dir =~ s/^$homedir(\/$basedir)?//;
}
$dir =~ s/\.\.//g;
$dir = "$abshomedir/$basedir/$dir";
$dir =~ s{//+}{/}g;
$dir =~ s/\/$//g;
return $dir;
}
sub publichtmldirfixup {
my $dir = shift;
my $homedir = shift;
my $abshomedir = shift;
if ( !$homedir ) { $homedir = $Cpanel::homedir; }
if ( !$abshomedir ) { $abshomedir = $Cpanel::abshomedir; }
$dir =~ s/\n//g;
$dir =~ s/^public_html//;
my $did_strip_abshomedir = ( $dir =~ s/^$abshomedir(\/public_html)?// );
if ( !$did_strip_abshomedir ) {
$dir =~ s/^$homedir(\/public_html)?//;
}
$dir =~ s/\.\.//g;
$dir = "$abshomedir/public_html/$dir";
$dir =~ s{//+}{/}g;
$dir =~ s/\/$//g;
return $dir;
}
sub homedirfixup {
my $dir = shift;
my $homedir = shift;
my $abshomedir = shift;
if ( !$homedir ) { $homedir = $Cpanel::homedir || q{}; }
if ( !$abshomedir ) { $abshomedir = $Cpanel::abshomedir || q{}; }
$dir =~ s/\n//g;
$dir =~ s/\/$//g;
$abshomedir =~ s/\/$//g;
my $did_strip_abshomedir = ( $dir =~ s/^$abshomedir// );
if ( !$did_strip_abshomedir ) {
$dir =~ s/^$homedir//;
}
$dir =~ s/\.\.//g;
$dir = "$abshomedir/$dir";
$dir =~ s{//+}{/}g;
$dir =~ s/\/$//g;
return $dir;
}
sub safe_abs_path {
my $path = shift;
my $tainted_path = Cwd::abs_path($path);
return '' unless defined $tainted_path;
($tainted_path) = $tainted_path =~ m{^(.*)$};
return $tainted_path; # the regex-capture-as-last-item would return it but lets be explicit for sanity's sake
}
sub safemkdir {
goto &Cpanel::SafeDir::MK::safemkdir;
}
sub safermdir {
goto \&Cpanel::SafeDir::RM::safermdir;
}
sub read_dir {
goto &Cpanel::SafeDir::Read::read_dir;
}
1;
} # --- END Cpanel/SafeDir.pm
{ # --- BEGIN Cpanel/Sync/Common.pm
package Cpanel::Sync::Common;
use strict;
# use Cpanel::SafeRun::Errors ();
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/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;
# use Cpanel::OSSys::Bits ();
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 1 if Cpanel::OSSys::Bits::getbits() == 32 && $num == '2147483647' + 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 );
$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 Cpanel::OSSys::Env ();
# use Cpanel::Sys::Hardware::Memory::Linux ();
# use Cpanel::Sys::Hardware::Memory::Vzzo ();
sub get_module {
my ($env_type) = @_;
my $envtype ||= Cpanel::OSSys::Env::get_envtype();
my $module = 'Cpanel::Sys::Hardware::Memory::' . ( $envtype eq 'virtuozzo' ? 'Vzzo' : 'Linux' );
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/Sync/v2.pm
package Cpanel::Sync::v2;
use strict;
use warnings;
use Carp;
# use Cpanel::CPAN::YAML::Tiny (); # Must be perlpkg friendly
# use Cpanel::Config::CpConfGuard ();
# use Cpanel::Crypt::GPG::VendorKeys::Verify (); # do not compile into Cpanel::HttpRequest, but require it here for updatenow.static
# use Cpanel::Exception ();
# use Cpanel::FileUtils::Move ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::HttpRequest ();
# use Cpanel::LoadModule ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeDir::RM ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::Sync::Common (); # do not remove, required for Cpanel::HttpRequest on new installs
# use Cpanel::Sys::Hardware::Memory ();
# use Cpanel::Sys::Hardware::Memory::Linux (); # included for fresh installs so it ends up in .static (see case 184689)
# use Cpanel::Sys::Hardware::Memory::Vzzo (); # included for fresh installs so it ends up in .static (see case 184689)
# use Cpanel::TempFile ();
# use Cpanel::Update::Logger ();
use Fcntl ();
use File::Basename ();
use File::Copy ();
use File::Spec ();
use IO::Handle ();
use Try::Tiny;
our $VERSION = '4.02';
our $MAX_NUM_SYNC_CHILDREN = 1;
our $MAX_NUM_SYNC_CHILDREN_WITHOUT_FAST_UPDATE = 1;
our $MAX_NUM_SYNC_CHILDREN_WITH_FAST_UPDATE = 4;
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';
our $FAST_UPDATE_FORCED_ON_FLAG_FILE = '/var/cpanel/has_fast_update_on_lan';
our $LISC_FILE = '/usr/local/cpanel/cpanel.lisc';
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 { '/etc/cpanelsync.exclude' }
sub cpanelsync_chmod_exclude_file { '/etc/cpanelsync.no_chmod' }
sub new {
my $class = shift or die;
my $args = shift or die;
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::MD5; $args->{'hasmd5'} = 1 };
eval { require Digest::SHA; $args->{'hassha'} = 1 };
eval { require Cpanel::IO::Mmap::Read; $args->{'hasmmap'} = 1; };
my @required_binaries = qw/bzip2 lsattr md5sum 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->{'allow_weak_checksums'} = $conf->{'allow_weak_checksums'};
$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;
$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'} = {};
if ( defined $args->{'shared_list'} ) {
$self->{'shared_list'} = $args->{'shared_list'};
$self->{'shared_list'}->add_v2_object($self);
}
return $self;
}
sub _create_http_client {
my ($self) = @_;
my %opts = (
'die_on_404' => 1,
'retry_dns' => 0,
'hideOutput' => $self->{'http_verbose'} ? 0 : 1,
'logger' => $self->{'logger'},
'announce_mirror' => 1,
);
return Cpanel::HttpRequest->new(%opts);
}
sub _get_excludes {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $file = shift 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 { @{ $_[0]->{'source'} } }
sub logger {
my $self = shift or die;
return $self->{'logger'};
}
sub get_hash {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $file = shift or die; # The normalized path.
my $relative_path = shift or die; # The path as listed in the .cpanelsync file. (./cpanel)
my $digest = shift || 'sha'; # Allow caller to specify a hashing algo, default to sha
my $use_cache = shift || $USE_HASH_CACHE;
my $file_info = $self->get_target_info($file);
return '' if $digest eq 'md5' && !$self->{'allow_weak_checksums'};
return '' if !$file_info->{'exists'};
return '' if $file_info->{'islnk'};
return '' if !$file_info->{'isnormfile'};
return '' if !$file_info->{'mtime'};
$relative_path =~ s/\.cpanelsync\.nodecompress$//;
$self->{'digest_lookup'}->{$relative_path} ||= {};
my $digest_cache = $self->{'digest_lookup'}->{$relative_path};
if (
$use_cache == $USE_HASH_CACHE
&& ( ( $digest eq 'md5' && $digest_cache->{'md5'} ) || ( $digest eq 'sha' && $digest_cache->{'sha'} ) ) # Skip cache if no md5 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 eq 'sha' ? $digest_cache->{'sha'} : $digest_cache->{'md5'};
}
my $hash;
if ( $digest eq 'sha' ) {
$hash = $self->{'hassha'} ? $self->_get_checksum_lib( $digest, $file, $file_info->{'size'} ) : $self->_get_checksum_binary( $digest, $file );
@{$digest_cache}{ 'size', 'mtime', 'sha', 'used' } = ( $file_info->{'size'}, $file_info->{'mtime'}, $hash, 1 );
}
elsif ( $digest eq 'md5' ) {
$hash = $self->{'hasmd5'} ? $self->_get_checksum_lib( $digest, $file, $file_info->{'size'} ) : $self->_get_checksum_binary( $digest, $file );
@{$digest_cache}{ 'size', 'mtime', 'md5', 'used' } = ( $file_info->{'size'}, $file_info->{'mtime'}, $hash, 1 );
}
return $hash;
}
sub _get_checksum_binary {
my ( $self, $digest, $file ) = @_;
my $bin = $digest eq 'sha' ? '/usr/bin/sha512sum' : '/usr/bin/md5sum';
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 {
my ( $self, $digest, $file, $size ) = @_;
my $ctx = $digest eq 'sha' ? Digest::SHA->new(512) : Digest::MD5->new();
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'` ); #give more debug info
$self->{'logger'}->set_need_notify();
return '';
}
return $hash;
}
sub parse_new_cpanelsync_files {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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;
open( my $sync_fh, '<', $temp_sync_file ) or die("Cannot open $temp_sync_file for read");
while ( my $line = <$sync_fh> ) {
chomp($line);
my ( $rtype, $rfile, $rperm, $rextra, $sha ) = split( /===/, $line, 5 );
next if $rtype =~ m/^\s*\.\s*$/ || !$rtype;
$rperm = sprintf( '%04d', $rperm );
my $key = $self->normalize_syncfile_path($rfile);
$sync{$key} = {
'file' => $rfile,
'type' => $rtype,
'perm' => $rperm,
'extra' => $rextra,
'sha' => $sha,
};
}
close $sync_fh;
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 {
my $self = shift;
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path = shift or die;
return if !$self->{'source_data'}->{'excludes'};
return $self->syncfile_path_is_excluded( $path, $self->{'source_data'}->{'excludes'} );
}
sub is_excluded_chmod {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path = shift or die;
return if !$self->{'source_data'}->{'chmod_excludes'};
return $self->syncfile_path_is_excluded( $path, $self->{'source_data'}->{'chmod_excludes'} );
}
sub commit_directories {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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'} or $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->{'path'} );
}
}
}
$self->{'logger'}->info("All directories created and updated");
return 1;
}
sub commit_files {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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'`);
$self->{'logger'}->debug(`ls -ld '$commit_path'`);
$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
}
}
sub handle_symlinks {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
for my $source ( $self->get_source_list() ) {
my $cpanelsync_data = $self->{'source_data'}->{'sync_file_data'}->{$source};
foreach my $path ( keys %$cpanelsync_data ) {
my $target_info = $self->get_target_info( $self->_convert_path_to_ulc($path) );
my $cpanelsync_file = $cpanelsync_data->{$path};
next if ( !$cpanelsync_file->{'type'} or $cpanelsync_file->{'type'} ne 'l' );
my $link_to = $cpanelsync_file->{'extra'};
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();
}
}
}
}
sub validate_file_permissions {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$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};
foreach my $full_path ( keys %$cpanelsync_data ) {
my $target_info = $self->get_target_info( $self->_convert_path_to_ulc($full_path) );
next if ( !$target_info->{'exists'} );
$self->chmod( $cpanelsync_data->{$full_path}->{'perm'}, $target_info->{'path'} );
}
}
}
sub is_file_immutable {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $file = shift or die;
my $attr = `/usr/bin/lsattr $file`;
return 1 if ( $attr =~ m/^\s*\S*[ai]/ );
return;
}
sub get_target_info {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $normalized_path = shift or die;
my %target = ( 'path' => $normalized_path );
my @_lstat = lstat( $target{'path'} );
@target{ 'perm', 'uid', 'gid', 'size', 'mtime' } = @_lstat[ 2, 4, 5, 7, 9 ];
$target{'exists'} = $target{'perm'} ? 1 : undef;
$target{'isdir'} = $target{'exists'} ? Fcntl::S_ISDIR( $target{'perm'} ) : undef;
$target{'isnormfile'} = $target{'exists'} ? Fcntl::S_ISREG( $target{'perm'} ) : undef;
$target{'islnk'} = 0;
if ( $target{'exists'} && Fcntl::S_ISLNK( $target{'perm'} ) ) {
$target{'islnk'} = 1;
$target{'isdir'} = 0;
$target{'isnormfile'} = 0;
}
foreach my $key (qw/uid gid/) {
$target{$key} = -1 unless defined $target{$key};
}
return \%target;
}
sub _convert_path_to_ulc {
my ( $self, $path ) = @_;
if ( defined $path ) {
$path =~ s/^$self->{'staging_dir'}/$self->{'ulc'}/ if defined $self->{'staging_dir'};
$path =~ s/$self->{'stage_suffix'}$// if defined $self->{'stage_suffix'};
}
return $path;
}
sub _convert_path_to_staging {
my ( $self, $path ) = @_;
$path =~ s/^$self->{'ulc'}/$self->{'staging_dir'}/;
return $path;
}
sub create_dot_new_file {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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";
}
close($new_fh);
}
sub init_current_digest_cache {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->{'digest_lookup'} = {};
return if ( $self->{'force'} );
unlink("$self->{'syncto'}/.cpanelsync.md5") if -f "$self->{'syncto'}/.cpanelsync.md5";
my $digest_file = "$self->{'syncto'}/.cpanelsync.digest";
return if ( !-e $digest_file ); # No MD5 is fine.
my $digest_fh;
unless ( open( $digest_fh, '<', $digest_file ) ) {
$self->{'logger'}->fatal("Could not open '$digest_file' for reading: $!");
die("Cannot continue without reading $digest_file");
}
$self->{'logger'}->info("Loading digest cache from $self->{'syncto'}/.cpanelsync.digest");
while (<$digest_fh>) {
chomp();
my ( $filename, $size, $mtime, $md5, $sha ) = split( /:::/, $_, 5 );
$self->{'digest_lookup'}{$filename} = {
'size' => $size,
'mtime' => $mtime,
'md5' => $md5,
'sha' => $sha,
};
}
close($digest_fh);
}
sub save_updated_digest_data {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $digest_file = "$self->{'syncto'}/.cpanelsync.digest";
my $digest_fh;
unless ( open( $digest_fh, '>', $digest_file ) ) {
$self->{'logger'}->fatal("Could not open '$digest_file' for writing: $!");
die("Cannot continue without writing $digest_file");
}
foreach my $relative_path ( sort keys %{ $self->{'digest_lookup'} } ) {
next if ( !$self->{'digest_lookup'}{$relative_path}{'used'} ); # Don't save the cache of a file we didn't use this time around
next if ( !defined $self->{'digest_lookup'}{$relative_path}{'size'} ); # Don't save if size is undefined
next if ( !$self->{'digest_lookup'}{$relative_path}{'mtime'} ); # Don't save if mtime is false
next if ( !$self->{'digest_lookup'}{$relative_path}{'sha'} && !$self->{'digest_lookup'}{$relative_path}{'md5'} ); # Don't' save if no hash
my $cache_str = join(
':::',
$relative_path,
$self->{'digest_lookup'}{$relative_path}{'size'},
$self->{'digest_lookup'}{$relative_path}{'mtime'}
);
$cache_str .= ":::";
if ( $self->{'digest_lookup'}{$relative_path}{'md5'} ) {
$cache_str .= $self->{'digest_lookup'}{$relative_path}{'md5'};
}
$cache_str .= ":::";
if ( $self->{'digest_lookup'}{$relative_path}{'sha'} ) {
$cache_str .= $self->{'digest_lookup'}{$relative_path}{'sha'};
}
$cache_str .= "\n";
print {$digest_fh} $cache_str;
}
close($digest_fh);
}
sub normalize_syncfile_path {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path_from_syncfile = shift or croak '[ARGUMENT] path_from_syncfile must be specified';
$path_from_syncfile =~ s{/+$}{};
$path_from_syncfile =~ s{\Q.cpanelsync.nodecompress\E$}{};
if ( $path_from_syncfile =~ m/^\./ ) {
$path_from_syncfile =~ s/^\./$self->{'syncto'}/eo;
}
return $path_from_syncfile;
}
sub syncfile_path_is_excluded {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path = shift or die;
my $normalized_exclude_lookup_hr = shift 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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $plaintext_octal_perms = shift || 0;
my $full_path = shift or die;
my $check_exclusions = !( shift @_ );
my $file_info = $self->get_target_info($full_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;
}
$self->{'logger'}->info("Set permissions on $full_path to $plaintext_octal_perms");
return 1;
}
sub chown {
my ( $self, $uid, $gid, $full_path ) = @_;
ref $self eq __PACKAGE__ or die("must be called as a method");
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path = shift or die;
my $file_name;
while ( ( $file_name, $path ) = File::Basename::fileparse($path) ) {
$path =~ s{/+$}{}; # Strip off the trailing slash from the path.
return 2 if ( length($path) < length( $self->_convert_path_to_ulc( $self->{'syncto'} ) ) );
return if ( $path eq $self->_convert_path_to_ulc( $self->{'syncto'} ) );
return 1 if ( -l $path ); # Something along the path to this file is a symlink.
}
return 2;
}
sub handle_removed_files {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my @source_list = $self->get_source_list();
my @files_to_remove;
my @directories_to_remove;
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 _ );
my $fh;
unless ( open( $fh, "<", $sync_file ) ) {
$self->{'logger'}->fatal("Could not open '$sync_file' for reading: $!");
die("Cannot proceed.");
}
handle_removed_files_next_syncfile:
while ( my $line = <$fh> ) {
chomp $line;
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);
my $ulc_path = $self->_convert_path_to_ulc($path);
next if $self->symlink_in_path($ulc_path);
next if $self->is_excluded($ulc_path);
my @shared_list = $self;
push @shared_list, $self->{'shared_list'}->get_v2_list( 'skip' => $self )
if defined $self->{'shared_list'};
foreach my $v2 (@shared_list) {
my $syncdata = $v2->{'source_data'}->{'sync_file_data'};
my $found = grep { $syncdata->{$_}->{$path} || ( $path =~ m/\.(bz2|t?gz|xz)$/i && $syncdata->{$_}->{"$path.cpanelsync.nodecompress"} ) } $v2->get_source_list();
next handle_removed_files_next_syncfile if $found;
}
if ( !-l $ulc_path && -d _ ) {
push @directories_to_remove, $ulc_path;
}
else {
push @files_to_remove, $ulc_path;
}
}
}
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");
rmdir($path);
if ( -d $path ) {
if ( ( stat(_) )[3] > 2 ) { # ? or if (3rd readdir()) { ?
$self->{'logger'}->warning("'$path' is not empty, not removing.");
}
else {
$self->{'logger'}->warning("Could not remove directory '$path': $!");
}
}
}
}
sub fetch_file {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $download_to = shift or die;
my $source_path = shift or die;
my $file_info = shift or die;
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 $hash_type = $file_info->{'sha'} ? 'sha' : 'md5';
my $cached_hash = $hash_type eq 'sha' ? $file_info->{'sha'} : $file_info->{'extra'};
if ( !$file_info->{'nochecksum'} && !$file_info->{'sha'} && !$self->{'allow_weak_checksums'} ) {
$self->{'logger'}->error("No sha512 digest found, and not accepting weak checksums!");
die("No sha512 digest found, and not accepting weak checksums!");
}
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 .= ".$Cpanel::HttpRequest::COMPRESSION{'extension'}";
}
}
$self->{'logger'}->info("Retrieving and staging $real_source_path");
my $is_disk_full;
my $total_attempts = 10;
$self->{'http_client'} ||= $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->{'extra'} || $file_info->{'sha'} ) {
my $check_hash = $self->get_hash( $download_to, $file_info->{'file'}, $hash_type, $IGNORE_HASH_CACHE );
if ( $hash_type eq 'sha' && $check_hash eq $file_info->{'sha'} ) {
$self->{'logger'}->debug("Got file $download_to ok (sha512 matches)");
}
elsif ( $hash_type eq 'md5' && $check_hash eq $file_info->{'extra'} ) {
$self->{'logger'}->debug("Got file $download_to ok (md5 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 {
my ( $self, $download_to, $file_info ) = @_;
if ( ( $file_info->{'sha'} && $self->get_hash( $download_to, $file_info->{'file'}, 'sha', $USE_HASH_CACHE ) eq $file_info->{'sha'} )
|| ( $self->{'allow_weak_checksums'} && $file_info->{'extra'} && $self->get_hash( $download_to, $file_info->{'file'}, 'md5', $USE_HASH_CACHE ) eq $file_info->{'extra'} ) ) {
$self->{'logger'}->debug("$download_to already downloaded");
return 1;
}
return 0;
}
sub _df {
my ($path) = @_;
$path ||= '';
my @output = `/bin/df -PB1 $path 2>&1`;
return @output;
}
sub is_disk_full {
my ($self) = @_;
$self or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my @disk_space = _df( $self->{'syncto'} );
return 0 if ( $? || scalar @disk_space != 2 );
return 0 if ( !$disk_space[1] or $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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $download_into = shift or die;
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 {
my ( $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 {
my ( $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 {
my ( $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 _check_for_symlinked_parents {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $path_to_check = shift;
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $source_path = shift or die; # The URL after hostname for what we want to download (might be minus the .bz2)
my $download_into = shift 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)
my $file_info = shift or die; # The cpanelsync hash data.
my $staged_dir = shift || $self->stage_directory($download_into);
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, $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'}, $stage_path );
}
return $stage_path;
}
sub get_staged_file {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $file = shift 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 {
my ( $self, $source ) = @_;
ref $self eq __PACKAGE__ or die("must be called as a method");
die("no source provided") unless $source;
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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return $self if $self->{'already_ran_stage_cpanelsync_files'};
for my $source ( $self->get_source_list() ) {
$self->stage_file( "/$source/$self->{'sync_basename'}", $self->get_local_cpanelsync_file_name($source), { 'perm' => '0644', 'signed' => 1, 'nochecksum' => 1 } );
}
$self->{'already_ran_stage_cpanelsync_files'} = 1;
return $self;
}
sub stage {
my ( $self, %opts ) = @_;
ref $self eq __PACKAGE__ or die("stage must be called as a method");
$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 ( keys %$cpanelsync_data ) {
( my $path_modified = $path ) =~ s/\.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;
}
next if ( $cpanelsync_data->{$path}->{'type'} ne 'f' );
if ( $cpanelsync_data->{$path}->{'sha'} && $self->get_hash( $file_info_in_ulc->{'path'}, $cpanelsync_data->{$path}->{'file'}, 'sha', $USE_HASH_CACHE ) eq $cpanelsync_data->{$path}->{'sha'} ) {
next;
}
elsif ( $cpanelsync_data->{$path}->{'extra'} && $self->{'allow_weak_checksums'} && $self->get_hash( $file_info_in_ulc->{'path'}, $cpanelsync_data->{$path}->{'file'}, 'md5', $USE_HASH_CACHE ) eq $cpanelsync_data->{$path}->{'extra'} ) {
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 {
my ( $self, $files_to_stage_by_child_ref ) = @_;
ref $self eq __PACKAGE__ or die("stage must be called as a method");
$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 {
my ($self) = @_;
while ( scalar keys %{ $self->{'sync_children'} } ) {
my $child_pid = waitpid( -1, 0 );
last if $child_pid == -1;
next if $child_pid == 0;
if ( $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 $/;
if ( $INC{'Cpanel/JSON.pm'} && $INC{'JSON/XS.pm'} ) {
$child_data = ( Cpanel::JSON::Load( readline($fh) ) )[0];
}
elsif ( $INC{'Cpanel/YAML.pm'} && $INC{'YAML/Syck.pm'} ) {
$child_data = ( Cpanel::YAML::Load( readline($fh) ) )[0];
}
else {
$child_data = ( Cpanel::CPAN::YAML::Tiny::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: $!";
}
}
}
delete $self->{'sync_children_temp_obj'};
delete $self->{'sync_children'};
return 1;
}
sub _create_sync_children {
my ( $self, $files_to_stage_by_child_ref ) = @_;
$self->{'sync_children_temp_obj'} = Cpanel::TempFile->new();
$self->{'sync_children'} = {};
my $NUM_SYNC_CHILDREN = scalar keys %{$files_to_stage_by_child_ref};
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 ) {
$self->{'http_client'} = undef;
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, #
( $INC{'Cpanel/JSON.pm'} && $INC{'JSON/XS.pm'} ) ? Cpanel::JSON::Dump( { 'staged_files' => $self->{'staged_files'}, 'digest_lookup' => $self->{'digest_lookup'} } ) #
: ( $INC{'Cpanel/YAML.pm'} && $INC{'YAML/Syck.pm'} ) ? Cpanel::YAML::Dump( { 'staged_files' => $self->{'staged_files'}, 'digest_lookup' => $self->{'digest_lookup'} } ) #
: Cpanel::CPAN::YAML::Tiny::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 {
my ($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 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
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 install_rpm_versions {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
local $self->{'staged_files'} = {};
local $self->{'staged_directories'} = {};
my $target = $self->{'syncto'} . '/etc/rpm.versions';
$self->stage_file( "/cpanel/etc/rpm.versions", $target, { 'file' => './etc/rpm.versions', 'perm' => '0640' } );
$self->commit_directories();
$self->commit_files();
return 1;
}
sub sync_updatenow_static {
my ( $self, $skip_signature_check ) = @_;
die("must be called as a method") unless ( defined $self && ref $self eq __PACKAGE__ );
if ( !-d $self->{'syncto'} ) {
Cpanel::SafeDir::MK::safemkdir( $self->{'syncto'}, 0711 );
Cpanel::SafeDir::MK::safemkdir( $self->{'syncto'} . '/scripts', 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 } );
return $self->get_staged_file($target);
}
sub _calculate_stage_path_and_temp_file_from_stage_file {
my ( $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 get_max_num_client {
my ($self) = @_;
return $MAX_NUM_SYNC_CHILDREN_WITHOUT_FAST_UPDATE unless $self->_can_use_fastupdate();
return $MAX_NUM_SYNC_CHILDREN_WITH_FAST_UPDATE if !_is_cpanel_first_install();
return $MAX_NUM_SYNC_CHILDREN if $MAX_NUM_SYNC_CHILDREN;
my $grep = Cpanel::FindBin::findbin('grep') or die "Cannot find grep binary.";
my $cpu = Cpanel::SafeRun::Simple::saferunnoerror( $grep, '-c', '^processor', '/proc/cpuinfo' );
chomp($cpu) if $cpu;
$cpu ||= 1;
$MAX_NUM_SYNC_CHILDREN = 4 * int($cpu);
$MAX_NUM_SYNC_CHILDREN = 16 if $MAX_NUM_SYNC_CHILDREN > 16;
return $MAX_NUM_SYNC_CHILDREN;
}
sub _calculate_max_sync_children {
my ($self) = @_;
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;
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 DESTROY {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return if $self->{'master_pid'} && $self->{'master_pid'} != $$;
if ( defined $self && defined $self->{'shared_list'} ) {
$self->{'shared_list'}->remove_v2_object($self);
$self->{'shared_list'} = undef;
}
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 );
}
}
}
sub _can_use_fastupdate {
my ($self) = @_;
if ( !-e $FAST_UPDATE_NEVER_EVER_FLAG_FILE ) {
return 1 if $self->_is_test_build();
return 1 if $self->_is_cpanel_first_install();
return 1 if $self->_fastupdate_is_manually_forced_on();
return 1 if $self->_current_partner_id_has_local_fastupdate();
}
return 0;
}
sub _current_partner_id_has_local_fastupdate {
my ($self) = @_;
if ( open( my $lisc_fh, '<', $LISC_FILE ) ) {
while ( readline($lisc_fh) ) {
if (m{cid=7,}) { return 1; }
elsif (m{^[\r\n]*$}) { last; }
}
}
elsif ( !$!{'ENOENT'} ) {
$self->{'logger'}->warn("The system failed to open “$LISC_FILE” for reading because of an error: $!");
}
return 0;
}
sub _fastupdate_is_manually_forced_on {
return -e $FAST_UPDATE_FORCED_ON_FLAG_FILE ? 1 : 0;
}
sub _is_cpanel_first_install {
return $ENV{'CPANEL_BASE_INSTALL'} ? 1 : 0;
}
sub _is_test_build {
my ($self) = @_;
if ( $self->{'host'} =~ m{^(?:branch-build|next|qa-build)\.} ) {
return 1;
}
return 0;
}
1;
} # --- END Cpanel/Sync/v2.pm
{ # --- BEGIN Cpanel/Sync/v2_shared_list.pm
package Cpanel::Sync::v2_shared_list;
use strict;
use Carp;
sub new {
my ($class) = shift;
my $self = {
'v2_list' => [],
};
return bless $self, $class;
}
sub add_v2_object {
my ( $self, $p_v2 ) = @_;
croak '[ARGUMENT] you must provide a v2 object'
if !$p_v2 || ref($p_v2) ne 'Cpanel::Sync::v2';
push @{ $self->{'v2_list'} }, $p_v2;
return $self;
}
sub get_v2_list {
my $self = shift;
return @{ $self->{'v2_list'} };
}
sub remove_v2_object {
my ( $self, $p_v2 ) = @_;
croak '[ARGUMENT] you must provide a v2 object'
if !$p_v2 || ref($p_v2) ne 'Cpanel::Sync::v2';
my $count = @{ $self->{'v2_list'} };
@{ $self->{'v2_list'} } = grep { $_ && $_ ne $p_v2 } @{ $self->{'v2_list'} };
croak '[ARGUMENT] provided v2 object was not in shared list'
if scalar @{ $self->{'v2_list'} } != $count;
return $self;
}
1
} # --- END Cpanel/Sync/v2_shared_list.pm
{ # --- BEGIN Cpanel/IP/Parse.pm
package Cpanel::IP::Parse;
use strict;
# use Cpanel::IP::Convert ();
our $BRACKET_IPV6 = 1;
sub parse {
my ( $ipdata, $port, $flags ) = @_;
my ( $ip, $version, $parsed_port );
if ( $ipdata =~ tr/*// ) {
( $ip, $parsed_port ) = split( /:/, $ipdata, 2 );
$version = 4; #default to 4
}
elsif ( $ipdata =~ tr/\.// && ( $ipdata =~ tr/:// ) >= 2 ) { #ipv4 embedded in ipv6
$ipdata =~ tr/[]//d;
$ipdata =~ s/^\(null\)/0000/;
$version = 4;
( $ip, $parsed_port ) = $ipdata =~ /:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):?([0-9]*)$/;
}
elsif ( $ipdata =~ tr/\[// ) { #ipv6
$ipdata =~ s/^\(null\)/0000/;
$version = 6;
if ( $ipdata =~ m/]:/ ) {
( $ip, $parsed_port ) = split( /]/, $ipdata, 2 );
$ip =~ tr/[//d;
$parsed_port =~ tr/://d;
$ip = Cpanel::IP::Convert::expand_ip($ip);
}
else {
$ipdata =~ tr/[]//d;
$ip = Cpanel::IP::Convert::expand_ip($ipdata);
}
}
elsif ( $ipdata =~ tr/\.// ) { #ipv4
$ipdata =~ s/^\(null\)/0.0.0.0/;
$version = 4;
( $ip, $parsed_port ) = split( /:/, $ipdata, 2 );
}
elsif ( ( $ipdata =~ tr/:// ) == 1 || $ipdata eq '(null)' || $ipdata =~ /^\(null\):\d+$/ ) { #empty
$version = 4;
($parsed_port) = ( split( /:/, $ipdata, 2 ) )[1];
$ip = '0.0.0.0';
}
else { #default to ipv6
$ipdata =~ s/^\(null\)/0000/;
$version = 6;
if ( ( $ipdata =~ tr/:// ) >= 8 ) {
my @split_ip = split( /:/, $ipdata );
$parsed_port = pop @split_ip;
$ip = Cpanel::IP::Convert::expand_ip( join( ':', @split_ip ) );
}
else {
$ip = Cpanel::IP::Convert::expand_ip($ipdata);
}
}
if ($parsed_port) { $port = $parsed_port; }
$ip = '[' . $ip . ']' if $version == 6 && $flags && ( $flags & $BRACKET_IPV6 );
return ( $version, $ip, $port );
}
1;
} # --- END Cpanel/IP/Parse.pm
{ # --- BEGIN Cpanel/Config/Httpd.pm
package Cpanel::Config::Httpd;
use strict;
# use Cpanel::CachedCommand ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::ConfigFiles::Apache 'apache_paths_facade';
INIT { Cpanel::ConfigFiles::Apache->import(qw{apache_paths_facade}); }
# use Cpanel::IP::Parse ();
our $CPANEL_ROOT = '/usr/local/cpanel';
our $PRODUCT_CONF_DIR = '/var/cpanel';
our $SYSTEM_RUN_DIR = '/var/run';
my $DEFAULT_IP = '0.0.0.0';
sub get_message_if_apache_is_building {
my ($specific) = @_;
if ( -e apache_paths_facade->dir_base() . "/AN_EASYAPACHE_BUILD_IS_CURRENTLY_RUNNING" || ( !-e httpd_binary_location() && -e "$SYSTEM_RUN_DIR/easyapache.pid" ) ) {
return <<EA3_RUNNING;
<p>EasyApache is currently upgrading your Apache and PHP installation.</p>
<p>$specific</p>
EA3_RUNNING
}
}
sub get_main_httpd_port {
_fetch_http_port( 'cpconfkey' => 'apache_port', 'default_port' => 80 );
}
sub get_ssl_httpd_port {
_fetch_http_port( 'cpconfkey' => 'apache_ssl_port', 'default_port' => 443 );
}
sub get_main_httpd_ip_and_port {
_fetch_http_ip_and_port( 'cpconfkey' => 'apache_port', 'default_port' => 80 );
}
sub get_ssl_httpd_ip_and_port {
_fetch_http_ip_and_port( 'cpconfkey' => 'apache_ssl_port', 'default_port' => 443 );
}
sub _fetch_http_ip_and_port {
my %OPTS = @_;
my $cpconf = Cpanel::Config::LoadCpConf::loadcpconf_not_copy(); # safe since we never modify cpconf
my $main_port = $cpconf->{ $OPTS{'cpconfkey'} } || $OPTS{'default_port'};
if ( $main_port =~ m/^[0-9]+$/ ) {
$main_port = "0.0.0.0:$main_port";
}
return $main_port;
}
sub _fetch_http_port {
my %OPTS = @_;
my $ip_and_port = _fetch_http_ip_and_port(%OPTS);
my $port = ( Cpanel::IP::Parse::parse($ip_and_port) )[2];
return ( $port && $port =~ m/^[0-9]+/ ) ? $port : $OPTS{'default_port'};
}
sub is_ea4 {
return -e "/etc/cpanel/ea4/is_ea4" ? 1 : 0;
}
sub is_ea3 {
return httpd_was_built_by_ea3() && system_has_ea3_available() ? 1 : 0;
}
sub httpd_was_built_by_ea3 {
if ( -e "$PRODUCT_CONF_DIR/httpd_was_built_by_ea3" ) { return 1; }
my $httpd_v = Cpanel::CachedCommand::cachedcommand( httpd_binary_location(), '-v' );
if ( $httpd_v =~ m{Cpanel\:\:Easy\:\:Apache v(\S+) rev(\S+) [(]([^)]+)[)]} ) {
return wantarray ? ( $1, $2, $3 ) : 1;
}
elsif ( $httpd_v =~ m{Cpanel\:\:Easy\:\:Apache v(\S+) rev(\S+)} ) {
return wantarray ? ( $1, $2, 'public branch' ) : 1;
}
else {
return;
}
}
sub system_has_ea3_available {
return 0 if is_ea4();
open my $ea_fh, '<', "$CPANEL_ROOT/scripts/easyapache" or return;
while ( my $line = readline($ea_fh) ) {
if ( $line =~ m{Cpanel\:\:Easy\:\:Apache} ) {
close $ea_fh;
return 1;
}
}
return;
}
sub default_cpanel_dir {
$CPANEL_ROOT = shift if @_;
return $CPANEL_ROOT;
}
sub default_httpd_dir {
my $HTTPD_BASE_DIR = shift;
return ( defined $HTTPD_BASE_DIR ) ? $HTTPD_BASE_DIR : apache_paths_facade->dir_base();
}
sub default_product_dir {
$PRODUCT_CONF_DIR = shift if @_;
return $PRODUCT_CONF_DIR;
}
sub default_run_dir {
$SYSTEM_RUN_DIR = shift if @_;
return $SYSTEM_RUN_DIR;
}
sub httpd_vendor_info {
if ( -r '/usr/local/lsws/VERSION' ) {
return ( 'litespeed', Cpanel::LoadFile::loadfile('/usr/local/lsws/VERSION') );
}
my ($http_v) = httpd_was_built_by_ea3();
if ($http_v) {
return ( 'easyapache', $http_v );
}
return ( 'unknown', 'unknown' );
}
sub httpd_binary_location {
my $dir = default_httpd_dir();
return $dir eq apache_paths_facade->dir_base() ? apache_paths_facade->bin_httpd() : default_httpd_dir() . '/bin/httpd';
}
sub suexec_binary_location {
my $dir = default_httpd_dir();
return $dir eq apache_paths_facade->dir_base() ? apache_paths_facade->bin_suexec() : default_httpd_dir() . '/bin/suexec';
}
sub splitlogs_binary_location {
return default_cpanel_dir() . '/bin/splitlogs';
}
1;
} # --- END Cpanel/Config/Httpd.pm
{ # --- BEGIN Cpanel/Parser/Line.pm
package Cpanel::Parser::Line;
use strict;
sub process_data {
my ( $self, $data ) = @_;
if ( length $self->{'_buffer'} ) {
substr( $data, 0, 0, $self->{'_buffer'} );
}
while ( $data =~ m/\n/ ) {
$self->process_line( substr( $data, 0, $+[0], '' ) ) || 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 ( $data =~ m/\n/ ) {
$self->process_error_line( substr( $data, 0, $+[0], '' ) ) || 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 Cpanel::Parser::Line ();
# use Cpanel::Parser::Line();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Parser::Line); }
sub new {
my ( $class, %OPTS ) = @_;
my $self = { 'success' => 0 };
return bless $self, $class;
}
sub process_error_line { ##no critic qw(RequireArgUnpacking)
return print STDERR $_[1];
}
sub output { ##no critic qw(RequireArgUnpacking)
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 ();
# use Cpanel::Parser::Base();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Parser::Base); }
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/Output.pm
package Cpanel::Output;
use strict;
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->_init() 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 syswrite(
$self->{'filehandle'},
Cpanel::JSON::Dump(
{
'pid' => $$,
'type' => $message_type,
'contents' => $msg_contents,
'partial' => $partial_message ? $PARTIAL_MESSAGE : $COMPLETE_MESSAGE,
( $source ? ( 'source' => $source ) : () )
}
)
. "\n"
);
}
sub error {
my ( $self, @args ) = @_;
return $self->message( 'error', @args );
}
sub warn {
my ( $self, @args ) = @_;
return $self->message( 'warn', @args );
}
sub success {
my ( $self, @args ) = @_;
return $self->message( 'success', @args );
}
sub out {
my ( $self, @args ) = @_;
return $self->message( 'out', @args );
}
*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 reset_indent_level {
my ($self) = @_;
return ( $self->{'_indent_level'} = 0 );
}
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/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 $fixed_txt;
if ( defined $length ) {
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;
}
if ( Cpanel::UTF8::char_count($fixed_txt) < $length ) {
my $padding = " " x ( $length - Cpanel::UTF8::char_count($fixed_txt) );
if ( $align && $align == $ALIGN_RIGHT ) {
substr( $fixed_txt, 0, 0, $padding );
}
else {
$fixed_txt .= $padding;
}
}
return $fixed_txt;
}
1;
} # --- END Cpanel/StringFunc/Fmt.pm
{ # --- BEGIN Cpanel/Output/Formatted.pm
package Cpanel::Output::Formatted;
use strict;
# use Cpanel::Output();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Output); }
# use Cpanel::StringFunc::Fmt ();
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 {
my ( $self, $message_type, $msg_contents, $source, $partial_message, $prepend_message ) = @_;
my $message_as_text = ref $msg_contents ? $msg_contents->{'msg'} : $msg_contents;
if ( $message_type eq 'failed' || $message_type eq 'fail' || $message_type eq 'error' ) {
$self->_safe_render_message( $message_as_text, 'bold black on_red', $partial_message, $prepend_message );
}
elsif ( $message_type eq 'warn' ) {
$self->_safe_render_message( $message_as_text, 'bold black on_yellow', $partial_message, $prepend_message );
}
elsif ( $message_type eq 'success' ) {
$self->_safe_render_message( $message_as_text, 'bold green', $partial_message, $prepend_message );
}
elsif ( $message_type eq 'header' ) {
$self->_safe_render_message( $message_as_text, 'bold', $partial_message, $prepend_message );
}
elsif ( $message_type eq 'out' ) {
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 {
my ( $self, $color, $message ) = @_;
$color = '' if !$color;
return $self->_format_text( $color, $message );
}
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 = ( $msg =~ m{\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() : '' );
$output .= ( $prepend_message ? $self->_prepend_message() : q{} );
$output .= $self->format_message( $color, $lines[$count] );
$output .= ( $count <= $last_line_to_add_new_line ? $self->_new_line() : q{} );
if ( $self->{'_parent'} ) {
my $pid = $self->{'_parent'}{'pid'};
my $queue = $self->{'_parent'}{'contents'}{'queue'};
my $child_number = $self->{'_parent'}{'contents'}{'child_number'};
my $item_name = $self->{'_parent'}{'contents'}{'item_name'};
my $item = $self->{'_parent'}{'contents'}{'item'};
my $pid_info = Cpanel::StringFunc::Fmt::fixed_length( $pid, 6, $Cpanel::StringFunc::Fmt::ALIGN_RIGHT );
my $job_info = Cpanel::StringFunc::Fmt::fixed_length( "$queue:$child_number", 10 );
my $item_info = Cpanel::StringFunc::Fmt::fixed_length( "$item_name", 1 );
my $item_formatted = 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;
}
sub _prepend_message {
return q{};
}
1;
} # --- END Cpanel/Output/Formatted.pm
{ # --- BEGIN Cpanel/Terminal.pm
package Cpanel::Terminal;
use strict;
# use Cpanel::Autodie ();
# use Cpanel::ChildErrorStringifier ();
# use Cpanel::ForkAsync ();
# use Cpanel::ReadMultipleFH ();
my $INFOCMP_BIN = '/usr/bin/infocmp';
my @KNOWN_TERMINAL_MAX_COLORS = (
'xterm-256color' => 256,
'xterm-24' => 256,
);
my %cached_max_colors = (@KNOWN_TERMINAL_MAX_COLORS);
our $_cached_stdin_is_tty;
our $_cached_EXECUTABLE_NAME_is_cpanel_perl;
sub _init {
$_cached_stdin_is_tty = undef;
$_cached_EXECUTABLE_NAME_is_cpanel_perl = undef;
}
if ( !${^GLOBAL_PHASE} || ${^GLOBAL_PHASE} eq 'START' ) {
eval q/INIT { _init() }/ ## no critic qw(ProhibitStringyEval)
}
else {
_init();
}
sub it_is_safe_to_colorize {
if ( !defined $_cached_stdin_is_tty ) {
$_cached_stdin_is_tty = -t STDIN;
}
if ($_cached_stdin_is_tty) {
if ( !defined $_cached_EXECUTABLE_NAME_is_cpanel_perl ) {
$_cached_EXECUTABLE_NAME_is_cpanel_perl = ( $^X =~ m{^/usr/local/cpanel/3rdparty/perl} );
}
return 1 if $_cached_EXECUTABLE_NAME_is_cpanel_perl;
}
return 0;
}
sub _run_infocmp_to_get_max_colors {
my ($term) = @_;
Cpanel::Autodie::pipe( my $rdr, my $wtr );
Cpanel::Autodie::pipe( my $erdr, my $ewtr );
my $pid = Cpanel::ForkAsync::do_in_child(
sub {
Cpanel::Autodie::close($rdr);
Cpanel::Autodie::close($erdr);
Cpanel::Autodie::open( \*STDOUT, '>&=', $wtr );
Cpanel::Autodie::open( \*STDERR, '>&=', $ewtr );
exec( $INFOCMP_BIN, '-L', '-1', $term ) or die "Failed to run $INFOCMP_BIN: $!";
}
);
Cpanel::Autodie::close($wtr);
Cpanel::Autodie::close($ewtr);
my $read_fhs = Cpanel::ReadMultipleFH->new(
filehandles => [ $rdr, $erdr ],
);
Cpanel::Autodie::close($rdr);
Cpanel::Autodie::close($erdr);
waitpid $pid, 0;
if ( ${ $read_fhs->get_buffer($rdr) } =~ m{max_colors\#(\d+)} ) {
return $1;
}
if ($?) {
my $err = Cpanel::ChildErrorStringifier->new( $?, $INFOCMP_BIN );
warn ${ $read_fhs->get_buffer($erdr) } . $err->autopsy();
}
return undef;
}
sub get_max_colors_for_terminal {
my ($term) = @_;
die "Need terminal!" if !length $term;
if ( exists $cached_max_colors{$term} ) {
return $cached_max_colors{$term};
}
my $max_colors = _run_infocmp_to_get_max_colors($term);
if ( !length $max_colors ) {
if ( $term =~ m{([0-9]+)color} ) {
$max_colors = $1;
}
}
$cached_max_colors{$term} = $max_colors;
return $max_colors;
}
1;
} # --- END Cpanel/Terminal.pm
{ # --- BEGIN Cpanel/Term/ANSIColor/Solarize.pm
package Cpanel::Term::ANSIColor::Solarize;
use strict;
use Term::ANSIColor ();
# use Cpanel::Terminal ();
our $_cached_palette_ref;
our $_cached_max_colors;
sub _init {
$_cached_palette_ref = undef;
$_cached_max_colors = undef;
}
if ( !${^GLOBAL_PHASE} || ${^GLOBAL_PHASE} eq 'START' ) {
eval q/INIT { _init() }/ ## no critic qw(ProhibitStringyEval)
}
else {
_init();
}
my %solarize256 = (
base03 => 'grey2',
base02 => 'grey3',
base01 => 'grey8',
base00 => 'grey9',
base0 => 'grey12',
base1 => 'grey13',
base2 => 'grey22',
base3 => 'rgb554',
yellow => 'rgb320',
orange => 'rgb410',
red => 'rgb400',
magenta => 'rgb301',
violet => 'rgb113',
blue => 'rgb025',
cyan => 'rgb033',
green => 'rgb120',
on_base03 => 'on_grey2',
on_base02 => 'on_grey3',
on_base01 => 'on_grey8',
on_base00 => 'on_grey9',
on_base0 => 'on_grey12',
on_base1 => 'on_grey13',
on_base2 => 'on_grey22',
on_base3 => 'on_rgb554',
on_yellow => 'on_rgb320',
on_orange => 'on_rgb410',
on_red => 'on_rgb400',
on_magenta => 'on_rgb301',
on_violet => 'on_rgb113',
on_blue => 'on_rgb025',
on_cyan => 'on_rgb033',
on_green => 'on_rgb120'
);
my %solarize16 = (
base03 => 'bright_black',
base02 => 'black',
base01 => 'bright_green',
base00 => 'bright_yellow',
base0 => 'bright_blue',
base1 => 'bold', # cyan looked really bad in transfer restores
base2 => 'white',
base3 => 'bright_white',
on_base03 => 'on_bright_black',
on_base02 => 'on_black',
on_base01 => 'on_bright_green',
on_base00 => 'on_bright_yellow',
on_base0 => 'on_bright_blue',
on_base1 => 'on_bright_cyan',
on_base2 => 'on_white',
on_base3 => 'on_bright_white',
violet => 'bright_magenta',
orange => 'bright_red',
);
my %solarize8 = (
base03 => 'black',
base02 => 'black',
base01 => 'green',
base00 => 'yellow',
base0 => 'blue',
base1 => 'cyan',
base2 => 'white',
base3 => 'white',
on_base03 => 'on_black',
on_base02 => 'on_black',
on_base01 => 'on_green',
on_base00 => 'on_yellow',
on_base0 => 'on_blue',
on_base1 => 'on_cyan',
on_base2 => 'on_white',
on_base3 => 'on_white',
violet => 'magenta',
orange => 'red',
);
sub colored {
my (@input) = @_;
_set_cached_palette_ref() if !defined $_cached_max_colors;
if ( ref $input[0] ) {
my $attr = shift @input;
return join( '', @input ) if !$_cached_max_colors || !Cpanel::Terminal::it_is_safe_to_colorize();
return Term::ANSIColor::colored( [ join( ' ', map { $_cached_palette_ref->{$_} || $_ } split( m{\s+}, $attr->[0] ) ) ], @input );
}
else {
my $string = shift @input;
return $string if !$_cached_max_colors || !Cpanel::Terminal::it_is_safe_to_colorize();
return Term::ANSIColor::colored( $string, map { $_cached_palette_ref->{$_} || $_ } @input );
}
}
sub _set_cached_palette_ref {
if ( !defined $_cached_max_colors ) {
$_cached_max_colors = $ENV{'TERM'} && Cpanel::Terminal::get_max_colors_for_terminal( $ENV{'TERM'} );
$_cached_max_colors ||= 0;
if ($_cached_max_colors) {
$_cached_palette_ref = $_cached_max_colors >= 256 ? \%solarize256 : $_cached_max_colors >= 16 ? \%solarize16 : \%solarize8;
}
}
return;
}
1;
} # --- END Cpanel/Term/ANSIColor/Solarize.pm
{ # --- BEGIN Cpanel/Output/Formatted/Terminal.pm
package Cpanel::Output::Formatted::Terminal;
use strict;
our $VERSION = '1.0';
# use Cpanel::Output::Formatted();
our @ISA;
BEGIN { push @ISA, qw(Cpanel::Output::Formatted); }
our $product_dir = '/var/cpanel';
eval {
local $SIG{'__DIE__'};
local $SIG{'__WARN__'};
require Cpanel::Term::ANSIColor::Solarize;
};
sub _new_line {
my ($self) = @_;
return "\n";
}
sub _indent {
my ($self) = @_;
return $self->{'_indent_level'} ? ( "\t" x $self->{'_indent_level'} ) : '';
}
sub _format_text {
my ( $self, $color, $text ) = @_;
if ( $INC{'Cpanel/Term/ANSIColor/Solarize.pm'} && $color && !$self->_disable_color() ) {
return Cpanel::Term::ANSIColor::Solarize::colored( [$color], $text );
}
return $text;
}
sub _disable_color {
if ( -e $product_dir . '/disable_cpanel_terminal_colors' ) {
return 1;
}
return 0;
}
1;
} # --- END Cpanel/Output/Formatted/Terminal.pm
{ # --- BEGIN Cpanel/SysPkgs/YUM.pm
package Cpanel::SysPkgs::YUM;
use strict;
use Try::Tiny;
# use Cpanel::SafeFile ();
# use Cpanel::FileUtils::Write ();
# use Cpanel::Fcntl::Constants ();
# use Cpanel::SafeRun::Errors ();
# use Cpanel::HttpRequest ();
# use Cpanel::Logger ();
# use Cpanel::Config::Httpd ();
# use Cpanel::Config::Sources ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::FindBin ();
# use Cpanel::CPAN::IO::Callback::Write ();
# use Cpanel::Parser::Callback ();
# use Cpanel::TempFile ();
# use Cpanel::Validate::FilesystemNodeName ();
# use Cpanel::Output::Formatted::Terminal ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::Config::Httpd ();
use IO::Handle;
our $VERSION = '22.3';
our $YUM_BIN = '/usr/bin/yum';
our $YUM_CONF = '/etc/yum.conf';
our $FORCE_DRY_RUN = 0; # For testing
our %setup_oses = (
'centos' => {
5 => 1,
6 => 1,
7 => 1,
},
);
sub new {
my $class = shift;
my $self = shift or die;
my $newself = bless $self, $class;
if ( !$self->{'output_obj'} ) {
if ( $self->{'logger'} ) {
$self->{'output_is_logger'} = 1;
$self->{'output_obj'} = $self->{'logger'};
}
else {
$self->{'output_obj'} = Cpanel::Output::Formatted::Terminal->new();
}
}
$self->{'excludes'} = default_exclude_list();
$self->{'exclude_remove'} = [];
$self->{'yum_tolerant'} = 1;
$self->{'yum_errorlevel'} = 1; # default value is 2
$self->{'yum.conf'} = $YUM_CONF;
$self->{'exe'} = $YUM_BIN;
$self->{'VERSION'} = $VERSION;
$self->{'system_perl_bin'} = '/usr/bin/perl';
return $newself;
}
sub out {
my ( $self, @args ) = @_;
return $self->{'output_obj'}->out(@args);
}
sub error {
my ( $self, @args ) = @_;
return $self->{'output_obj'}->error(@args);
}
sub haspkg {
return;
}
sub update {
my $self = shift or Carp::croak 'update() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("update() must be called as a method.");
return $self->install( @_, 'command' => ['update'] );
}
sub ensure {
my $self = shift or Carp::croak 'ensure() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("ensure() must be called as a method.");
$self->install(@_);
}
sub reinstall {
my $self = shift or Carp::croak 'reinstall() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("reinstall() must be called as a method.");
return $self->install( @_, 'command' => ['reinstall'] );
}
sub install {
my $self = shift or Carp::croak 'install() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("install() must be called as a method.");
my (%OPTS) = @_;
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 {
my ( $self, %OPTS ) = @_;
return $self->_call_yum( %OPTS, 'command' => ['erase'] );
}
sub install_packages {
my ( $self, %OPTS ) = @_;
return $self->_call_yum(%OPTS);
}
sub check {
my $self = shift or Carp::croak 'check() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("check() must be called as a method.");
$self->parse_yum_conf() or return; # A False return means we couldn't parse yum.conf
$self->write_yum_conf();
}
sub checkdb {
return 1;
}
sub checkconfig {
my $self = shift or Carp::croak 'checkconfig() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("checkconfig() must be called as a method.");
local $ENV{'LC_ALL'} = 'C';
my $glibcinfo = Cpanel::SafeRun::Errors::saferunallerrors( 'yum', 'info', 'glibc' ) || '';
if ( $glibcinfo !~ m{ (?: Installed | Available) \s+ Packages }xmsi || $glibcinfo =~ /No\s+Repositories\s+Available/ ) {
return 0;
}
return 1;
}
sub setup {
my $self = shift or Carp::croak 'setup() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("setup() must be called as a method.");
my $os = $self->{'sysinfo'}->{'rpm_dist'};
my $release_major_version = $self->{'sysinfo'}->{'rpm_dist_ver'};
return if ( $os ne 'centos' );
return if ( $release_major_version < 5 or $release_major_version > 6 );
return unless $self->can_setup();
$self->check(); # setup excludes, tolerant, errorlevel in the yum.conf file.
my $httpClient = Cpanel::HttpRequest->new( signed => 1 );
my $now = time();
my @FILES = ('/etc/yum.repos.d/CentOS-Base.repo');
my $case_count = 0;
my $CPSRC = Cpanel::Config::Sources::loadcpsources();
foreach my $case ( 'default', 'cpanel' ) {
$case_count++;
foreach my $file (@FILES) {
my @PATH = split( /\//, $file );
my $base_file = pop(@PATH);
rename( $file, $file . '.broken.' . $now ) if $case_count == 1;
my $url = 'http://' . $CPSRC->{'HTTPUPDATE'} . '/syspkgs/templates/' . $os . '/' . $release_major_version . '/' . $case . '/' . $base_file;
$httpClient->download( $url, $file );
}
$self->_call_yum( 'command' => [ 'clean', 'all' ] );
if ( $self->checkconfig() ) {
return 1;
}
}
foreach my $file (@FILES) {
unlink($file);
rename( $file . '.broken.' . $now, $file );
}
$self->check(); # setup excludes, tolerant, errorlevel in the yum.conf file.
}
sub can_setup {
my $self = shift or Carp::croak 'can_setup() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("can_setup() must be called as a method.");
my $os = $self->{'sysinfo'}->{'rpm_dist'};
my $release_major_version = $self->{'sysinfo'}->{'rpm_dist_ver'};
return $setup_oses{$os} && $setup_oses{$os}->{$release_major_version} || 0;
}
sub verify_package_version_is_available {
my ( $self, %OPTS ) = @_;
Cpanel::Validate::FilesystemNodeName::validate_or_die( $OPTS{'package'} );
die Cpanel::Exception::create( 'MissingParameter', { 'name' => 'version' } ) if !defined $OPTS{'version'};
my $result = Cpanel::SafeRun::Object->new(
'program' => $self->{'exe'},
'args' => [ 'list', $OPTS{'package'} ],
);
if ( $result->CHILD_ERROR() ) {
die Cpanel::Exception::create(
'IO::ExecError',
'The system failed to find the package “[_1]” because of an error: [_2]',
[
$OPTS{'package'},
$result->stderr() ? $result->stderr() : $result->autopsy(),
]
);
}
my $stdout = $result->stdout();
my @ret = split( m{\n}, $stdout );
foreach my $line (@ret) {
if ( $line =~ m/^[ \t]*\Q$OPTS{'package'}\E[\.\S]*[ \t]+\Q$OPTS{'version'}\E/ ) {
return 1;
}
}
die "The package “$OPTS{'package'}” with version “$OPTS{'version'}” is not available via yum: $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::IO::ExecError' )
&& $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;
}
return 1;
}
sub installed_package_version {
my ( $self, $package ) = @_;
local $ENV{'LANG'} = 'C';
local $ENV{'LC_ALL'} = 'C';
my $rpm_bin = $self->rpm_bin();
my $result = Cpanel::SafeRun::Object->new(
'program' => $rpm_bin,
'args' => [ '--query', '--queryformat', '%{VERSION}-%{RELEASE}\n', $package ],
);
if ( $result->CHILD_ERROR() && $result->error_code != 1 ) {
die "Failed to execute rpm -q $package:" . $result->stderr() . ':' . $result->autopsy();
}
my $package_version = $result->stdout();
$package_version =~ s/\s+$//;
return '' if !$package_version || $package_version =~ m{\s+not\s+installed$}; # The package is not installed
my %VERSIONS = map { $_ => 1 } split( m{\n}, $package_version );
if ( scalar keys %VERSIONS > 1 ) {
die "Multiple versions of the $package are installed: $package_version";
}
return ( keys %VERSIONS )[0];
}
sub is_package_unaltered {
my $self = shift or Carp::croak 'is_package_unaltered() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("is_package_unaltered() must be called as a method.");
my ( $path, $package ) = @_;
local $ENV{'LANG'} = 'C';
local $ENV{'LC_ALL'} = 'C';
my $rpm_bin = $self->rpm_bin();
if ( !-e $path ) {
my $check_perl = Cpanel::SafeRun::Errors::saferunallerrors( $rpm_bin, '-q', $package );
return 1 if $?;
return 0;
}
my $package_name = Cpanel::SafeRun::Simple::saferun( $rpm_bin, '-qf', $path );
$package_name = ( split /\n/, $package_name )[0];
if ( $package_name =~ /is not owned by any package/ ) {
return 0;
}
my $rpm_verbose = Cpanel::SafeRun::Simple::saferun( $rpm_bin, '-vV', $package_name );
my @rpm_verbose = split( /\n/, $rpm_verbose );
foreach my $line (@rpm_verbose) {
next unless ( $line =~ m{$path\b} ); #only parse the interpreter line to see if it's been altered.
return 1 if ( $line =~ /^\Q........\E/ );
if ( $line =~ /^\S*[SM5DLUG]/ ) {
return 0;
}
}
return 0;
}
sub is_system_perl_unaltered {
my $self = shift or Carp::croak 'is_system_perl_unaltered() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("is_system_perl_unaltered() must be called as a method.");
return $self->is_package_unaltered( $self->{'system_perl_bin'}, 'perl' );
}
sub parse_existing_excludes {
my $self = shift or Carp::croak 'parse_existing_excludes() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("parse_existing_excludes() must be called as a method.");
my $pkgs = shift || '';
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 ( 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 );
}
if ( grep { $_ eq 'perl*' } @PKGS ) {
}
else {
}
$self->{'exclude_string'} = join( ' ', sort @PKGS );
}
sub determine_remove_from_excludes {
my $self = shift or Carp::croak 'determine_remove_from_excludes() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("determine_remove_from_excludes() must be called as a method.");
my @remove_excludes = qw/apache wget/;
if ( !$self->{'exclude_options'}->{'kernel'} ) {
delete $self->{'excludes'}->{'kernel'};
if ( !-e '/var/cpanel/checkyum-keepkernel' ) {
push @remove_excludes, qw( ^kernel ^kmod );
}
}
if ( $self->is_system_perl_unaltered() ) {
$self->{'exclude_options'}->{'perl'} = 0;
}
if ( $self->is_package_unaltered( '/usr/bin/ruby', 'ruby' ) ) {
$self->{'exclude_options'}->{'ruby'} = 0;
}
unless ( $self->{'exclude_options'}->{'ruby'} ) {
push @remove_excludes, 'ruby';
}
unless ( $self->{'exclude_options'}->{'perl'} ) {
push @remove_excludes, 'perl';
}
unless ( $self->{'exclude_options'}->{'bind-chroot'} ) {
push @remove_excludes, 'bind-chroot';
}
return @remove_excludes;
}
sub parse_yum_conf {
my $self = shift or Carp::croak 'parse_yum_conf() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("parse_yum_conf() must be called as a method.");
return if -e '/etc/checkyumdisable';
$self->{'output_obj'}->out("checkyum version $self->{VERSION}");
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 ) {
require Cpanel::Logger;
$self->{'logger'}->fatal( "Could not read from " . $self->{'yum.conf'} ) if ( $self->{'logger'} );
Cpanel::Logger->new()->die( "Could not read from " . $self->{'yum.conf'} );
}
my @all_exclude_lines;
while ( my $line = <$yum_conf_fh> ) {
next if ( $line =~ m/^\s*tolerant=/i );
next if ( $line =~ m/^\s*errorlevel=/i );
if ( $line =~ m/^\s*exclude\s*=\s*(.*)/i ) {
push @all_exclude_lines, $1;
next;
}
push @YUM_CONF_CONTENTS, $line;
}
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_yum_conf {
my $self = shift or Carp::croak 'write_yum_conf() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("write_yum_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::writefile( $self->{'yum.conf'}, join( '', @temp_file_contents ) ) ) {
require Cpanel::Logger;
$self->{'logger'}->fatal( "Could not write to " . $self->{'yum.conf'} ) if ( $self->{'logger'} );
Cpanel::Logger->new()->die( "Could not write to " . $self->{'yum.conf'} );
}
}
sub excludes {
my $self = shift or die;
return { map { s/\*//; $_ => 1 } split /\s+/, $self->{'original_exclude_string'} };
}
sub rpm_bin {
my $self = shift or Carp::croak 'rpm_bin() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("rpm_bin() must be called as a method.");
$self->{'rpm_bin'} ||= Cpanel::FindBin::findbin('rpm');
return $self->{'rpm_bin'};
}
sub default_exclude_list {
return {
'courier' => 'courier*',
'dovecot' => 'dovecot*',
'nsd' => 'nsd*',
'mydns' => 'mydns*',
'mod_ssl' => 'mod_ssl*',
'httpd' => 'httpd*',
'mysql' => 'mysql*',
'squirrelmail' => 'squirrelmail*',
'php' => 'php*',
'spamassassin' => 'spamassassin*',
'exim' => 'exim*',
'pure-ftpd' => 'pure-ftpd*',
'proftpd' => 'proftpd*',
'p0f' => 'p0f',
'filesystem' => 'filesystem', # This should only get pulled in on a new install.
'kernel' => 'kernel kernel-xen kernel-smp kernel-pae kernel-PAE kernel-SMP kernel-hugemem kernel-debug*',
'kmod' => 'kmod-[a-z]*',
'perl' => 'perl*',
'bind-chroot' => 'bind-chroot',
};
}
sub reinit {
my ( $self, $exclude_options ) = @_;
$self->{'excludes'} = default_exclude_list();
$self->{'exclude_options'} = $exclude_options || die;
}
sub _call_yum {
my ( $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 $dry_run = $OPTS{'dry_run'} ? 1 : 0;
my $temp_obj;
my @args = ( ( $usecache ? '-C' : () ), '-y' );
if ( $dry_run || $FORCE_DRY_RUN ) {
$temp_obj = Cpanel::TempFile->new();
my ( $temp_yum_conf, $temp_yum_fh ) = $temp_obj->file();
my $yum_conf = Cpanel::LoadFile::load( $self->{'yum.conf'} );
print {$temp_yum_fh} $yum_conf . "\n[main]\ntsflags=test\n";
close($temp_yum_conf);
push @args, '-c', $temp_yum_conf;
}
else {
push @args, '-c', $self->{'yum.conf'};
}
foreach my $package ( @{$exclude_packages} ) {
Cpanel::Validate::FilesystemNodeName::validate_or_die($package);
push @args, ( '-x', $package );
}
push @args, @{$command};
foreach my $package ( @{$packages} ) {
Cpanel::Validate::FilesystemNodeName::validate_or_die($package);
push @args, $package;
}
push @args, '--disablerepo=epel' if _is_epel_installed();
return $self->_exec_yum( %OPTS, '_args' => \@args );
}
sub _exec_yum {
my ( $self, %OPTS ) = @_;
my $stderr_callback = $OPTS{'stderr_callback'};
local $ENV{'LANG'} = 'C';
local $ENV{'LC_ALL'} = 'C';
my $stderr = '';
my $callback_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->out(@_); } );
my $callback_err_obj = Cpanel::Parser::Callback->new( 'callback' => sub { $self->error(@_); } );
my $result = Cpanel::SafeRun::Object->new(
'program' => $self->{'exe'},
'args' => $OPTS{'_args'},
'stdout' => Cpanel::CPAN::IO::Callback::Write->new(
sub {
my ($data) = @_;
if ( $data =~ m{\w+\s*:\s.*\d+/\d+}m ) {
$data =~ s/[\x00-\x0A]+//go;
$data .= "\n";
}
$callback_obj->process_data($data);
return;
}
),
'stderr' => Cpanel::CPAN::IO::Callback::Write->new(
sub {
my ($data) = @_;
$stderr .= $data;
if ($stderr_callback) {
$stderr_callback->($data) if $stderr_callback;
}
else {
$callback_err_obj->process_data($data);
}
return;
}
)
);
$callback_obj->finish();
$callback_err_obj->finish();
if ( $result->CHILD_ERROR() ) {
die Cpanel::Exception::create(
'IO::ExecError',
'The system failed to execute yum with the arguments “[_1]” because of an error: [_2]',
[
join( ' ', @{ $OPTS{'_args'} } ),
$result->autopsy() . ' : ' . $stderr,
]
);
}
return 1;
}
sub _should_ignore_package_conflicts_in_yum_error_output {
my ( $self, $yum_stderr, $ignore_conflict_packages_regexp ) = @_;
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;
}
1;
} # --- END Cpanel/SysPkgs/YUM.pm
{ # --- BEGIN Cpanel/SysPkgs.pm
package Cpanel::SysPkgs;
use strict;
# use Cpanel::SysPkgs::YUM (); # This is the only option as of 11.36 now so there's no reason not to include it.
# use Cpanel::GenSysInfo ();
$Cpanel::SysPkgs::VERSION = '1.1';
our $OUTPUT_OBJ_SINGLETON; # For EasyApache
sub new {
my $class = shift;
my %args = @_;
my $self = \%args;
bless $self, $class;
$self->{'exclude_options'} ||= { 'perl' => 1, 'bind-chroot' => 1, 'ruby' => 1 };
$self->{'sysinfo'} = Cpanel::GenSysInfo::run();
if ($OUTPUT_OBJ_SINGLETON) { # For EasyApache
$self->{'output_obj'} = $OUTPUT_OBJ_SINGLETON;
}
my $newself = Cpanel::SysPkgs::YUM->new($self) or die("Could not convert SysPkgs Object to Cpanel::SysPkgs::YUM");
$self->{'syspkgobj'} = bless {}, 'Cpanel::SysPkgs::YUM';
return $newself;
}
1;
} # --- END Cpanel/SysPkgs.pm
{ # --- BEGIN Cpanel/Sysup.pm
package Cpanel::Sysup;
use strict;
use Carp ();
use Try::Tiny;
# use Cpanel::iContact ();
# use Cpanel::SysPkgs ();
# use Cpanel::SysPkgs::YUM (); # Needed to force inclusion in updatenow.static. This is the only logical choice as of 11.36
# use Cpanel::GenSysInfo ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::Update::Logger ();
# use Cpanel::Version ();
# use Cpanel::Services::Enabled ();
sub new {
my $class = shift or Carp::croak 'new() called incorrectly; missing class';
my $self = shift || {};
return bless $self, $class;
}
sub logger {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("You must call this as a method.");
$self->{'logger'} ||= Cpanel::Update::Logger->new( { 'stdout' => 1, 'log_level' => 'info', 'timestamp' => 0 } );
}
sub run {
my $self = shift or Carp::croak 'run() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("run() must be called as a method.");
my $sysinfo = Cpanel::GenSysInfo::run();
my ( $rpm_list, $blockers ) = $self->needed_packages( $sysinfo->{'rpm_dist_ver'}, $sysinfo->{'rpm_dist'} );
push @$rpm_list, $self->optional_packages();
$self->install_packages( $rpm_list, $blockers );
}
my $installed_rpms;
sub get_installed_rpms {
my $self = shift or Carp::croak 'get_installed_rpms() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("get_installed_rpms() must be called as a method.");
return $installed_rpms if ($installed_rpms);
my %rpms = map { chomp; ( $_ => 1 ) } (`rpm -qa --queryformat "%{NAME}\n"`);
return $installed_rpms = \%rpms;
}
sub install_packages {
my $self = shift or Carp::croak 'install_packages() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("install_packages() must be called as a method.");
my ( $rpms_wanted, $blockers, $rpms_alternate ) = @_;
my @rpms_needed = @{ $self->get_outstanding_packages( @{$rpms_wanted}, $rpms_alternate ) };
if (@rpms_needed) {
my $syspkgobj = $self->_package_object();
$syspkgobj->check(); # dangerous to run yum update/install without excludes set up correctly
$syspkgobj->install( 'pkglist' => \@rpms_needed );
$blockers->{'kernel'} = 0;
$blockers->{'perl'} = 1;
$blockers->{'bind-chroot'} = 1;
$blockers->{'ruby'} = 1;
$syspkgobj->reinit($blockers);
$syspkgobj->check();
if ( scalar grep { $_ eq 'nscd' } @rpms_needed ) {
Cpanel::Services::Enabled::touch_disable_file('nscd');
}
$installed_rpms = 0;
my @uninstalled_rpms = @{ $self->get_outstanding_packages( @{$rpms_wanted}, $rpms_alternate ) };
if (@uninstalled_rpms) {
my $message = "Sysup: Needed system RPMs were not installed: " . join( ", ", @uninstalled_rpms );
$self->logger->error($message);
$self->_notify($message);
return;
}
return 1;
}
elsif ( keys %{$blockers} ) {
my $syspkgobj = Cpanel::SysPkgs->new( $self->{'logger'} ? ( 'logger' => $self->{'logger'} ) : () )
or die "The system could not create the SysPkgs object.\n";
$syspkgobj->reinit($blockers);
$syspkgobj->check();
}
$self->logger->info("All Needed RPMS are installed.\n");
return 1;
}
sub get_outstanding_packages {
my $self = shift or Carp::croak 'get_outstanding_packages() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("get_outstanding_packages() must be called as a method.");
my @rpms_wanted = @_;
pop @rpms_wanted if !defined $rpms_wanted[-1];
my $installed_rpms = $self->get_installed_rpms();
my @rpms_tocheck;
foreach my $rpms (@rpms_wanted) {
$rpms = [$rpms] unless $rpms && ref $rpms eq 'ARRAY';
push @rpms_tocheck, $rpms unless grep { $installed_rpms->{$_} } @$rpms;
}
my @rpms_missing;
my %missings;
foreach my $rpms (@rpms_tocheck) {
foreach my $rpm (@$rpms) {
if ( _is_capability_available($rpm) ) {
$missings{ $rpms->[0] } = 0;
last;
}
$missings{ $rpms->[0] } = 1;
}
}
return [ grep { $missings{$_} } sort keys %missings ];
}
sub _package_object {
my ($self) = @_;
return $self->{package_object} if defined $self->{package_object};
my $syspkgobj = Cpanel::SysPkgs->new(
$self->{'logger'} ? ( 'logger' => $self->{'logger'} ) : (),
exclude_options => { 'kernel' => 1, 'perl' => 1, 'bind-chroot' => 1, 'ruby' => 1 }
) or die "The system could not create the SysPkgs object.\n";
return $self->{package_object} = $syspkgobj;
}
sub _is_capability_available {
Cpanel::SafeRun::Simple::saferun( 'rpm', '-q', '--whatprovides', shift );
return $? == 0 ? 1 : 0;
}
sub _notify {
my ( $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 {
Cpanel::iContact::icontact(
application => 'sysup',
subject => 'cPanel update failure during sysup',
message => $fullmessage,
);
}
}
sub needed_packages {
my $self = shift or Carp::croak 'needed_packages() method called without arguments.';
ref $self eq __PACKAGE__ or Carp::croak("needed_packaged() must be called as a method.");
my $distro_version = shift or Carp::croak 'The system could not pass a distribution version to needed_packages.';
my $distro = shift or Carp::croak 'The system could not pass a distribution to needed_packages.';
$distro_version == 5
or $distro_version == 6
or $distro_version == 7
or $distro eq q{amazon}
or Carp::croak "This version of cPanel & WHM only supports distribution versions 5, 6, and 7: $distro_version detected";
my @packages = _all_centos_packages();
if ( $distro eq 'amazon' && $distro_version eq "6" ) {
push( @packages, qw{ xz-compat-libs } );
}
if ( $distro ne 'amazon' ) {
push @packages, qw{ compat-db python-tools smartmontools tclx tix tk tkinter };
}
my %blockers;
if ( $distro_version == 5 ) {
push @packages, qw{
db4
db4-devel
caching-nameserver
curl-devel
gnupg
glib
iptables-ipv6
lcms
python-simplejson
util-linux
vixie-cron
aspell
aspell-en
}, [ 'sysklogd', 'rsyslog' ];
}
elsif ( $distro_version == 6 ) {
push @packages, qw{
db4
db4-devel
glibc-static
gnupg2
glib2
iptables-ipv6
lcms
pixman
quota-devel
tcp_wrappers-devel
util-linux-ng
hunspell
hunspell-en
};
}
elsif ( $distro_version == 7 ) {
push @packages, qw{
glibc-static
gnupg2
glib2
libdb
libicu
libmount-devel
pixman
psmisc
quota-devel
tcp_wrappers-devel
hunspell
hunspell-en
net-tools
};
$blockers{'postfix'} = 0;
}
return \@packages, \%blockers;
}
sub optional_packages {
my $self = shift or die;
ref $self or die("You must call this as a method.");
my @entries = (
[qw/nscd unscd/],
);
my @results;
my $pkgobj = $self->_package_object();
$pkgobj->parse_yum_conf();
my $excludes = $pkgobj->excludes;
foreach my $entry (@entries) {
my @choices = ( ref $entry eq 'ARRAY' ? @$entry : ($entry) );
push @results, $entry unless $excludes->{ $choices[0] };
}
return @results;
}
sub _all_centos_packages {
return qw{
at
autoconf
automake
bind
bind-devel
bind-libs
bind-utils
binutils
bison
bzip2
cairo
coreutils
cpio
cpp
crontabs
curl
e2fsprogs
e2fsprogs-devel
expat
expat-devel
expect
file
flex
fontconfig
freetype
ftp
gamin
gamin-devel
gcc
gcc-c++
gd
gd-devel
gd-progs
gdbm
gdbm-devel
gettext
gettext-devel
ghostscript
giflib
glibc-devel
gzip
initscripts
iptables
krb5-devel
less
libaio
libaio-devel
libgcc
libgomp
libidn
libidn-devel
libjpeg
libjpeg-devel
libpcap
libpng
libpng-devel
libstdc++
libstdc++-devel
libtiff
libtiff-devel
libtool
libwmf
libxml2
libxml2-devel
libxslt
libxslt-devel
lsof
lynx
make
nano
ncurses
ncurses-devel
openssh
openssh-clients
openssh-server
openssl
openssl-devel
pcre
pam
pam-devel
pango
passwd
patch
popt
python
python-devel
python-docs
python-setuptools
quota
rcs
rdate
rsync
screen
sed
shadow-utils
sharutils
strace
stunnel
sysstat
tar
tcl
traceroute
unzip
urw-fonts
wget
which
xz
yum-utils
zip
zlib
zlib-devel
zsh
kernel-headers
libtool-ltdl
libtool-ltdl-devel
libX11-devel
libXpm
libXpm-devel
gmp
};
}
1;
} # --- END Cpanel/Sysup.pm
{ # --- BEGIN Cpanel/App.pm
package Cpanel::App;
use strict;
our $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_context_display_name {
if ( is_webmail() ) {
return 'Webmail';
}
elsif ( is_whm() ) {
return 'WHM';
}
else {
return "cPanel";
}
}
1;
} # --- END Cpanel/App.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->{'DEFWEBMAILTHEME'} ) {
$webmail_theme = $defaults->{'DEFWEBMAILTHEME'};
}
return $webmail_theme;
}
1;
} # --- END Cpanel/Conf.pm
{ # --- BEGIN Cpanel/Themes/Get.pm
package Cpanel::Themes::Get;
use strict;
# use Cpanel::ConfigFiles ();
# use Cpanel::App ();
# use Cpanel::Themes::List ();
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,
x4 => 1,
x4mail => 1,
xmail => 1,
bluelagoon => 1,
monsoon => 1,
Xskin => 1,
n => 1,
no => 1,
tree => 1,
gorgo => 1
);
our %CPANEL_DISTRIBUTED_THEMES = (
'x3' => 1,
'x3mail' => 1,
'paper_lantern' => 1,
);
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 {
require Cpanel::Conf;
return Cpanel::Conf->new()->cpanel_theme;
}
1;
} # --- END Cpanel/Themes/Get.pm
{ # --- BEGIN Cpanel/Themes/List.pm
package Cpanel::Themes::List;
use strict;
# use Cpanel::Themes::Get ();
sub get_list {
return reverse sort keys %Cpanel::Themes::Get::CPANEL_DISTRIBUTED_THEMES;
}
1;
} # --- END Cpanel/Themes/List.pm
{ # --- BEGIN Cpanel/Config/Services.pm
package Cpanel::Config::Services;
# use Cpanel::Services::Enabled ();
my %disable_files = (
'dns' => '/etc/nameddisable',
'ftp' => '/etc/ftpddisable',
'mail' => '/etc/imapdisable'
);
sub is_enabled { goto &service_enabled; }
sub service_enabled {
my $service = shift;
if ( !$service ) {
require Cpanel::Logger;
my $logger = Cpanel::Logger->new();
$logger->warn('No service specified to determine if enabled');
return wantarray ? ( 0, 'No service specified to determine if enabled' ) : 0;
}
my $disabled_service_name;
my $srv_en = 1; # default to enabled
my @srvcs = split( /\,/, $service );
my $msg;
foreach my $srvc (@srvcs) {
unless ( Cpanel::Services::Enabled::is_enabled($srvc) ) {
$disabled_service_name = $srvc;
$msg = defined( $disable_files{$srvc} ) ? $disable_files{$srvc} : '/etc/' . $disabled_service_name . 'disable';
$srv_en = 0;
last;
}
}
if ( $srv_en == 0 ) {
return wantarray ? ( 0, $msg ) : 0;
}
else {
return wantarray ? ( 1, $service . ' is enabled' ) : 1;
}
}
1;
} # --- END Cpanel/Config/Services.pm
{ # --- BEGIN Cpanel/Update.pm
package Cpanel::Update;
# use Cpanel::Logger ();
# use Cpanel::Config::Services ();
# use Cpanel::Config::Sources ();
# use Cpanel::HttpRequest ();
# use Cpanel::Update::Config ();
our $VERSION = '2.1';
our $cpanel_update_conf = $Cpanel::Update::Config::cpanel_update_conf;
our $max_download_attempts = 5;
our $delay_interval_between_attempts = 2;
my $logger = Cpanel::Logger->new();
sub _deprecate {
my ( $old, $new ) = @_;
$logger->invalid("Cpanel::Update::$old has been renamed to Cpanel::Update::$new. Please call it instead.");
}
sub get_transfers_sync_tree { _deprecate( 'get_transfers_sync_tree', 'get_transfers_sync_tier' ); goto &get_transfers_sync_tier; }
sub is_manual_update { _deprecate( 'is_manual_update', 'is_cpanel_update_enabled' ); goto &Cpanel::Update::is_cpanel_update_enabled; }
sub loadupdateconfig { _deprecate( 'loadupdateconfig', 'Config::load' ); goto &Cpanel::Update::Config::load; }
sub sanitize_config { _deprecate( 'sanitize_config', 'Config::sanitize' ); goto &Cpanel::Update::Config::sanitize; }
sub saveupdateconfig { _deprecate( 'saveupdateconfig', 'Config::save' ); goto &Cpanel::Update::Config::save; }
sub get_update_tier { _deprecate( 'get_update_tier', 'Config::get_tier' ); goto &Cpanel::Update::Config::get_tier; }
sub get_update_tree { _deprecate( 'get_update_tree', 'Config::get_tier' ); goto &Cpanel::Update::Config::get_tier; }
sub pkg_update_list { _deprecate( 'pkg_update_list', 'Config::pkg_update_list' ); goto &Cpanel::Update::Config::pkg_update_list; }
sub init_UP_update {
my ($update_name) = @_;
my ( $status, $disabled_name ) = Cpanel::Config::Services::service_enabled($update_name);
if ( !$status ) {
print "Updates for \xE2\x80\x9C$update_name\xE2\x80\x9D are disabled because \xE2\x80\x9C$disabled_name\xE2\x80\x9D exists.\n";
exit;
}
( $status, $disabled_name ) = Cpanel::Config::Services::service_enabled( $update_name . 'up' );
if ( !$status ) {
print "Updates for \xE2\x80\x9C$update_name\xE2\x80\x9D are disabled because \xE2\x80\x9C$disabled_name\xE2\x80\x9D exists.\n";
exit;
}
}
sub safe_update_environment {
my $update_name = shift;
$SIG{'PIPE'} = 'DEFAULT';
if ( ( !$ENV{'LANG'} || $ENV{'LANG'} ne 'C' ) && -x '/usr/local/cpanel/scripts/' . $update_name . 'up' ) {
$ENV{'LANG'} = 'C';
$ENV{'LC_ALL'} = 'C';
exec( '/usr/local/cpanel/scripts/' . $update_name . 'up', @ARGV ) or exit;
}
if ( !-t STDERR ) {
open( STDERR, '>&STDOUT' );
}
$| = 1;
}
sub set_tier {
my $tier = shift || '';
$tier =~ tr/A-Z/a-z/;
my $rUPCONF = Cpanel::Update::Config::load();
my $old_tier = $rUPCONF->{'CPANEL'};
return $old_tier if ( !$tier or $old_tier eq $tier );
return $old_tier if ( !validate_tier($tier) );
$rUPCONF->{'CPANEL'} = $tier;
if ( Cpanel::Update::Config::save($rUPCONF) ) {
return $tier;
}
else {
$logger->warn( 'Unable to Cpanel::Update::Config::save() with ' . $tier );
return $old_tier;
}
}
sub validate_tier {
my ($tier) = @_;
my $update_config_ref = { 'CPANEL' => $tier };
my $CPSRC = Cpanel::Config::Sources::loadcpsources();
my $remote_tiers = eval { get_remote_tiers_info($CPSRC) };
return if ( !$remote_tiers );
my $version = get_remote_version_from_tier( $update_config_ref, $remote_tiers );
return if ( !$version );
return $version;
}
sub set_update_type {
my $rUPCONF = Cpanel::Update::Config::load();
my $default_rUPCONF = Cpanel::Update::Config::_default_preferences();
my $update_type = shift or return $rUPCONF->{'UPDATES'};
$update_type =~ tr/A-Z/a-z/;
$update_type =~ m/^(daily|manual|never)$/ or return $rUPCONF->{'UPDATES'};
$rUPCONF->{'UPDATES'} = $update_type;
Cpanel::Update::Config::save($rUPCONF);
return $update_type;
}
sub get_remote_version_from_tier {
my ( $update_config_ref, $remote_tiers ) = @_;
my $cpconf_tier = Cpanel::Update::Config::get_tier($update_config_ref);
return $cpconf_tier if ( $cpconf_tier =~ m{^\d+\.\d+\.\d+\.\d+$} );
if ( exists $remote_tiers->{$cpconf_tier} ) {
return $remote_tiers->{$cpconf_tier};
}
return;
}
sub get_remote_tiers_info {
my ( $CPSRC, $local_logger ) = @_;
my $HttpRequest_obj = Cpanel::HttpRequest->new(
'hideOutput' => 1,
defined $local_logger ? ( logger => $local_logger ) : (),
'timeout' => 45,
'announce_mirror' => 1,
);
my $remote_tiers_info;
for my $attempt ( 1 .. $max_download_attempts ) {
$remote_tiers_info = undef;
eval {
$remote_tiers_info = $HttpRequest_obj->request(
'host' => $CPSRC->{'HTTPUPDATE'},
'url' => '/cpanelsync/TIERS',
'signed' => 1,
);
};
last if ( !$@ and $remote_tiers_info );
sleep $delay_interval_between_attempts;
}
$local_logger ||= $logger;
if ( !$remote_tiers_info ) {
my $msg = "Unable to retrieve tier version info: $@";
if ( $local_logger->can("die") ) {
$local_logger->die($msg);
}
else {
$local_logger->fatal($msg);
die $msg;
}
}
my %tiers;
foreach my $tier_definition ( split( /\n/, $remote_tiers_info ) ) {
next if ( $tier_definition =~ m/^\s*#/ ); # Skip commented lines.
next if ( $tier_definition !~ m/^\s*([^:\s]+)\s*:\s*(\S+)/ );
my ( $remote_tier, $remote_version ) = ( $1, $2 );
$tiers{$remote_tier} = $remote_version;
}
return \%tiers;
}
sub get_transfers_sync_tier {
return -f '/var/cpanel/transfers_devel' ? 'DEVEL' : 'PUBLIC';
}
1;
} # --- END Cpanel/Update.pm
{ # --- BEGIN Cpanel/DB/Map/Path.pm
package Cpanel::DB::Map::Path;
use strict;
# use Cpanel::ConfigFiles ();
# use Cpanel::Validate::FilesystemNodeName ();
sub data_file_for_username {
my ($cpuser) = @_;
Cpanel::Validate::FilesystemNodeName::validate_or_die($cpuser);
return "$Cpanel::ConfigFiles::DATABASES_INFO_DIR/$cpuser.json";
}
1;
} # --- END Cpanel/DB/Map/Path.pm
{ # --- BEGIN Cpanel/Session/Constants.pm
package Cpanel::Session::Constants;
use strict;
our $CPSES_DIR = '/var/cpanel/cpses';
our $CPSES_KEYS_DIR = "$CPSES_DIR/keys";
our $CPSES_MAILMAN_DIR = "$CPSES_DIR/mailman";
our $CPSES_LOOKUP_DIR = "$CPSES_DIR/lookup";
our $TEMP_USER_PREFIX = 'cpses_';
our $TEMP_SEPARATOR = '[::cpses::]';
1;
} # --- END Cpanel/Session/Constants.pm
{ # --- BEGIN Cpanel/DB/Map/Reader.pm
package Cpanel::DB::Map::Reader;
use strict;
# use Cpanel::ArrayFunc ();
# use Cpanel::Autodie ();
# use Cpanel::ConfigFiles ();
# use Cpanel::Context ();
# use Cpanel::DB::Map::Path ();
# use Cpanel::LoadModule ();
# use Cpanel::Session::Constants ();
# use Cpanel::Transaction::File::JSONReader ();
my %ENGINE_IN_DATASTORE = qw(
mysql MYSQL
postgresql PGSQL
);
my @REQUIRED_ENGINE_KEYS = qw(dbs dbusers);
sub cpuser_exists {
my ($cpuser) = @_;
return 1 if -e _data_file($cpuser);
return 1 if -e "$Cpanel::ConfigFiles::DATABASES_INFO_DIR/$cpuser.yaml";
return 0;
}
sub get_all_cpusers {
Cpanel::Context::must_be_list();
Cpanel::Autodie::opendir( my $dfh, $Cpanel::ConfigFiles::DATABASES_INFO_DIR );
return Cpanel::ArrayFunc::uniq( map { m<\A(.+)\.(?:json|yaml)\z> ? $1 : () } readdir $dfh );
}
*_data_file = \&Cpanel::DB::Map::Path::data_file_for_username;
sub _find_old_data {
my ($cpuser) = @_;
Cpanel::LoadModule::load_perl_module('Cpanel::DB::Map::Convert');
return Cpanel::DB::Map::Convert::read_old_dbmap($cpuser);
}
sub _get_dsengine_for_engine {
my ($engine) = @_;
my $ds_engine = $ENGINE_IN_DATASTORE{$engine};
if ( !$ds_engine ) {
die "Invalid engine: “$engine”";
}
return $ds_engine;
}
sub new {
my ( $class, %opts ) = @_;
my $ds_engine = _get_dsengine_for_engine( $opts{'engine'} );
my $data_file = _data_file( $opts{'cpuser'} );
my $data;
if ( -s $data_file ) {
my $trans = Cpanel::Transaction::File::JSONReader->new(
path => $data_file,
);
$data = $trans->get_data();
}
if ( 'HASH' ne ref $data ) {
$data = _find_old_data( $opts{'cpuser'} );
}
if ( !$data ) {
die Cpanel::Exception::create( 'Database::CpuserNotInMap', { name => $opts{'cpuser'} } );
}
my $self = {
_engine => $ds_engine,
_data => $data,
_cpuser => $opts{'cpuser'},
};
return bless $self, $class;
}
sub _get_engine_data {
my $self = shift;
foreach my $required (@REQUIRED_ENGINE_KEYS) {
$self->{'_data'}{ $self->{'_engine'} }{$required} ||= {};
}
return $self->{'_data'}{ $self->{'_engine'} };
}
sub get_dbusers_for_database {
my ( $self, $db ) = @_;
Cpanel::Context::must_be_list();
my $dbusers_element = $self->_get_engine_data()->{'dbusers'};
my @users;
for my $user ( keys %$dbusers_element ) {
next if $user =~ m{^\Q$Cpanel::Session::Constants::TEMP_USER_PREFIX\E};
push @users, $user if exists $dbusers_element->{$user}->{'dbs'}->{$db};
}
return @users;
}
sub get_databases_for_dbuser {
my ( $self, $dbuser ) = @_;
Cpanel::Context::must_be_list();
my $dbuser_element = $self->_get_engine_data()->{'dbusers'}->{$dbuser};
return ( $dbuser_element ? keys %{ $dbuser_element->{'dbs'} } : () );
}
sub get_dbusers_for_all_databases {
my ($self) = @_;
my $dbusers_element = $self->_get_engine_data()->{'dbusers'};
my %dbusers;
for my $dbuser ( keys %$dbusers_element ) {
next if $dbuser =~ m{^\Q$Cpanel::Session::Constants::TEMP_USER_PREFIX\E};
for my $db ( keys %{ $dbusers_element->{$dbuser}{'dbs'} } ) {
push @{ $dbusers{$db} }, $dbuser;
}
}
for my $db ( keys %{ $self->_get_engine_data()->{'dbs'} } ) {
$dbusers{$db} ||= [];
}
return \%dbusers;
}
sub database_exists {
my ( $self, $dbname ) = @_;
return $self->_get_engine_data()->{'dbs'}{$dbname} ? 1 : 0;
}
sub dbuser_exists {
my ( $self, $dbuser ) = @_;
return $self->_get_engine_data()->{'dbusers'}{$dbuser} ? 1 : 0;
}
sub get_dbusers {
my ($self) = @_;
Cpanel::Context::must_be_list();
return grep { !m<\A\Q$Cpanel::Session::Constants::TEMP_USER_PREFIX\E> } $self->get_dbusers_plus_cpses();
}
sub get_dbusers_plus_cpses {
my ($self) = @_;
Cpanel::Context::must_be_list();
return if !$self->_get_engine_data();
return keys %{ $self->_get_engine_data()->{'dbusers'} };
}
sub get_databases {
my ($self) = @_;
Cpanel::Context::must_be_list();
return if !$self->_get_engine_data();
return keys %{ $self->_get_engine_data()->{'dbs'} };
}
sub get_cpuser {
my ($self) = @_;
return $self->{'_cpuser'};
}
sub set_engine {
my ( $self, $engine ) = @_;
return $self->{'_engine'} = _get_dsengine_for_engine($engine);
}
1;
} # --- END Cpanel/DB/Map/Reader.pm
{ # --- BEGIN Cpanel/Config/Users.pm
package Cpanel::Config::Users;
use strict;
# use Cpanel::Config::LoadUserDomains ();
our $VERSION = '1.1';
sub getcpusers {
my $trueuserdomains_ref = Cpanel::Config::LoadUserDomains::loadtrueuserdomains( undef, 1 );
return wantarray ? keys %$trueuserdomains_ref : [ keys %$trueuserdomains_ref ];
}
1;
} # --- END Cpanel/Config/Users.pm
{ # --- BEGIN Cpanel/DB/Map/Collection.pm
package Cpanel::DB::Map::Collection;
use strict;
# use Cpanel::DB::Map::Reader ();
# use Cpanel::Config::Users ();
my %DB_ENGINE_CONVERSION = qw(
MYSQL mysql
PGSQL postgresql
);
sub new {
my ( $class, $args ) = @_;
my $self = $class->init($args);
bless $self, $class;
$self->_load_maps();
return $self;
}
sub init {
my ( $class, $args ) = @_;
my $self = {
'db' => $args->{'db'} || 'MYSQL',
'maps' => {},
'dbindex' => {},
};
}
*_get_cpusers = \&Cpanel::Config::Users::getcpusers;
sub _load_maps {
my ($self) = @_;
my $engine = $DB_ENGINE_CONVERSION{ $self->{'db'} } || die "unknown “db”: “$self->{'db'}”";
my @cpusers = grep { Cpanel::DB::Map::Reader::cpuser_exists($_) } $self->_get_cpusers();
$self->{'maps'} = { map { $_ => ( Cpanel::DB::Map::Reader->new( 'cpuser' => $_, 'engine' => $engine ) ) } @cpusers };
foreach my $user (@cpusers) {
my $db_map = $self->{'maps'}{$user};
my $cpuser = $db_map->get_cpuser();
foreach my $db ( $db_map->get_databases() ) {
$self->{'dbindex'}{$db} = $cpuser;
}
}
}
sub set_db {
my ( $self, $db ) = @_;
return if !$db;
$self->{'db'} = $db;
$self->_load_maps();
}
sub _get_map_for_cpuser {
my ( $self, $cpuser ) = @_;
if ( exists $self->{'maps'}->{$cpuser} ) {
return $self->{'maps'}->{$cpuser};
}
else {
return $self->_make_map_for_cpuser($cpuser);
}
}
sub _make_map_for_cpuser {
my ( $self, $cpuser ) = @_;
return Cpanel::DB::Map::Reader->new( 'cpuser' => $cpuser, 'engine' => $self->{'db'} );
}
sub _build_dbuser_map {
my ($self) = @_;
my $cpuser;
$self->{'dbusermaps_cache'} = {
map {
$cpuser = $_;
map {
$_ => $cpuser; # This is what is actually going into the hashref
} $self->{'maps'}{$_}->get_dbusers_plus_cpses()
} keys %{ $self->{'maps'} }
};
}
sub find_by_dbuser {
my ( $self, $dbuser ) = @_;
return $self->{'maps'}->{$dbuser} if exists $self->{'maps'}->{$dbuser};
$self->_build_dbuser_map() if !exists $self->{'dbusermaps_cache'};
return exists $self->{'dbusermaps_cache'}{$dbuser} ? $self->{'maps'}->{ $self->{'dbusermaps_cache'}{$dbuser} } : undef;
}
sub find_by_db {
my ( $self, $db ) = @_;
$db =~ s/\\//g;
my $cpuser = $self->{'dbindex'}{$db};
return $cpuser ? $self->_get_map_for_cpuser($cpuser) : undef;
}
1;
} # --- END Cpanel/DB/Map/Collection.pm
{ # --- BEGIN Cpanel/DbUtils.pm
package Cpanel::DbUtils;
use strict;
# use Cpanel::FindBin ();
# use Cpanel::Logger ();
our $VERSION = 1.2;
sub _find_bin {
return Cpanel::FindBin::findbin( $_[0], ( defined $_[1] ? $_[1] : () ) );
}
sub find_mysql { _find_bin('mysql'); }
sub find_mysql_config { _find_bin('mysql_config'); }
sub find_mysqladmin { _find_bin('mysqladmin'); }
sub find_mysqlcheck { _find_bin('mysqlcheck'); }
sub find_mysqldump { _find_bin('mysqldump'); }
sub find_mysql_fix_privilege_tables { _find_bin('mysql_fix_privilege_tables'); }
sub find_mysql_upgrade { _find_bin('mysql_upgrade') }
sub find_mysqld { _find_bin( 'mysqld', [ '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin', '/usr/libexec', '/usr/local/libexec' ] ); }
sub find_pg_dump { _find_bin( 'pg_dump', ['/usr/local/cpanel/3rdparty/bin'] ) }
sub find_pg_restore { _find_bin( 'pg_restore', ['/usr/local/cpanel/3rdparty/bin'] ) }
sub find_psql { _find_bin('psql') }
sub find_postmaster { _find_bin('postmaster') }
sub find_createdb { _find_bin('createdb'); }
sub find_pg_ctl { _find_bin('pg_ctl'); }
sub find_createuser { _find_bin('createuser'); }
sub find_dropdb { _find_bin('dropdb'); }
sub find_dropuser { _find_bin('dropuser'); }
1;
} # --- END Cpanel/DbUtils.pm
{ # --- BEGIN Cpanel/Mysql/Error.pm
package Cpanel::Mysql::Error;
use strict;
sub ER_ACCESS_DENIED_ERROR { return 1045 }
sub ER_BAD_DB_ERROR { return 1049 }
sub ER_CANNOT_USER { return 1396 }
sub ER_DB_CREATE_EXISTS { return 1007 }
sub ER_DB_DROP_EXISTS { return 1008 }
sub ER_NONEXISTING_GRANT { return 1141 }
sub ER_NOT_ALLOWED_COMMAND { return 1148 }
sub ER_PASSWORD_NO_MATCH { return 1133 }
sub ER_PARSE_ERROR { return 1064 }
sub ER_SERVER_IS_IN_SECURE_AUTH_MODE { return 1275 }
sub ER_USER_LIMIT_REACHED { return 1226 }
sub CR_CONN_HOST_ERROR { return 2003 }
sub CR_CONNECTION_ERROR { return 2002 }
my $CR_MIN_ERROR;
my $CR_MAX_ERROR;
BEGIN {
$CR_MIN_ERROR = 2000;
$CR_MAX_ERROR = 2999;
}
sub is_client_error_code {
my ($code) = @_;
return ( $code >= $CR_MIN_ERROR ) && ( $code <= $CR_MAX_ERROR ) ? 1 : 0;
}
1;
} # --- END Cpanel/Mysql/Error.pm
{ # --- BEGIN Cpanel/Encoder/utf8.pm
package Cpanel::Encoder::utf8;
use strict;
sub teletex_to_utf8 {
my ($value) = @_;
my @chrs = unpack( 'C*', $value );
my @string;
while ( my @cl = splice( @chrs, 0, 1 ) ) {
push @string, pack( 'U', $cl[0] );
}
return join( '', @string );
}
sub ucs2_to_utf8 {
my ($value) = @_;
my @chrs = unpack( 'C*', $value );
my @string;
while ( my @cl = splice( @chrs, 0, 2 ) ) {
push @string, pack( 'U', hex( sprintf( "%02x%02x", @cl ) ) );
}
my $ret = join( '', @string );
return $ret;
}
sub is_utf8 {
require bytes;
return 1 if bytes::length( $_[0] ) != length( $_[0] );
return 0;
}
sub encode {
use bytes; # only for the scope of this subroutine
$_[0] = substr $_[0], 0;
return;
}
1;
} # --- END Cpanel/Encoder/utf8.pm
{ # --- BEGIN Cpanel/Validate/LineTerminatorFree.pm
package Cpanel::Validate::LineTerminatorFree;
use strict;
use Try::Tiny;
# use Cpanel::Encoder::utf8 ();
# use Cpanel::Exception ();
sub is_valid {
my ($node) = @_;
my $err;
try {
validate_or_die($node);
}
catch {
$err = $_;
};
return $err ? 0 : 1;
}
sub validate_or_die {
my ($name) = @_;
if ( $name =~ tr/\x{000A}// ) { # LF: (CR+LF)
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a line feed.', { value => $name, invalid_characters => ["\x{000A}"] } );
}
elsif ( $name =~ tr/\x{000B}// ) { # VT:
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a vertical tab.', { value => $name, invalid_characters => ["\x{000B}"] } );
}
elsif ( $name =~ tr/\x{000C}// ) { # FF:
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a form feed.', { value => $name, invalid_characters => ["\x{000C}"] } );
}
elsif ( $name =~ tr/\x{000D}// ) { # CR: (CR+LF)
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a carriage return.', { value => $name, invalid_characters => ["\x{000D}"] } );
}
elsif ( $name =~ tr/\x{0085}// ) { # NEL:
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a Unicode [asis,NEL] character.', { value => $name, invalid_characters => ["\x{0085}"] } );
}
Cpanel::Encoder::utf8::encode($name);
if ( -1 != index( $name, "\xe2\x80\xa8" ) ) { # LS:
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a Unicode [asis,LS] character..', { value => $name, invalid_characters => ["\x{2028}"] } );
}
elsif ( -1 != index( $name, "\xe2\x80\xa9" ) ) { # PS:
die Cpanel::Exception::create( 'InvalidCharacters', 'This value may not contain a Unicode [asis,PS] character.', { value => $name, invalid_characters => ["\x{2029}"] } );
}
elsif ( $name =~ tr{\0}{} ) {
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/LineTerminatorFree.pm
{ # --- BEGIN Cpanel/MysqlUtils/Grants.pm
package Cpanel::MysqlUtils::Grants;
use strict;
# use Cpanel::MysqlUtils ();
# use Cpanel::Validate::LineTerminatorFree ();
use Try::Tiny;
my %ATTRIBUTE_QUOTER = (
db_name => 'quote_pattern_identifier',
db_obj => 'quote_identifier',
db_user => 'quote',
db_host => 'quote_pattern',
);
my @ATTRIBUTES = qw(
db_privs
db_object_type
db_name
db_obj
db_user
db_host
db_rest
);
my %RAW_ASTERISK_OK = map { $_ => undef } qw(
db_name
db_obj
);
sub _getter_setter {
my ( $self, $attribute, $input ) = @_;
my $quoter = $ATTRIBUTE_QUOTER{$attribute};
if ( @_ > 2 ) {
if ($quoter) {
$input = Cpanel::MysqlUtils->can($quoter)->($input);
}
$self->{"_$attribute"} = $input;
}
if ($quoter) {
return Cpanel::MysqlUtils->can("un$quoter")->( $self->{"_$attribute"} );
}
else {
return $self->{"_$attribute"};
}
}
sub db_privs {
my $self = shift;
return $self->_getter_setter( 'db_privs', @_ );
}
sub db_name {
my $self = shift;
return $self->_getter_setter( 'db_name', @_ );
}
sub db_object_type {
my $self = shift;
return $self->_getter_setter( 'db_object_type', @_ );
}
sub db_obj {
my $self = shift;
return $self->_getter_setter( 'db_obj', @_ );
}
sub db_user {
my $self = shift;
return $self->_getter_setter( 'db_user', @_ );
}
sub db_host {
my $self = shift;
return $self->_getter_setter( 'db_host', @_ );
}
sub db_rest {
my $self = shift;
return $self->_getter_setter( 'db_rest', @_ );
}
sub _quoted_getter_setter {
my ( $self, $attribute, $input ) = @_;
my $quoter = $ATTRIBUTE_QUOTER{$attribute};
die "“$attribute” is not quoted!" if !$quoter;
if ( @_ > 2 ) {
$self->{"_$attribute"} = $input;
}
return $self->{"_$attribute"};
}
sub quoted_db_name {
my $self = shift;
return $self->_quoted_getter_setter( 'db_name', @_ );
}
sub quoted_db_obj {
my $self = shift;
return $self->_quoted_getter_setter( 'db_obj', @_ );
}
sub quoted_db_user {
my $self = shift;
return $self->_quoted_getter_setter( 'db_user', @_ );
}
sub quoted_db_host {
my $self = shift;
return $self->_quoted_getter_setter( 'db_host', @_ );
}
sub new {
my ( $class, $grant ) = @_;
my $self = {};
bless $self, $class;
if ( defined $grant ) {
$self->_init($grant);
}
return bless $self, $class;
}
sub _init {
my ( $self, $grant ) = @_;
my $orig_grant = $grant;
$grant =~ s{;\s*\z}{};
my $object_type = '(?: ( PROCEDURE | FUNCTION | TABLE ) \s+ )?';
my @parts = $grant =~ m/
\A\s* #
GRANT\s+ #
([^\r\n'"]+?) # Privileges (can contain backtick-quoted identifiers)
\s+ON\s+ #
$object_type # Object type
(\*|$Cpanel::MysqlUtils::IDENTIFIER_REGEXP) # Database name
\. #
(\*|$Cpanel::MysqlUtils::IDENTIFIER_REGEXP) # Database object
\s+TO\s+ #
($Cpanel::MysqlUtils::QUOTED_STRING_REGEXP) # Database user
\@ #
($Cpanel::MysqlUtils::QUOTED_STRING_REGEXP) # Database host
( # The rest of the line (can contain quoted strings)
(?:\s+.*)? #
) #
\s*\z #
/xmsi;
die "Invalid grant string: $orig_grant\n" if !@parts;
@{$self}{ map { "_$_" } @ATTRIBUTES } = @parts;
$self->{'_db_rest'} =~ s{\A\s+}{};
$self->{'_db_rest'} =~ s{\s+\z}{};
while ( my ( $attr, $quoter_name ) = each %ATTRIBUTE_QUOTER ) {
my $raw = $self->{"_$attr"};
if ( $raw eq '*' ) {
next if exists $RAW_ASTERISK_OK{$attr};
die "“$attr” may not be unquoted “*”: $orig_grant\n";
}
my $roundtrip_quoted = Cpanel::MysqlUtils->can($quoter_name)->( Cpanel::MysqlUtils->can("un$quoter_name")->($raw) );
if ( substr( $raw, 0, 1 ) ne substr( $roundtrip_quoted, 0, 1 ) ) {
$self->can("quoted_$attr")->( $self, $roundtrip_quoted );
}
}
if (
$self->quoted_db_name() eq '*'
&& $self->quoted_db_obj() ne '*' # db_obj is a MySQL object_type of: TABLE, FUNCTION, and/or PROCEDURE
) {
die "“db_name” may not be unquoted “*” unless “db_obj” is also unquoted “*”: $orig_grant\n";
}
foreach my $attr (@ATTRIBUTES) {
next if !length $self->{"_$attr"};
try {
Cpanel::Validate::LineTerminatorFree::validate_or_die( $self->{"_$attr"} );
}
catch {
die "$_: $orig_grant\n";
};
}
return $self;
}
sub to_string {
my ($self) = @_;
my $str = $self->_to_string_before_user() . $self->quoted_db_user() . '@' . $self->quoted_db_host();
if ( length $self->db_rest() ) {
$str .= q{ } . $self->db_rest();
}
$str .= ';';
return $str;
}
sub db_name_pattern {
my ($self) = @_;
return Cpanel::MysqlUtils::unquote_identifier( $self->quoted_db_name() );
}
sub db_name_has_wildcard {
my ($self) = @_;
return 1 if $self->quoted_db_name() eq '*';
return 1 if $self->quoted_db_name() =~ m{(?<!\\)[_%]};
return 0;
}
sub matches_db_name {
my ( $self, $db ) = @_;
return 1 if $self->quoted_db_name() eq '*';
my $mysql_pattern = $self->db_name_pattern();
return Cpanel::MysqlUtils::like( $db, $mysql_pattern );
}
sub db_host_pattern {
my ($self) = @_;
return Cpanel::MysqlUtils::unquote( $self->quoted_db_host() );
}
sub db_host_has_wildcard {
my ($self) = @_;
return 1 if $self->quoted_db_host() =~ m{(?<!\\)[_%]};
return 0;
}
sub matches_db_host {
my ( $self, $db ) = @_;
return 1 if $self->quoted_db_host() eq '*';
my $mysql_pattern = $self->db_host_pattern();
return Cpanel::MysqlUtils::like( $db, $mysql_pattern );
}
sub password {
my ($self) = @_;
my ($quoted) = $self->db_rest() =~ m<IDENTIFIED\s+BY\s+(\S+)>i;
if ( !$quoted || $quoted =~ m<\APASSWORD\s>i ) {
my $string = $self->to_string();
die "The grant “$string” does not contain an unhashed password.";
}
return Cpanel::MysqlUtils::unquote($1);
}
sub hashed_password {
my ($self) = @_;
my ($quoted) = $self->db_rest() =~ m<IDENTIFIED\s+BY\s+PASSWORD\s+(\S+)>i;
if ( !$quoted ) {
my $string = $self->to_string();
die "The grant “$string” does not contain a hashed password.";
}
return Cpanel::MysqlUtils::unquote($1);
}
sub to_string_for_users {
my ( $self, @users_ar ) = @_;
my @user_strs;
for my $user_hr (@users_ar) {
my $str = Cpanel::MysqlUtils::quote( $user_hr->{'user'} ) . '@' . Cpanel::MysqlUtils::quote( $user_hr->{'host'} );
if ( defined $user_hr->{'hashed_password'} ) {
$str .= ' IDENTIFIED BY PASSWORD ' . Cpanel::MysqlUtils::quote( $user_hr->{'hashed_password'} );
}
elsif ( defined $user_hr->{'password'} ) {
$str .= ' IDENTIFIED BY ' . Cpanel::MysqlUtils::quote( $user_hr->{'password'} );
}
push @user_strs, $str;
}
return $self->_to_string_before_user() . join( ',', @user_strs ) . ';';
}
sub _to_string_before_user {
my ($self) = @_;
my $str = sprintf 'GRANT %s ON%s %s.%s TO ', (
$self->db_privs(),
$self->db_object_type() ? ' ' . $self->db_object_type() : '',
$self->quoted_db_name(),
$self->quoted_db_obj(), # db_obj is a MySQL object_type of: TABLE, FUNCTION, and/or PROCEDURE
);
return $str;
}
1;
} # --- END Cpanel/MysqlUtils/Grants.pm
{ # --- BEGIN Cpanel/MysqlUtils/Quote.pm
package Cpanel::MysqlUtils::Quote;
use strict;
my @_orig_QUOTE_ESCAPE_CHARACTER = (
"\0" => '0',
q(') => q('),
q(") => q("),
"\x{a}" => 'n',
"\x{d}" => 'r',
"\x{1a}" => 'Z',
'\\' => '\\',
);
my @unquote_unescape = (
b => "\b",
t => "\t",
);
our %QUOTE_ESCAPE_CHARACTER;
our @PATTERN_ESCAPE_CHARACTERS = qw( \ _ % );
our $PATTERN_ESCAPE_REGEXP_PART;
our $QUOTE_REGEXP_PART;
our $QUOTE_PATTERN_REGEXP_PART;
our $UNQUOTE_PATTERN_REGEXP_PART;
our $UNQUOTE_REGEXP_PART;
our %UNQUOTE_ORIGINAL_CHARACTER;
our $DID_QUOTE_INIT = 0;
sub quote_init {
return if $DID_QUOTE_INIT;
$DID_QUOTE_INIT = 1; # extra safety in case the glob is copied.
%QUOTE_ESCAPE_CHARACTER = @_orig_QUOTE_ESCAPE_CHARACTER;
$PATTERN_ESCAPE_REGEXP_PART = join( '', map { quotemeta($_) } @PATTERN_ESCAPE_CHARACTERS );
$QUOTE_REGEXP_PART = join( '', map { quotemeta($_) } keys %QUOTE_ESCAPE_CHARACTER );
@QUOTE_ESCAPE_CHARACTER{@PATTERN_ESCAPE_CHARACTERS} = @PATTERN_ESCAPE_CHARACTERS;
$QUOTE_PATTERN_REGEXP_PART = join( '', map { quotemeta($_) } keys %QUOTE_ESCAPE_CHARACTER );
%QUOTE_ESCAPE_CHARACTER = (
%QUOTE_ESCAPE_CHARACTER,
reverse @unquote_unescape,
);
$UNQUOTE_PATTERN_REGEXP_PART = join( '', map { quotemeta($_) } values %QUOTE_ESCAPE_CHARACTER );
%UNQUOTE_ORIGINAL_CHARACTER = reverse %QUOTE_ESCAPE_CHARACTER;
%QUOTE_ESCAPE_CHARACTER = (
@_orig_QUOTE_ESCAPE_CHARACTER,
reverse @unquote_unescape,
);
$UNQUOTE_REGEXP_PART = join( '', map { quotemeta($_) } values %QUOTE_ESCAPE_CHARACTER );
@QUOTE_ESCAPE_CHARACTER{@PATTERN_ESCAPE_CHARACTERS} = @PATTERN_ESCAPE_CHARACTERS;
{
no warnings 'redefine';
*quote_init = sub { };
}
return;
}
sub quote {
my ($copy) = @_;
return 'NULL' if !defined $copy;
return qq{'$copy'} if $copy !~ tr<\0'"\x{a}\x{d}\x{1a}\\><>;
quote_init();
$copy =~ s{([$Cpanel::MysqlUtils::Quote::QUOTE_REGEXP_PART]{1})}{\\$Cpanel::MysqlUtils::Quote::QUOTE_ESCAPE_CHARACTER{$1}}g;
return qq{'$copy'};
}
1;
} # --- END Cpanel/MysqlUtils/Quote.pm
{ # --- BEGIN Cpanel/MysqlUtils/MyCnf/Full.pm
package Cpanel::MysqlUtils::MyCnf::Full;
our $VERSION = '1.0';
# use Cpanel::ConfigFiles ();
sub etc_my_cnf_preserve_lines {
my $my_cnf = shift() || $Cpanel::ConfigFiles::MYSQL_CNF;
my @results = ();
my $fh;
if ( !open( $fh, '<', $my_cnf ) ) {
my $logger = Cpanel::Logger->new();
$logger->info("Could not open the mysql config file: $my_cnf; $!");
return;
}
my $section = '';
while ( my $line = <$fh> ) {
my $line_item = { 'line' => $line };
push @results, $line_item;
next if $line =~ /^\s*[#;]/;
my ( $key, $value );
$line_item->{'eol_comment'} = $1 if $line =~ s{(\s*(?<!\\)#.*)}{}; # Save the end of line comment, so we can put it back if need be
$line =~ s{(?:^\s*|\s*$)}{}g; # better than chomp
next if $line eq '';
if ( $line =~ m/^\[(.*?)\]/ ) {
$section = $1;
}
elsif ( $line =~ m/(\S+?)\s*=\s*(["'])(.*?)\2/ ) {
$key = $1;
$value = $3;
$value = '' if !defined $value;
}
elsif ( $line =~ m/(\S+?)\s*=\s*(\S+)/ ) {
$key = $1;
$value = $2;
$value = '' if !defined $value;
}
elsif ( $line =~ m/^\s*(\S+)\s*=\s*$/ ) {
$key = $1;
$value = '';
}
elsif ( $line =~ m/^\s*(\S+)\s*$/ ) {
$key = $1;
$value = '';
}
$line_item->{'section'} = $section;
$line_item->{'key'} = $key;
$line_item->{'value'} = $value;
}
close $fh;
return \@results;
}
sub etc_my_cnf {
my $my_cnf = shift() || $Cpanel::ConfigFiles::MYSQL_CNF;
my $stash = {};
if ( open( my $fh, '<', $my_cnf ) ) {
my $section = '';
while ( my $line = <$fh> ) {
next if $line =~ /^\s*[\#\;]/;
$line =~ s{\s*(?<!\\)\#.*}{}; # strip end of line comments (if \# is not a valid way to incldue a literal # then the look behind can be dropped)
$line =~ s{(?:^\s*|\s*$)}{}g; # better than chomp
next if $line eq '';
if ( $line =~ m/^\[(.*?)\]/ ) {
$section = $1;
}
elsif ( $line =~ m/(\S+?)\s*=\s*(["'])(.*?)\2/ ) {
$stash->{$section}{$1} = $3;
}
elsif ( $line =~ m/(\S+?)\s*=\s*(\S+)/ ) {
$stash->{$section}{$1} = $2;
}
elsif ( $line =~ m/^\s*(\S+)\s*=\s*$/ ) {
$stash->{$section}{$1} = '';
}
elsif ( $line =~ m/^\s*(\S+)\s*$/ ) {
$stash->{$section}{$1} = undef; # ? or should this be '1' ?
}
}
close $fh;
if ( exists $stash->{''} ) {
require Cpanel::Logger;
my $logger = Cpanel::Logger->new();
$logger->info("error: Found option without preceding group in config file: $my_cnf");
if ( !exists $stash->{'mysqld'} ) {
$logger->info("Assigning 'options without preceding group' to non-existant 'mysqld' group");
$stash->{'mysqld'} = $stash->{''};
}
}
return $stash;
}
return;
}
1;
} # --- END Cpanel/MysqlUtils/MyCnf/Full.pm
{ # --- BEGIN Cpanel/MysqlUtils.pm
package Cpanel::MysqlUtils;
use strict;
use warnings;
use IPC::Open3 ();
use Try::Tiny;
# use Cpanel::CachedCommand ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::ConfigFiles ();
# use Cpanel::DB::Prefix ();
# use Cpanel::DIp::MainIP ();
# use Cpanel::DbUtils ();
# use Cpanel::Exception ();
# use Cpanel::LoadModule ();
# use Cpanel::Logger ();
# use Cpanel::Mysql::Error ();
# use Cpanel::MysqlUtils::Grants ();
# use Cpanel::MysqlUtils::Quote ();
# use Cpanel::MysqlUtils::Version ();
# use Cpanel::MysqlUtils::MyCnf::Basic ();
# use Cpanel::MysqlUtils::MyCnf::Full ();
# use Cpanel::SafeRun::Object ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::SafeRun::Errors ();
# use Cpanel::SocketIP ();
# use Cpanel::Sys::Hostname ();
# use Cpanel::UTF8 ();
our $VERSION = '2.9';
my $logger = Cpanel::Logger->new();
my $mysql_bin;
my $mycnf;
our $mysqldatadir; # must stay undefined
my $mysql_version; # must stay undefined
our @_EXTRA_MYSQL_ARGS;
sub DB_MYSQL { return 'mysql' }
{
no warnings 'once';
*find_mysql = \&Cpanel::DbUtils::find_mysql;
*find_mysql_config = \&Cpanel::DbUtils::find_mysql_config;
*find_mysql_fix_privilege_tables = \&Cpanel::DbUtils::find_mysql_fix_privilege_tables;
*find_mysqldump = \&Cpanel::DbUtils::find_mysqldump;
*find_mysqladmin = \&Cpanel::DbUtils::find_mysqladmin;
*find_mysqlcheck = \&Cpanel::DbUtils::find_mysqlcheck;
*find_mysqld = \&Cpanel::DbUtils::find_mysqld;
*_getmydb_param = \&Cpanel::MysqlUtils::MyCnf::Basic::_getmydb_param;
*_getmydbparm = \&Cpanel::MysqlUtils::MyCnf::Basic::_getmydbparm;
*getmydbuser = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbuser;
*getmydbpass = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbpass;
*getmydbhost = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbhost;
*getmydbport = \&Cpanel::MysqlUtils::MyCnf::Basic::getmydbport;
*is_remote_mysql = \&Cpanel::MysqlUtils::MyCnf::Basic::is_remote_mysql;
*find_mysql_upgrade = \&Cpanel::DbUtils::find_mysql_upgrade;
*quote = \&Cpanel::MysqlUtils::Quote::quote;
}
sub db_exists {
my $db = $_[0];
if ( !is_remote_mysql() ) {
my $datadir = getmysqldir() || return 0;
return 1 if -e $datadir . '/' . $db;
}
$db = safesqlstring($db);
my $ms = sqlcmd("SHOW DATABASES LIKE '$db';") || '';
$ms =~ s/\s//g;
return ( $ms =~ /\A\Q$db\E\z/ ) ? 1 : 0;
}
sub user_exists {
my ( $user, $dbh ) = @_;
my $exists;
if ($dbh) {
$exists = $dbh->selectrow_array( "SELECT COUNT(user) FROM mysql.user WHERE user = ? LIMIT 1;", undef, $user );
}
else {
my $quoted_user = quote($user);
$exists = sqlcmd("SELECT COUNT(user) FROM mysql.user WHERE user = $quoted_user LIMIT 1;");
}
return $exists ? 1 : 0;
}
sub decode_mysql_output {
return $_[0] if $_[0] !~ tr/\\//;
my ($string) = @_;
$string =~ s/(?<!\\)\\t/\t/g; # Restore tabs
$string =~ s/(?<!\\)\\n/\n/g; # Restore newlines
$string =~ s/(?<!\\)\\0/\0/g; # Restore nulls
$string =~ s/\\\\/\\/g; # Restore backslashes
return $string;
}
sub encode_mysql_output {
return if !defined $_[0];
return $_[0] if $_[0] !~ tr/\n\t\0\\//;
my ($string) = @_;
$string =~ s/\\/\\\\/g; # Escape backslashes
$string =~ s/\0/\\0/g; # Escape nulls
$string =~ s/\n/\\n/g; # Escape newlines
$string =~ s/\t/\\t/g; # Escape tabs
return $string;
}
sub safesqlstring {
$_[0] !~ tr/\\\0\n\r'"\?\x1a// ? $_[0] : substr( quote( $_[0] ), 1, -1 );
}
sub like {
my ( $operand, $pattern ) = @_;
tr{A-Z}{a-z} for ( $operand, $pattern );
my %string_escape_chars = (
( reverse %Cpanel::MysqlUtils::Quote::QUOTE_ESCAPE_CHARACTER ),
( map { $_ => $_ } @Cpanel::MysqlUtils::Quote::PATTERN_ESCAPE_CHARACTERS ),
);
my $regexp;
while ( length $pattern ) {
my $char = substr( $pattern, 0, 1, q{} );
if ( $char eq q{\\} ) {
my $escaped_char = substr( $pattern, 0, 1, q{} );
if ( length $escaped_char ) {
$regexp .= quotemeta( $string_escape_chars{$escaped_char} || $escaped_char );
}
else {
$regexp .= quotemeta $char;
}
}
elsif ( $char eq '_' ) {
$regexp .= '.';
}
elsif ( $char eq '%' ) {
$regexp .= '.*';
}
else {
$regexp .= quotemeta $char;
}
}
return ( $operand =~ $regexp ) ? 1 : 0;
}
sub quote_conf_value {
return $_[0] if $_[0] !~ tr/"\n\t\0\\//;
my ($string) = @_;
$string =~ s/\\/\\\\/g; # Escape backslashes
$string =~ s/\0/\\0/g; # Escape nulls
$string =~ s/"/\\"/g; # Escape double quotes
$string =~ s/\n/\\n/g; # Escape newlines
$string =~ s/\r/\\r/g; # Escape line feeds
$string =~ s/\t/\\t/g; # Escape tabs
return $string;
}
sub quote_pattern_identifier {
my ($copy) = @_;
return 'NULL' if !defined $copy;
return "`$copy`" if $copy !~ tr/`_%//;
$copy =~ s{`}{``}g;
$copy =~ s{_}{\\_}g;
$copy =~ s{%}{\\%}g;
return "`$copy`";
}
sub quote_pattern {
my ($copy) = @_;
return 'NULL' if !defined $copy;
return qq{'$copy'} if $copy !~ tr/\0'"\x{a}\x{d}\x{1a}\\_%//;
Cpanel::MysqlUtils::Quote::quote_init();
$copy =~ s{([$Cpanel::MysqlUtils::Quote::QUOTE_PATTERN_REGEXP_PART]{1})}{\\$Cpanel::MysqlUtils::Quote::QUOTE_ESCAPE_CHARACTER{$1}}g;
return qq{'$copy'};
}
sub escape_pattern {
my ($copy) = @_;
Cpanel::MysqlUtils::Quote::quote_init();
$copy =~ s{([$Cpanel::MysqlUtils::Quote::PATTERN_ESCAPE_REGEXP_PART])}{\\$1}g;
return $copy;
}
sub unescape_pattern {
my ($copy) = @_;
Cpanel::MysqlUtils::Quote::quote_init();
$copy =~ s{\\([$Cpanel::MysqlUtils::Quote::PATTERN_ESCAPE_REGEXP_PART])}{$1}g;
return $copy;
}
sub unquote {
my ($copy) = @_;
return undef if $copy eq 'NULL';
_unquote_quotes($copy) if $copy =~ tr/'"//; # operates on $copy
Cpanel::MysqlUtils::Quote::quote_init();
$copy =~ s{\\([^$Cpanel::MysqlUtils::Quote::UNQUOTE_PATTERN_REGEXP_PART]{1})}{$1}g;
$copy =~ s{\\([$Cpanel::MysqlUtils::Quote::UNQUOTE_REGEXP_PART]{1})}{$Cpanel::MysqlUtils::Quote::UNQUOTE_ORIGINAL_CHARACTER{$1}}g;
return $copy;
}
sub unquote_pattern {
my ($copy) = @_;
return undef if $copy eq 'NULL';
_unquote_quotes($copy) if $copy =~ tr/'"//; # operates on $copy
Cpanel::MysqlUtils::Quote::quote_init();
$copy =~ s{\\([^$Cpanel::MysqlUtils::Quote::UNQUOTE_PATTERN_REGEXP_PART]{1})}{$1}g;
$copy =~ s{\\([$Cpanel::MysqlUtils::Quote::UNQUOTE_PATTERN_REGEXP_PART]{1})}{$Cpanel::MysqlUtils::Quote::UNQUOTE_ORIGINAL_CHARACTER{$1}}g;
return $copy;
}
sub _unquote_quotes {
if ( $_[0] =~ s{\A'}{} ) {
$_[0] =~ s{'\z}{};
$_[0] =~ s{''}{'}g;
}
elsif ( $_[0] =~ s{\A"}{} ) {
$_[0] =~ s{"\z}{};
$_[0] =~ s{""}{"}g;
}
}
sub quote_identifier {
my ($copy) = @_;
return '' if !defined $copy;
return "`$copy`" if $copy !~ tr/`_%//;
$copy =~ s{`}{``}g;
return "`$copy`";
}
our ( $QUOTED_IDENTIFIER_REGEXP, $IDENTIFIER_REGEXP );
BEGIN {
$QUOTED_IDENTIFIER_REGEXP = qr{`(?:``|[\x{0001}-\x{005f}\x{0061}-\x{ffff}])+`};
$IDENTIFIER_REGEXP = qr{(?:$QUOTED_IDENTIFIER_REGEXP|(?:[0-9a-zA-Z\x{0080}-\x{ffff}\$_])+)};
}
sub unquote_identifier {
my ($copy) = @_;
return undef if !defined $copy;
if ( $copy =~ s{\A`}{} ) {
$copy =~ s{`\z}{};
$copy =~ s{``}{`}g;
}
return $copy;
}
sub unquote_pattern_identifier {
my ($copy) = @_;
return undef if $copy eq 'NULL';
if ( $copy =~ s{\A`}{} ) {
$copy =~ s{`\z}{};
$copy =~ s{``}{`}g;
$copy =~ s{\\_}{_}g;
$copy =~ s{\\%}{%}g;
}
return $copy;
}
sub is_create_statement { ##no critic qw(RequireArgUnpacking)
return ( $_[0] =~ m<\A\s*(?:/\*!\d+\s+)?CREATE(?:\*/|\s+)>i ) ? 1 : 0;
}
our $QUOTED_STRING_REGEXP = q{(?^x:
'
(?:
'' #this must be first!
|
[^\\\\']* #anything but a backslash or quote
(?:
\\\\. #backslash plus anything
[^\\\\']* #anything but a backslash or quote
)*
)*
'
)};
my $MYSQL_VAR_NAME_REGEXP = qq{(?^x:
[a-zA-Z0-9._\$]+ #unquoted can have alphanums and: . _ \$
|
$QUOTED_IDENTIFIER_REGEXP
|
$QUOTED_STRING_REGEXP
)};
sub parse_set_statement { ##no critic qw(RequireArgUnpacking)
my ( $key, $value ) = (
$_[0] =~ m<
\A
\s*
(?:/\*!\d+\s+)?
SET
\s+
(
\@? #user-defined variables are prefixed with @
$MYSQL_VAR_NAME_REGEXP
)
\s*
=
\s*
(
\S+
|
$QUOTED_STRING_REGEXP
)
>xi
);
return $key ? ( $key, $value ) : ();
}
sub get_server_version {
my ($dbh) = @_;
return $dbh->selectrow_array('SELECT VERSION()');
}
sub _max_mysql_for_comment {
my ($version) = @_;
if ( 1 == $version =~ tr<.><> ) {
$version .= ".99";
}
return Cpanel::MysqlUtils::Version::string_to_number($version);
}
sub identifier_must_be_quoted {
my $id = shift;
return 1 if !length $id;
return 1 if $id !~ tr<0-9><>c;
while ( $id =~ m<([^0-9a-zA-Z\$_]+)>g ) {
my $codes_ar = Cpanel::UTF8::get_unicode_as_code_point_list($1);
return 1 if grep { $_ < 0x80 } @$codes_ar;
}
return 0;
}
sub rename_db_in_command {
my ( $db, $new_db, $stmt ) = @_;
my ( $db_q, $new_db_q ) = map { quote_identifier($_) } ( $db, $new_db );
if ( !identifier_must_be_quoted($db) ) {
$stmt = _alter_stripped_string(
$stmt,
_regexp_to_capture_any_quoted_entity(),
sub { s[(?<! \. ) (\s*) (\Q$db\E) (?= \s* \.)][$1$new_db_q]xg },
);
}
my $db_re = qr[
(?<! \. ) (\s*)
(\Q$db_q\E)
(?= \s* \.)
]x;
return _alter_stripped_string(
$stmt,
qr<($QUOTED_STRING_REGEXP)>x,
sub { s<$db_re><$1$new_db_q>g },
);
}
sub replace_in_command_outside_quoted_strings {
my ( $pattern, $new_text, $command ) = @_;
return _alter_stripped_string(
$command,
_regexp_to_capture_any_quoted_entity(),
sub { s<$pattern><$new_text>g },
);
}
sub _regexp_to_capture_any_quoted_entity {
return qr<(
$QUOTED_IDENTIFIER_REGEXP
|
$QUOTED_STRING_REGEXP
)>x;
}
sub _alter_stripped_string {
my ( $string, $strip_re, $alter_cr ) = @_;
my @replaced_strings;
my $random_bit = rand();
$random_bit =~ tr<0-9><>cd;
my $cp_string_prefix = "__CP_STRING__$random_bit\__";
my $count = 0;
$string =~ s<$strip_re><
$count++;
push @replaced_strings, $1;
$cp_string_prefix . ($count - 1);
>eg;
$alter_cr->() for $string; #set $_ to the string
$string =~ s<$cp_string_prefix(\d+)><$replaced_strings[$1]>g;
return $string;
}
sub strip_comments_for_version {
my ( $version, $stmt ) = @_;
if ( UNIVERSAL::isa( $version, 'DBI::db' ) ) {
($version) = get_server_version($version);
}
my $pattern_re = _regexp_to_capture_any_quoted_entity();
my $max_mysql = _max_mysql_for_comment($version);
return _alter_stripped_string(
$stmt,
$pattern_re,
sub {
s{
/\*!([0-9]+)\s+(.*?)\s*\*/
}{
($1 < $max_mysql) ? $2 : q<>
}xegs;
},
);
}
sub getmysqldir {
if ( defined $mysqldatadir ) { return $mysqldatadir; }
if ( $> == 0 ) {
my $mysqlhost = getmydbhost();
return if is_remote_mysql();
my $mysqladmin = Cpanel::DbUtils::find_mysqladmin();
my $mysqladmin_output_ref = Cpanel::CachedCommand::_cached_cmd(
'binary' => $mysqladmin,
'args' => ['variables'],
'mtime' => ( stat($Cpanel::ConfigFiles::MYSQL_CNF) )[9] || 0,
'ttl' => 86400,
'suppress_errors' => 1,
);
if ( ref $mysqladmin_output_ref ) {
$$mysqladmin_output_ref =~ s/\|//g;
if ( $$mysqladmin_output_ref =~ m/\s+datadir\s+(\S+)/ ) {
$mysqldatadir = $1;
}
}
if ( !$mysqldatadir ) {
my $mycnf = Cpanel::MysqlUtils::MyCnf::Full::etc_my_cnf();
if ( $mycnf->{'mysqld'} ) {
$mysqldatadir = $mycnf->{'mysqld'}{'datadir'};
}
}
}
else {
local $@;
my $temp_mysql_env = eval { require Cpanel::MysqlUtils::TempEnv; Cpanel::MysqlUtils::TempEnv->new(); };
if ($temp_mysql_env) {
my $mysql_bin = Cpanel::DbUtils::find_mysql();
my @mysql_param = $temp_mysql_env->get_mysql_params();
my $variable_output = $temp_mysql_env->exec_coderef(
sub {
return scalar Cpanel::SafeRun::Errors::saferunnoerror( $mysql_bin, @mysql_param, '-N', '-e', 'SHOW VARIABLES LIKE "datadir";' );
}
);
if ( $variable_output =~ m/[\|\s]+(\/.*)/ ) {
$mysqldatadir = $1;
$mysqldatadir =~ s/[\s\|]+$//g;
}
}
}
if ( !$mysqldatadir ) {
if ( -d '/var/lib/mysql' ) {
$mysqldatadir = '/var/lib/mysql/'; # Linux default
}
elsif ( -d '/var/db/mysql' ) {
$mysqldatadir = '/var/db/mysql/'; # Default for no cost devil mascot
}
else {
$logger->warn('Failed to determine MySQL data directory. Please check the MySQL installation.');
return;
}
}
while ( -l $mysqldatadir ) {
$mysqldatadir = readlink $mysqldatadir;
}
return $mysqldatadir;
}
sub get_db_names {
my $out = sqlcmd( "SHOW DATABASES", { nodb => 1 } );
return [ split m{[\r\n]+}, $out ];
}
sub new {
shift @_ if ( $_[0] eq __PACKAGE__ ); # Strip off this class name from the args list.
my @modules_to_try = qw(
Cpanel::MysqlUtils::Connect
);
my $module_to_use;
for my $module (@modules_to_try) {
my $module_path = "$module.pm";
$module_path =~ s{::}{/}g;
if ( exists $INC{$module_path} ) {
$module_to_use = $module;
last;
}
}
local $@;
if ( !$module_to_use ) {
for my $module (@modules_to_try) {
if ( eval { Cpanel::LoadModule::load_perl_module($module) } ) {
$module_to_use = $module;
last;
}
}
}
if ( !$module_to_use ) {
die "The system failed to load a Cpanel MySQL client module. (Attempted modules: @modules_to_try) The last error was: $@";
}
my $obj = $module_to_use->new(@_) or die "Could not connect using $module_to_use: $@";
return $obj->{'dbh'};
}
sub get_db_handle {
my $module = _get_cpmysql_module() or die "No cpmysql module!";
return $module->instance()->db_handle();
}
sub _get_cpmysql_module {
if ( exists $INC{'Cpanel/MysqlUtils/Connect.pm'} ) {
return 'Cpanel::MysqlUtils::Connect';
}
return;
}
sub sqlcmd {
my (@args) = @_;
my $module = _get_cpmysql_module();
return _forked_sqlcmd(@args) if !$module;
my $result = $module->instance()->sqlcmd(@args);
if ( !length $result ) {
$result = undef;
}
return $result;
}
sub _forked_sqlcmd {
my ( $cmds, $opts ) = @_;
my ( @preargs, @args );
if ( $opts->{'nodb'} ) {
$mycnf ||= Cpanel::MysqlUtils::MyCnf::Basic::get_dot_my_dot_cnf('root');
@preargs = ( '--defaults-extra-file=' . $mycnf );
}
else {
@args = ( $opts->{'db'} || 'mysql' );
}
push @preargs, '-N' unless $opts->{'column_names'};
if ( $opts->{'multi_fallback_ok'} && ref $cmds ) {
$cmds = join( ";\n", @{$cmds} );
}
my $result = '';
my $retcode;
my $did_select;
foreach my $cmd ( ref $cmds ? ( @{$cmds} ) : ($cmds) ) {
my ( $wtrfh, $rdrfh );
$mysql_bin ||= find_mysql();
my $mysql_results = Cpanel::SafeRun::Object->new(
'program' => $mysql_bin,
'args' => [ @preargs, '-B', '-A', @args ],
'stdin' => \"$cmd\n",
);
$did_select = $cmd =~ /^\s*(?:show|select)/i ? 1 : 0;
$retcode = $mysql_results->CHILD_ERROR();
if ( length $mysql_results->stderr() ) {
$result .= join( "\n", grep( !m/^Warning:/, split( m{\n}, $mysql_results->stderr() ) ) );
}
$result .= $mysql_results->stdout();
}
$result =~ s/\n$// if length $result; #match Connect output
if ( !$did_select && !length($result) && $retcode == 0 ) {
$result = '0E0';
}
return $result;
}
sub is_local_mysql {
my $mysql_host = shift || getmydbhost('root') || 'localhost';
return Cpanel::MysqlUtils::MyCnf::Basic::is_remote_mysql($mysql_host) ? 0 : 1;
}
sub mysqlversion {
local $@;
return eval { Cpanel::MysqlUtils::Version::mysqlversion() } || Cpanel::MysqlUtils::Version::get_short_mysql_version_from_data_files() || $Cpanel::MysqlUtils::Version::DEFAULT_MYSQL_RELEASE_TO_ASSUME_IS_INSTALLED;
}
sub get_server {
if ( !is_remote_mysql() ) {
return Cpanel::DIp::MainIP::getmainserverip();
}
else {
my $server = getmydbhost('root');
return Cpanel::SocketIP::_resolveIpAddress($server);
}
}
sub get_grant_host {
return is_remote_mysql() ? Cpanel::Sys::Hostname::gethostname() : 'localhost';
}
sub get_procedures_by_definer {
my ( $dbh, $definer ) = @_;
return $dbh->selectall_arrayref( q<SELECT ROUTINE_SCHEMA as database_name, ROUTINE_NAME name FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND SUBSTRING_INDEX(DEFINER,'@',1) = ?>, { Slice => {} }, $definer );
}
sub get_functions_by_definer {
my ( $dbh, $definer ) = @_;
return $dbh->selectall_arrayref( q<SELECT ROUTINE_SCHEMA as database_name, ROUTINE_NAME as name FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND SUBSTRING_INDEX(DEFINER,'@',1) = ?>, { Slice => {} }, $definer );
}
sub get_views_by_definer {
my ( $dbh, $definer ) = @_;
my $dbs_ar = _get_dbs_for_dbuser( $dbh, $definer );
my @payload;
for my $db (@$dbs_ar) {
my $views_ar = $dbh->selectcol_arrayref( q<SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ? and SUBSTRING_INDEX(DEFINER,'@',1) = ?>, { Slice => {} }, $db, $definer );
push @payload, map { { database_name => $db, name => $_ } } @$views_ar;
}
return \@payload;
}
sub get_triggers_by_definer {
my ( $dbh, $definer ) = @_;
my $dbs_ar = _get_dbs_for_dbuser( $dbh, $definer );
my @payload;
for my $db (@$dbs_ar) {
my $quoted_db = $dbh->quote_identifier($db);
my $views_ar = $dbh->selectcol_arrayref( qq<SHOW TRIGGERS IN $quoted_db WHERE SUBSTRING(DEFINER,1,1 + LENGTH(?)) = CONCAT(?, '\@')>, { Slice => {} }, $definer, $definer );
push @payload, map { { database_name => $db, name => $_ } } @$views_ar;
}
return \@payload;
}
sub _get_dbs_for_dbuser {
my ( $dbh, $dbuser ) = @_;
return $dbh->selectcol_arrayref( q<SELECT DISTINCT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA, mysql.db WHERE SCHEMA_NAME LIKE mysql.db.db AND mysql.db.user = ?>, undef, $dbuser );
}
sub get_events_by_definer {
my ( $dbh, $definer ) = @_;
if ( !server_supports_events($dbh) ) {
return [];
}
return $dbh->selectall_arrayref( q<SELECT EVENT_SCHEMA as database_name, EVENT_NAME as name FROM INFORMATION_SCHEMA.EVENTS WHERE SUBSTRING_INDEX(DEFINER,'@',1) = ?>, { Slice => {} }, $definer );
}
sub process_sql_file {
my %opts = @_;
if ( 'SCALAR' ne ref $opts{'out_ref'} ) {
return 0, 'Invalid output reference provided';
}
elsif ( !-r $opts{'file'} ) {
return 0, "Unable to read file $opts{'file'}";
}
elsif ( !$opts{'db'} ) {
return 0, 'Invalid database name provided';
}
$mysql_bin ||= find_mysql();
my @command_line = ( '-B', '-A', '--force', $opts{'db'} );
unshift @command_line, "--defaults-file=$opts{'defaults-file'}" if $opts{'defaults-file'};
push @command_line, @_EXTRA_MYSQL_ARGS;
my ( $msg, $rh );
if ( open( my $wh, '<', $opts{'file'} ) ) {
my $e;
if ( my $pid = open( my $rh, '-|' ) ) {
local $/;
${ $opts{'out_ref'} } = readline($rh);
waitpid $pid, 0;
$e = $?; # save value before close
close $rh;
}
elsif ( defined $pid ) {
no strict 'subs';
open( STDIN, '<&=' . fileno($wh) );
exec( $mysql_bin, @command_line ) or do {
die "Failed to execute $mysql_bin @command_line: $!";
};
}
else {
return 0, "Failed to fork(): $!";
}
return 1 if !( $e >> 8 );
if ( $e == -1 ) {
$msg = "Execution of $mysql_bin @command_line failed: $!";
}
elsif ( $e & 127 ) {
$msg = "Execution of $mysql_bin @command_line died with signal: " . ( $e & 127 );
}
else {
$msg = "Execution of $mysql_bin @command_line exited with value: " . ( $e >> 8 );
}
close($wh);
}
else {
$msg = "Failed to open $opts{'file'}: $!";
}
return 0, $msg;
}
sub _set_binding {
my ( $stmt, @bind ) = @_;
if ( ( scalar @bind > 0 ) and ( ( $stmt =~ tr/?// ) == scalar @bind ) ) {
return join( '', map { $_, @bind ? quote( shift @bind ) : () } split( m/\?/, $stmt ) );
}
return $stmt;
}
sub fetch_hashref {
if ( exists $INC{'Cpanel/MysqlUtils/Connect.pm'} ) {
return Cpanel::MysqlUtils::Connect->instance()->fetch_hashref(@_);
}
my ( $stmt, @bind ) = @_;
$stmt = _set_binding( $stmt, @bind );
my $data = _runsqlcmd($stmt);
my @mysql_data = split /\n/, $data;
my @field_names = split( /\t/, shift(@mysql_data) ); # single tab only
my $field_count = scalar @field_names;
my @result_set;
foreach my $row (@mysql_data) {
my @row = map { decode_mysql_output($_) } split /\t/, $row, $field_count; # single tab only
my $results = {};
my $count = 0;
foreach my $field (@field_names) {
$results->{$field} = $row[$count];
$count++;
}
push @result_set, $results;
}
return \@result_set;
}
sub do_sql {
my ( $stmt, @bind ) = @_;
local $@;
$stmt = _set_binding( $stmt, @bind );
my $data = _runsqlcmd($stmt);
return ( $@ || $data =~ m/^\s*ERROR/ ) ? 0 : 1;
}
sub _runsqlcmd {
sqlcmd( $_[0], { 'nodb' => 1, 'column_names' => 1 } );
}
sub stream_mysqldump_to_filehandle {
my ($args) = @_;
my $mysqldump = find_mysqldump();
local $ENV{'MYSQL_PWD'} = $args->{'dbpass'};
my $wfh;
my $rfh;
my $pid = IPC::Open3::open3(
$wfh, $rfh, ">/dev/null",
$mysqldump,
'--no-defaults',
'-u', $args->{'dbuser'},
'-h', $args->{'dbhost'},
( $args->{'dbport'} ? ( '--port', $args->{'dbport'} ) : () ),
@{ $args->{options} },
'--',
$args->{'db'},
);
close($wfh);
while ( my $data = <$rfh> ) {
print { $args->{'filehandle'} } $data;
}
close($rfh);
waitpid( $pid, 0 );
}
sub build_mysql_exec_env {
my ($env) = @_;
$mysql_bin ||= find_mysql();
return sub {
my ($sql) = @_;
if ( my $mysql_pid = open( my $mysql_input_fh, '|-' ) ) {
print {$mysql_input_fh} $sql;
close($mysql_input_fh);
}
else {
local $ENV{'MYSQL_PWD'} = $env->{'dbpass'};
exec $mysql_bin, '--no-defaults', '-h', $env->{'dbhost'}, '-u', $env->{'dbuser'}, ( $env->{'dbport'} ? ( '--port', $env->{'dbport'} ) : () ), $env->{'db'};
die "Could not exec($mysql_bin)";
}
}
}
sub stream_filehandle_to_mysql {
my ($args) = @_;
$mysql_bin ||= find_mysql();
my $wfh;
my $rfh;
my $efh;
my $pid = IPC::Open3::open3(
$wfh, $rfh, ">/dev/null",
$mysql_bin,
'--force',
$args->{'db'},
);
close($rfh);
my $fh = $args->{'filehandle'};
while ( my $line = <$fh> ) {
print {$wfh} $line;
}
print {$wfh} "\nFLUSH PRIVILEGES;\n";
close($wfh);
waitpid( $pid, 0 );
}
sub assign_db_procs_to_user {
my ( $dbh, $olddbname, $newuser ) = @_;
die 'Only for DB prefixing' if !Cpanel::DB::Prefix::use_prefix();
my $cmd = join(
"\n",
'UPDATE mysql.proc',
'SET',
"db = CONCAT( ?, '_', SUBSTRING_INDEX(db, '_', -1) ),",
"definer = CONCAT( ?, '_', SUBSTRING_INDEX(definer, '_', -1) )",
"WHERE db = ?",
);
return $dbh->do( $cmd, undef, $newuser, $newuser, $olddbname );
}
sub get_all_hosts_for_users {
my ( $dbh, $users ) = @_;
my $user_list = join( ',', map { $dbh->quote($_) } @{$users} );
my $hosts_ar = $dbh->selectall_arrayref("SELECT user, host FROM mysql.user WHERE user IN ($user_list);");
my %user_hosts_map;
if ( $hosts_ar && @{$hosts_ar} ) {
foreach my $user_host ( @{$hosts_ar} ) {
my ( $user, $host ) = @{$user_host};
push @{ $user_hosts_map{$user} }, $host;
}
}
return \%user_hosts_map;
}
sub drop_user_in_mysql {
my ( $dbh, $user ) = @_;
my $user_hosts_map = get_all_hosts_for_users( $dbh, [$user] );
for my $host ( @{ $user_hosts_map->{$user} } ) {
$dbh->do( 'DROP USER ?@?', undef, $user, $host );
}
return 1;
}
sub show_grants_on_dbs {
my ( $dbh, @dbs ) = @_;
my @tables_to_query = qw(
SCHEMA_PRIVILEGES
TABLE_PRIVILEGES
COLUMN_PRIVILEGES
);
my $where_clause = join(
q{ OR },
map {
my $quoted_db = $dbh->quote($_);
"($quoted_db LIKE TABLE_SCHEMA)"
} @dbs
);
$where_clause ||= '0';
my $user_host_query = join( ' UNION ', map { "SELECT DISTINCT GRANTEE FROM INFORMATION_SCHEMA.$_ WHERE $where_clause" } @tables_to_query );
my $user_host_ar = $dbh->selectcol_arrayref($user_host_query);
if ( $dbh->err() ) {
die Cpanel::Exception->create( 'The query “[_1]” failed because of an error: [_2]', $user_host_query, $dbh->errstr() );
}
my @grants;
my $user_host_regexp = qr{\A($QUOTED_STRING_REGEXP)\@($QUOTED_STRING_REGEXP)\z}x;
local $dbh->{'RaiseError'} = 1;
while (@$user_host_ar) {
try {
while ( my $user_host = shift @$user_host_ar ) {
my ( $user, $host_pattern ) = map { unquote($_) } ( $user_host =~ $user_host_regexp );
my @grant_txts = $dbh->show_grants( $user, $host_pattern ) or do {
die Cpanel::Exception::create_raw( $dbh->errstr() );
};
for my $grant_txt (@grant_txts) {
my $grant_obj = Cpanel::MysqlUtils::Grants->new($grant_txt);
if ( grep { $grant_obj->matches_db_name($_) } @dbs ) {
push @grants, $grant_obj;
}
}
}
}
catch {
die $_ if $dbh->err() ne Cpanel::Mysql::Error::ER_NONEXISTING_GRANT();
};
}
return \@grants;
}
sub show_grants_for_user {
my ( $dbh, $user ) = @_;
local $dbh->{'RaiseError'} = 1;
my @grants;
my $hosts_ar = $dbh->selectall_arrayref( 'SELECT host FROM ' . DB_MYSQL() . '.user WHERE user = ?', undef, $user );
while (@$hosts_ar) {
try {
while ( my $host = ( shift @$hosts_ar || [] )->[0] ) {
my @grant_txts = $dbh->show_grants( $user, $host ) or next;
for my $grant_txt (@grant_txts) {
my $grant_obj = Cpanel::MysqlUtils::Grants->new($grant_txt);
push @grants, $grant_obj;
}
}
}
catch {
die $_ if $dbh->err() ne Cpanel::Mysql::Error::ER_NONEXISTING_GRANT();
}
}
return \@grants;
}
sub show_create_trigger {
my ( $dbh, $trigger_db, $trigger_name ) = @_;
if ( server_supports_show_create_trigger($dbh) ) {
my $full_name_q = _quote_db_and_name( $trigger_db, $trigger_name );
my $the_easy_way_ar = $dbh->selectrow_arrayref("SHOW CREATE TRIGGER $full_name_q");
return $the_easy_way_ar;
}
return _manual_show_create_trigger( $dbh, $trigger_db, $trigger_name );
}
sub server_supports_show_create_trigger {
my ($dbh) = @_;
return $dbh->{'mysql_serverversion'} >= 50121 ? 1 : 0;
}
sub server_supports_events {
my ($dbh) = @_;
return $dbh->{'mysql_serverversion'} >= 50106 ? 1 : 0;
}
sub _manual_show_create_trigger {
my ( $dbh, $trigger_db, $trigger_name ) = @_;
my $trigger_hr = $dbh->selectrow_hashref(
'SELECT * FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA=? AND TRIGGER_NAME=?',
{ Slice => {} },
$trigger_db,
$trigger_name,
);
my $full_trigger_name_q = _quote_db_and_name( $trigger_db, $trigger_name );
die "Trigger $full_trigger_name_q does not exist!" if !$trigger_hr;
my $create_stmt = join ' ', (
'CREATE',
'DEFINER=' . join(
'@',
map { $dbh->quote_identifier($_) }
split m<@>, $trigger_hr->{'DEFINER'}
),
'TRIGGER',
$full_trigger_name_q,
$trigger_hr->{'ACTION_TIMING'},
$trigger_hr->{'EVENT_MANIPULATION'},
'ON',
_quote_db_and_name( @{$trigger_hr}{qw(EVENT_OBJECT_SCHEMA EVENT_OBJECT_TABLE)} ),
'FOR EACH ROW',
$trigger_hr->{'ACTION_STATEMENT'},
);
return [
$trigger_name,
$trigger_hr->{'SQL_MODE'},
$create_stmt,
];
}
sub _quote_db_and_name {
my ( $db, $name ) = @_;
return join( '.', map { quote_identifier($_) } $db, $name );
}
sub is_mysql_running {
my $count = 0;
return 1 if $ENV{'RESTARTSRV'};
Cpanel::SafeRun::Simple::saferunnoerror( '/scripts/restartsrv_mysql', '--check' );
return $? == 0 ? 1 : 0;
}
sub get_mysql_error_log_file {
my $mycnf = Cpanel::MysqlUtils::MyCnf::Full::etc_my_cnf();
if ( $mycnf->{'mysqld'} ) {
if ( $mycnf->{'mysqld'}{'log-error'} ) {
return $mycnf->{'mysqld'}{'log-error'};
}
elsif ( $mycnf->{'mysqld'}{'log_error'} ) {
return $mycnf->{'mysqld'}{'log_error'};
}
}
my $datadir = getmysqldir() || '';
my $hostname = Cpanel::Sys::Hostname::gethostname();
my $shorthostname = Cpanel::Sys::Hostname::shorthostname();
my %logs;
foreach my $candidate ( "$datadir/$hostname.err", "$datadir/$shorthostname.err" ) {
if ( my $mtime = ( stat($candidate) )[9] ) {
$logs{$candidate} = $mtime;
}
}
if ( scalar keys %logs ) {
return ( sort { $logs{$b} <=> $logs{$a} } keys %logs )[0];
}
return "$datadir/$hostname.err";
}
1;
} # --- END Cpanel/MysqlUtils.pm
{ # --- BEGIN Cpanel/Update/Blocker/CpanelConfig.pm
package Cpanel::Update::Blocker::CpanelConfig;
use strict;
# use Cpanel::Update::Logger ();
# use Cpanel::Config::CpConfGuard ();
# use Cpanel::RPM::Versions::File ();
# use Cpanel::MysqlUtils::Versions ();
# use Cpanel::Version::Compare ();
# use Cpanel::RPM ();
my @BLOCKED_MYSQL_RELEASES = (
'3.23',
'4.0',
'4.1',
);
my @OLD_MYSQL_RELEASES_FOR_11_44 = ( '5.0', '5.1' );
my @SUPPORTED_MYSQL_RELEASES = ( '5.5', '5.6' ); # order matters
my @SUPPORTED_MARIADB_RELEASES = ( '10.0', '10.1' );
my $MINIMUM_RECOMMENDED_MYSQL_RELEASE = $SUPPORTED_MYSQL_RELEASES[0];
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 $rpmv = Cpanel::RPM::Versions::Directory->new( { 'mysql_targets' => [ Cpanel::MysqlUtils::Versions::get_rpm_target_names( Cpanel::MysqlUtils::Versions::get_installable_versions() ) ] } );
return {
'invalid' => 0,
'logger' => $logger,
'rpmv' => $rpmv,
'guard' => Cpanel::Config::CpConfGuard->new(),
};
}
sub cpconfig {
my $self = shift;
return $self->{'guard'}->{'data'};
}
sub is_mysql_version_valid {
my $self = shift;
my $mysql_version = $self->cpconfig()->{'mysql-version'} || '';
if ( $ENV{'CPANEL_BASE_INSTALL'} ) {
return 1 if $mysql_version eq '';
return 1 if grep { $mysql_version eq $_ } (
@SUPPORTED_MYSQL_RELEASES,
@SUPPORTED_MARIADB_RELEASES,
@OLD_MYSQL_RELEASES_FOR_11_44,
);
$self->{'invalid'}++;
return 0;
}
if ( !$self->is_mysql_supported_by_cpanel() ) {
$self->{'invalid'}++;
return 0;
}
return 1;
}
sub _double_check_mysqltarget_setting {
my ( $self, $target, $target_setting ) = @_;
return $target_setting unless $target && $target_setting && $target_setting eq 'uninstalled';
$self->{_rpm} ||= Cpanel::RPM->new();
my $rpm = $self->{_rpm};
my $server = $target . '-server';
my $result = $rpm->qa($server);
if ( $result && $result->{$server} && $result->{$server} =~ m/\.cp\d+$/ ) {
return 'installed';
}
return $target_setting;
}
sub is_mysql_supported_by_cpanel {
my $self = shift or die;
my $rpmv = $self->{rpmv} || return 0;
foreach my $version (@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 MySQL version: ' . $version . '.' . ' Upgrade your MySQL server to a version greater or equal to ' . $MINIMUM_RECOMMENDED_MYSQL_RELEASE;
return;
}
}
my @releases_to_allow = (
@SUPPORTED_MYSQL_RELEASES,
@OLD_MYSQL_RELEASES_FOR_11_44,
);
foreach my $version (@releases_to_allow) {
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 is_local_nameserver_type_valid {
my $self = shift;
my $nameserver_type = $self->cpconfig()->{'local_nameserver_type'} || '';
return 1 if ( $nameserver_type eq '' && $ENV{'CPANEL_BASE_INSTALL'} );
return 1 if !$nameserver_type;
return 1 if ( $nameserver_type =~ /^(?: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;
}
return unless $needs_save;
$self->{'logger'}->warning("Saving cpanel.config with removed white space");
$self->{'guard'}->save();
}
sub is_legacy_cpconfig_invalid {
my $self = shift;
return $self->{'invalid'};
}
1;
} # --- END Cpanel/Update/Blocker/CpanelConfig.pm
{ # --- BEGIN Cpanel/FastInstall.pm
package Cpanel::FastInstall;
use strict;
sub _disable_fast_install_file {
return q{/etc/cpanel/disable_fast_install};
}
sub is_enabled {
return $ENV{'CPANEL_BASE_INSTALL'} && !-e _disable_fast_install_file() ? 1 : 0;
}
1;
} # --- END Cpanel/FastInstall.pm
{ # --- BEGIN Cpanel/Update/Blocker/RPM.pm
package Cpanel::Update::Blocker::RPM;
use Cwd ();
# use Cpanel::Alarm ();
# use Cpanel::Config::Sources ();
# use Cpanel::FastInstall ();
# use Cpanel::FindBin ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::SafeRun::Dynamic ();
# use Cpanel::Update::Logger ();
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 $rpm_dir = $args->{'rpm_dir'} || '/var/lib/rpm';
return {
'logger' => $logger,
'rpm_dir' => $rpm_dir,
};
}
sub rpm_bin { return '/bin/rpm' }
sub rpm_dir {
my $self = shift;
return $self->{'rpm_dir'};
}
sub logger {
my $self = shift;
return $self->{'logger'};
}
sub test_rpm {
my ($self) = @_;
my $ret;
{
my $alarm = Cpanel::Alarm->new( 10 * 60, sub { die("alarm") } );
$self->logger()->info("Checking that the RPM DB is OK...\n");
eval {
$ret = $self->rpm_execute(qw/-q glibc/);
chomp $ret if $ret;
};
}
if ($@) {
return ( 0, "TIMEOUT: RPM DB is not responding after 10 minutes." );
}
elsif ($?) {
return ( 0, "FAIL: RPM DB error: $ret" );
}
elsif ($ret) {
return ( 1, "OK: RPM DB is responding to queries" );
}
return ( 0, "FAIL: RPM DB missing glibc" );
}
sub check_package_system {
my ($self) = @_;
my ( $status, $statusmsg ) = $self->test_rpm();
$self->logger()->info( $statusmsg . "\n" );
return 0 if ( !$status );
$self->logger()->info("Testing if rpm_is_working RPM is installed\n");
my $alarm = Cpanel::Alarm->new( 10 * 60, sub { die("alarm") } );
my $result = eval { $self->rpm_execute(qw/-q rpm_is_working/); };
undef $alarm;
if ($@) {
$self->logger()->info("Could not query the rpm database (timeout)\n");
return 0;
}
if ( $result && $result =~ m/^\Qrpm_is_working-1.0-0.noarch\E/ ) {
$self->logger()->info("Removing RPM rpm_is_working\n");
my $alarm = Cpanel::Alarm->new( 10 * 60, sub { die("alarm") } );
my $result = eval { $self->rpm_execute(qw/-e rpm_is_working/); 1 };
}
my $local_file = '/usr/local/cpanel/src/rpm_is_working-1.0-0.noarch.rpm';
if ( -e $local_file && !-z $local_file && !Cpanel::FastInstall::is_enabled() ) {
$self->logger()->info("Testing if it's possible to install a simple RPM\n");
my $alarm = Cpanel::Alarm->new( 10 * 60, sub { die("alarm") } );
eval { $self->rpm_execute( '-Uvh', '--force', $local_file ) };
undef $alarm;
if ($@) {
$self->logger()->info("TIMEOUT: RPM DB is unresponsive after 10 minutes installing a simple RPM -- $? -- $@ -- \n");
}
elsif ( !-e '/usr/local/cpanel/src/rpm_is_working' ) {
$self->logger()->info("The RPM did not appear to install.");
}
else {
$alarm = Cpanel::Alarm->new( 10 * 60, sub { die("alarm") } );
eval { $self->rpm_execute(qw/-e rpm_is_working/) };
return 1;
}
return 0;
}
return 1;
}
sub output_to_logger {
my ($self) = @_;
my $logger = $self->logger();
return sub {
my ( $msg, $stop ) = @_;
$logger->info($msg);
};
}
sub rpm_execute {
my ( $self, @args ) = @_;
my $logger = $self->logger();
my $rpm = $self->rpm_bin();
my $results = '';
Cpanel::SafeRun::Dynamic::saferun_callback(
'prog' => [ $rpm, @args ],
'callback' => sub {
my ( $msg, $stop ) = @_;
$logger->info($msg);
$results .= $msg;
}
);
return $results;
}
1;
} # --- END Cpanel/Update/Blocker/RPM.pm
{ # --- BEGIN Whostmgr/Transfers/Session/Config.pm
package Whostmgr::Transfers::Session::Config;
use strict;
use warnings;
# use Cpanel::ConfigFiles ();
our $VERSION = '2.3';
our $SESSION_DIR = '/var/cpanel/transfer_sessions';
our $MAX_SESSION_AGE = ( 86400 * 30 ); # 30 days in seconds
our $MAX_IDLE_TIME = ( 3600 * 2 ); # 2 hours in seconds
our $DBNAME = 'whmxfer';
our $NUMPHASES = 2;
our $UNRESTRICTED = 1;
our $RESTRICTED = 0;
our $MODULES_DIR = '/Whostmgr/Transfers/Systems';
our $CUSTOM_PERL_MODULES_DIR = $Cpanel::ConfigFiles::CUSTOM_PERL_MODULES_DIR;
our $CPANEL_PERL_MODULES_DIR = $Cpanel::ConfigFiles::CPANEL_ROOT;
our %ITEMTYPE_NAMES = (
1000 => 'FeatureListRemoteRoot',
1045 => 'BackupsRemoteRoot',
1050 => 'EximRemoteRoot',
1052 => 'ThemesRemoteRoot',
1054 => 'ApacheRemoteRoot',
1056 => 'MySQLRemoteRoot',
1058 => 'WHMConfRemoteRoot',
2000 => 'PackageRemoteRoot',
3000 => 'AccountRemoteRoot',
4000 => 'AccountRemoteUser',
5000 => 'AccountLocal',
6000 => 'LegacyAccountBackup',
7000 => 'AccountUpload',
8000 => 'RearrangeAccount',
);
1;
} # --- END Whostmgr/Transfers/Session/Config.pm
{ # --- BEGIN Cpanel/Update/Blocker.pm
package Cpanel::Update::Blocker;
use strict;
use Try::Tiny;
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::LoadCpConf ();
# use Cpanel::DB::Map::Collection ();
# use Cpanel::FileUtils::Open ();
# use Cpanel::GenSysInfo ();
# use Cpanel::iContact ();
# use Cpanel::Hostname ();
# use Cpanel::MysqlUtils ();
# use Cpanel::RPM ();
# use Cpanel::SafeRun::Simple ();
# use Cpanel::TempFile ();
# use Cpanel::Update::Blocker::CpanelConfig (); # cpanel.config integrity checks.
# use Cpanel::Update::Blocker::RPM (); # RPM Database integrity checks.
# use Cpanel::Update::Config ();
# use Cpanel::LoadFile ();
# use Cpanel::LoadModule ();
# use Cpanel::Update::Logger ();
# use Cpanel::Version::Compare ();
# use Whostmgr::Transfers::Session::Config ();
# use Cpanel::NAT ();
# use Cpanel::TimeHiRes ();
# use Cpanel::DIp::MainIP ();
# use Cpanel::SafeDir::MK ();
our $update_blocks_fname = '/var/cpanel/update_blocks.config';
sub new {
my $class = shift or die;
my $self = shift or die;
ref($self) eq 'HASH' or die("Options hash ref not passed to new");
$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->{'update_blocks_fname'} = $update_blocks_fname;
$self->{'upgrade_deferred_file'} = '/var/cpanel/upgrade_deferred';
$self = bless $self, $class;
$self->{'messages'} = [];
return $self;
}
sub cpanel_config {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
$self->{'cpanel_config'} ||= Cpanel::Config::LoadCpConf::loadcpconf();
return $self->{'cpanel_config'};
}
sub logger { shift->{'logger'} }
sub block_version_change {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $message = shift or return;
my $severity = shift || 'fatal';
my $notify = shift;
$notify = 1 unless defined $notify;
if ( $severity !~ m/quiet/i ) {
push( @{ $self->{'messages'} }, { 'message' => $message, 'severity' => $severity, 'notify' => $notify } );
}
$message =~ s/<a.*?>//ig;
$message =~ s{</a>}{}ig;
$self->logger->error("Blocker found: $message");
$self->{'is_fatal_block'}++;
}
sub is_fatal_block {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $new_value = shift;
if ( defined $new_value ) {
$self->{'is_fatal_block'} = $new_value;
}
return $self->{'is_fatal_block'};
}
sub is_downgrade_blocked {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $target_major = Cpanel::Version::Compare::get_major_release( $self->{'target_version'} );
my $current_major = Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} );
return if ( $target_major >= $current_major );
$self->block_version_change('Downgrades to a previous major release are not permitted.');
$self->generate_blocker_file(1);
return $self->is_fatal_block();
}
sub perform_global_checks {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
$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();
$self->is_rpm_database_broken();
$self->is_cpanel_config_broken();
$self->is_yum_locked();
return;
}
sub is_update_blocked {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
$self->perform_global_checks();
$self->generate_blocker_file(1);
return $self->is_fatal_block();
}
sub is_upgrade_blocked {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $current_major = Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} );
my $target_major = Cpanel::Version::Compare::get_major_release( $self->{'target_version'} );
return if $current_major >= $target_major;
$self->perform_global_checks();
$self->is_legacy_system();
my $auto_resolved_blocker = 0;
if ( check_upgrade_blockers_for( 11.32, $current_major ) ) {
$self->is_1130_exim();
}
if ( check_upgrade_blockers_for( 11.36, $current_major ) ) {
$self->are_rpm_updates_disabled();
$self->is_1134_exim();
$self->is_1134_munin();
}
if ( check_upgrade_blockers_for( 11.38, $current_major ) ) {
$self->is_interchange_disabled();
}
if ( check_upgrade_blockers_for( 11.44, $current_major ) ) {
$self->has_whmxfer_db_in_map_1144();
}
if ( check_upgrade_blockers_for( 11.46, $current_major ) ) {
$self->check_php53();
$self->is_using_frontpage();
}
if ( check_upgrade_blockers_for( 11.54, $current_major ) ) {
$auto_resolved_blocker += $self->is_using_courier();
$auto_resolved_blocker += $self->is_openssl_vulnerable();
}
if ( !$auto_resolved_blocker && $self->delay_upgrade() ) {
$self->generate_blocker_file(0);
return $self->is_fatal_block() + 1;
}
$self->generate_blocker_file(1);
return $self->is_fatal_block();
}
sub check_upgrade_blockers_for {
my ( $blocker, $current_major ) = @_;
return 0 unless defined $blocker && defined $current_major;
return 1 if $blocker - 0.02 eq $current_major;
return 1 if $blocker - 0.03 eq $current_major;
return 0;
}
sub _get_future_upgrade_date {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $days = shift;
die "Need random day padding" unless defined($days);
my $now = shift || time();
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime($now);
$now = $now - $sec - $min * 60 - $hour * 60 * 60;
my $pad = 86400; # one day in seconds
my $proposed_day = $wday + $days;
my $weekend_factor = 0;
if ( $proposed_day == 0 || ( $proposed_day >= 5 && $proposed_day <= 8 ) ) {
$weekend_factor = ( $wday >= 1 && $wday < 5 ) ? 3 : ( 8 - ( $proposed_day ? $proposed_day : 7 ) );
}
$now += $pad * ( $days + $weekend_factor );
return $now;
}
sub _alter_mtime {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $touchfile = shift or die;
my $future = shift or die;
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 delay_upgrade {
my $self = shift or die;
ref $self eq __PACKAGE__ 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)/i );
my $current_major = Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} );
my $target_major = Cpanel::Version::Compare::get_major_release( $self->{'target_version'} );
return 9 unless ( $self->{'target_version'} =~ m/^\d+\.\d+\.0\./ );
return 4 if ( $target_major - $current_major > 0.03 ); # The Next target is more than 1 LTS away. We don't check in that case.
return 5 unless ( $self->{'target_version'} eq ( $self->{'remote_tiers'}->{$current_tier} || 0 ) );
my $touchfile = $self->{'upgrade_deferred_file'};
my $mtime;
$mtime = ( stat($touchfile) )[9] if ( -e $touchfile );
if ( $mtime && $mtime < time ) {
return 6;
}
if ( !$mtime ) {
my $rand_days = shift;
$rand_days = int( rand(5) ) if ( !defined $rand_days );
return 7 if ( !$rand_days );
$mtime = $self->_get_future_upgrade_date($rand_days);
$self->_alter_mtime( $self->{'upgrade_deferred_file'}, $mtime );
}
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime($mtime);
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $future_upgrade_date = sprintf( "%s %s %s, %s", (qw{ Sunday Monday Tuesday Wednesday Thursday Friday Saturday})[$wday], $abbr[$mon], $mday, $year + 1900 );
$self->block_version_change( "Upgrade to the next LTS is blocked until $future_upgrade_date in order to distribute upgrades over a five day period. If you wish to upgrade now, you can do so now with the force option.", 'info', 0 );
return 8;
}
sub generate_blocker_file {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $notify = shift;
return if ( !$self->{'messages'} or ref( $self->{'messages'} ) ne '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 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,
);
}
sub send_icontact_openssl_notification {
my ( $self, $subject, $message ) = @_;
return Cpanel::iContact::icontact(
'application' => 'upcp',
'subject' => $subject,
'message' => $message,
);
}
sub is_legacy_system {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
return if $ENV{'CPANEL_BASE_INSTALL'};
my $sysinfo = eval { Cpanel::GenSysInfo::run() };
if ($@) {
my $error = $@;
chomp $error;
$self->block_version_change($error);
return;
}
my $legacy_message = '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. Please see our <a href="https://go.cpanel.net/eol" target="_blank">OS End of Life policy</a> for more information.';
unless ( $sysinfo->{'rpm_dist'} =~ /^(centos|cloudlinux|rhel|amazon)$/i ) {
$self->block_version_change($legacy_message);
return;
}
unless ( $sysinfo->{'rpm_dist_ver'} > 4 ) {
$self->block_version_change($legacy_message);
return;
}
return;
}
sub is_license_expired {
my $self = shift or die;
ref $self eq __PACKAGE__ 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;
}
if ( -e '/var/cpanel/dnsonly' ) {
$self->logger->info('DNSONLY detected.');
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;
if ( $self->{'upconf_ref'}->{'UPDATE_EXP_TIME'} ) {
$self->logger->warning("UPDATE_EXP_TIME=$self->{upconf_ref}->{'UPDATE_EXP_TIME'} in /etc/cpupdate.conf is blocking a proper license check.\n");
$updates_expire_time = $self->{'upconf_ref'}->{'UPDATE_EXP_TIME'};
}
else {
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 - ( 86400 * 7 ) ) ) {
$self->logger->warning("");
$self->logger->warning("");
$self->logger->warning("");
$self->logger->warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
$self->logger->warning("");
$self->logger->warning("cPanel software update unable to continue. This server's license is");
$self->logger->warning("no longer eligible for software updates. In order to update this");
$self->logger->warning("server's cPanel software, you will need to purchase an update");
$self->logger->warning("extension for this server. Please contact customer service for more");
$self->logger->warning("information on software updates and update extensions.");
$self->logger->warning("");
$self->logger->warning("https://tickets.cpanel.net/submit/?reqtype=cs");
$self->logger->warning("");
$self->logger->warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
$self->logger->warning("");
$self->logger->warning("");
$self->logger->warning("");
$self->logger->warning("Server's license is no longer eligible for updates");
$self->logger->warning("License check found regular cPanel & WHM license with expired updates");
$self->block_version_change("Server's license is no longer eligible for updates.");
}
$self->logger->info("License file check complete\n");
return;
}
sub is_1130_exim {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $exim_bin =
-x '/usr/sbin/exim' ? '/usr/sbin/exim'
: -x '/usr/local/sbin/exim' ? '/usr/local/sbin/exim'
: -x '/usr/sbin/sendmail' ? '/usr/sbin/sendmail'
: -x '/usr/local/sbin/sendmail' ? '/usr/local/sbin/sendmail'
: undef;
my $exim_version = undef;
if ($exim_bin) {
my $eximFversion = `$exim_bin -bV`;
$eximFversion =~ m/version\s+([\d\.]+)/;
$exim_version = $1;
}
if ( !$exim_version || $exim_version < 4.70 ) {
unless ( Cpanel::Update::Config::is_permitted( 'EXIMUP', $self->{'upconf_ref'} ) ) {
$self->block_version_change('Upgrades past 11.30 are blocked because your exim is older than 4.70 and eximup is disabled.');
}
}
return;
}
sub is_1134_munin {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
Cpanel::SafeRun::Simple::saferun( 'grep', 'munin', '/var/cpanel/addonmodules' );
return unless $? == 0;
Cpanel::SafeRun::Simple::saferun( 'rpm', '-q', '--whatprovides', 'munin' );
return unless $? == 0;
$self->block_version_change("Upgrade is blocked because munin is installed as an RPM on your system, and the cPanel plugin is installed at the same time. To proceed you can remove either the 'munin' and 'munin-node' RPMs or the cPanel plugin, then run the upgrade one more time.");
return 1;
}
sub is_1134_exim {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
return if Cpanel::Update::Config::is_permitted( 'EXIMUP', $self->{'upconf_ref'} );
my $touchfile = '/var/cpanel/exim.unmanaged';
return 2 if -e $touchfile;
$self->block_version_change("Upgrade is blocked because EXIMUP is set to 'never' in your configuration. To proceed, you can touch file '$touchfile' and run the upgrade one more time. Please refer to our documentation at https://go.cpanel.net/1136UpgradeExim for more information.");
return 1;
}
sub has_whmxfer_db_in_map_1144 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $collection = Cpanel::DB::Map::Collection->new( { 'db' => 'MYSQL' } );
my $map = $collection->find_by_db($Whostmgr::Transfers::Session::Config::DBNAME);
if ($map) {
my $owner_name = $map->get_cpuser();
$self->block_version_change("Upgrade is blocked because the user '$owner_name' owns the database '$Whostmgr::Transfers::Session::Config::DBNAME'. To proceed, you can remove the database '$Whostmgr::Transfers::Session::Config::DBNAME' and then run the upgrade one more time. Please refer to our documentation at https://go.cpanel.net/blockers for more information.");
return 1;
}
return;
}
sub _df { my @output = `/bin/df -PB1 $_[0] 2>&1` }
sub is_disk_full_ulc {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $path =
-e '/usr/local/cpanel' ? '/usr/local/cpanel'
: -e '/usr/local' ? '/usr/local'
: '/usr';
my $space = $self->_find_df_for_path($path);
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;
}
return 1;
}
sub is_disk_full_staging {
my $self = shift or die;
ref $self eq __PACKAGE__ 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 $space = $self->_find_df_for_path($path);
return if not defined $space;
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 = shift;
my @home_mounts;
eval {
Cpanel::LoadModule::load_perl_module('Cpanel::Filesys');
@home_mounts = Cpanel::Filesys::get_all_homedirs();
};
return if ( !scalar @home_mounts || $@ );
foreach my $largest_mountpoint (@home_mounts) {
if ( Cpanel::Update::Config::validate_staging_dir($largest_mountpoint) ) {
my $space = $self->_find_df_for_path( $largest_mountpoint, 'dont_block' );
return $largest_mountpoint if $space > 3221225472;
}
}
return;
}
sub _find_df_for_path {
my ( $self, $path, $dont_block ) = @_;
my @disk_space = _df($path);
chomp $_ foreach @disk_space;
if ($?) {
$self->block_version_change( "Unable to determine free disk space from $path. Could not get output from /bin/df -PB1 $path: ($?)<br />" . join( "<br />", @disk_space ) ) if !$dont_block;
return;
}
if ( !$disk_space[1] or $disk_space[1] !~ m/^\s*\S+\s+\S+\s+\S+\s+([0-9]+)\s/ ) {
$self->block_version_change( "Unable to determine free disk space from $path. Could not get output from /bin/df -PB1 $path:<br />" . join( "<br />", @disk_space ) ) if !$dont_block;
return;
}
return $1;
}
our @system_directories = qw{ /etc /var /var/lib/rpm /usr/local /usr/bin /tmp /var/tmp };
our @target_directories = qw{ /var/cpanel /usr/local/cpanel /usr/local/bin };
sub is_directory_ro {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
foreach my $dir (@system_directories) {
unless ( test_path_is_rw($dir) ) {
$self->block_version_change("Can not upgrade because $dir is not writable");
return;
}
}
foreach my $dir (@target_directories) {
next unless ( -d $dir );
unless ( test_path_is_rw($dir) ) {
$self->block_version_change("Can not upgrade because $dir is not writable");
return;
}
}
return 1;
}
our $rw_testfile = '/CPANEL_TEST_FS_IS_RW';
sub create_temporary_directory {
my $path = shift or return;
my $temp = Cpanel::TempFile->new;
$path = $temp->dir( { path => $path } ) . $rw_testfile;
return ( $temp, $path );
}
sub test_path_is_rw {
my $dir = shift or return;
$dir =~ s/\/$//; # Strip trailing slash.
$dir = "/" if !$dir;
return unless -d $dir;
my ( $temp, $path );
eval {
( $temp, $path ) = create_temporary_directory($dir);
open( my $fh, '>', $path ) or die "failed to open $path: $!";
print $fh 'abc';
close $fh or die "failed to close $path: $!";
};
my $error = $@;
my $file_size = 0;
$file_size = -s $path;
unlink $path;
( $file_size && $file_size == 3 ) or return;
return if ($error);
return 1;
}
sub is_rpm_database_broken {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $rpm_db = Cpanel::Update::Blocker::RPM->new( { 'logger' => $self->{'logger'} } );
my $db_works = $rpm_db->check_package_system();
return 1 if ($db_works);
$self->block_version_change("Your RPM database appears unstable. It is not possible at the moment to install a simple RPM.");
return;
}
sub check_php53 {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $php_target = 'cpanel-php53';
my $target_settings = Cpanel::RPM::Versions::Directory->new()->fetch( { 'section' => 'target_settings', 'key' => $php_target } );
return 2 if $target_settings && $target_settings eq 'unmanaged';
my $php_rpms = $php_target . '*'; # all rpms start with the target name
my $rpm = Cpanel::RPM->new();
my $result = $rpm->qa($php_rpms) || {};
my $has_cpanel_php_rpms = grep { m/\.cp\d+$/ } values %$result;
if ($has_cpanel_php_rpms) {
$self->block_version_change( _check_php53_error_msg() );
return;
}
return 1;
}
sub _check_php53_error_msg {
return 'cPanel & WHM version 11.46 and higher do not support PHP version 5.3. Use the following commands to uninstall the PHP 5.3 RPMs:'
. ' "/scripts/update_local_rpm_versions --del target_settings.cpanel-php53; /scripts/check_cpanel_rpms --fix"'
. ' The rpm.versions system will automatically install the PHP 5.4 RPMs.';
}
sub is_cpanel_config_broken {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $cpconfig = Cpanel::Update::Blocker::CpanelConfig->new( { 'logger' => $self->{'logger'} } );
$cpconfig->cleanse_cpanel_config_entries();
my $mysql_ok = $cpconfig->is_mysql_version_valid();
if ( !$mysql_ok ) {
my $reason = $cpconfig->{'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);
}
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 mydns, nsd, bind or you can leave it blank. You can change the value here: <a href="../scripts/nameserverconfig">Nameserver Selection</a>');
}
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();
}
sub are_rpm_updates_disabled {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $update_conf = Cpanel::Update::Config::load();
if ( $update_conf->{'SYSUP'} && $update_conf->{'SYSUP'} eq 'never' ) {
$self->block_version_change("Can not upgrade because sysup has been disabled in current installation");
return;
}
return 1;
}
sub is_interchange_disabled {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
return 1 if ( -e '/etc/interchangeisevil' || -e '/etc/interchangedisable' );
my $cpanel_config = $self->cpanel_config();
if ( exists $cpanel_config->{'interchangever'} && $cpanel_config->{'interchangever'} ne 'disable' ) {
$self->block_version_change("Cannot upgrade because Interchange is installed.");
return;
}
return 1;
}
our $YUM_WAIT_SLEEP_INTERVAL = 5; # for testing
sub is_yum_locked {
my $self = shift or die;
ref $self eq __PACKAGE__ 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;
}
our $fp_binary = q{/usr/local/frontpage/version5.0/bin/owsadm.exe};
sub is_using_frontpage {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
if ( -x $fp_binary ) {
$self->block_version_change("The server cannot upgrade to cPanel & WHM version 11.46 because Microsoft® FrontPage® is installed. Use WHM's <a href=\"../scripts/fplist?un=1\">Uninstall FrontPage Extensions interface</a> (Home >> FrontPage >> Uninstall FrontPage Extensions) to remove FrontPage.");
}
return;
}
my $courier_autoremove_time_file = '/var/cpanel/courier_autoremoval_time';
sub is_using_courier {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
my $cpanel_config = $self->cpanel_config();
my $auto_resolved = 0;
if ( $cpanel_config->{'mailserver'} eq 'courier' ) {
_set_courier_autoremove_file();
my ( $time_passed, $time_left ) = _check_courier_autoremove_time();
my ( $subject, $days_left, $hrs_left, $failed_to_convert, $script_output );
if ($time_passed) {
$script_output = Cpanel::SafeRun::Simple::saferunallerrors( '/usr/local/cpanel/scripts/setupmailserver', 'dovecot' );
if ( $? != 0 ) {
$failed_to_convert = 1;
$subject = 'Failed to automatically switch mailserver to Dovecot.';
}
else {
$subject = 'Mailserver switched to Dovecot successfully.';
$auto_resolved = 1;
}
}
else {
$days_left = int( $time_left / ( 24 * 60 * 60 ) );
$hrs_left = ( $time_left / ( 60 * 60 ) ) % 24;
$subject = 'The system will automatically switch the mail server from Courier to Dovecot in ' . $days_left . ' day(s) and ' . $hrs_left . ' hour(s) in order to continue receiving updates.';
$self->block_version_change(
"The server cannot upgrade cPanel & WHM. The Courier mailserver is no longer supported. To remove this blocker, switch the mailserver to Dovecot with WHM's <a href=\"../scripts/mailserverconfig\">Mailserver Selection</a> interface. If you take no action, cPanel & WHM will automatically switch the Mailserver to Dovecot in $days_left day(s) and $hrs_left hour(s).");
}
if ( try { Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Update::ServiceDeprecated') } ) {
$self->send_icontact_class_notification(
'class' => 'Update::ServiceDeprecated',
'application' => 'Update::ServiceDeprecated',
'constructor_args' => [
'origin' => 'upcp',
'service_name' => 'Courier',
'days_left' => $days_left,
'hrs_left' => $hrs_left,
'last_version' => '11.52',
'replacement' => 'Dovecot',
'failed_to_convert' => $failed_to_convert || 0,
'script_output' => $script_output || '',
]
);
}
else {
my $message = _fetch_legacy_courier_message( $days_left, $hrs_left, $failed_to_convert, $script_output );
$self->send_icontact_noclass_notification( $subject, $message );
}
}
return $auto_resolved;
}
sub _check_courier_autoremove_time {
my $time_to_check = Cpanel::LoadFile::loadfile($courier_autoremove_time_file);
chomp $time_to_check;
my $curtime = time();
if ( $time_to_check <= $curtime ) {
return ( 1, 0 );
}
return ( 0, $time_to_check - $curtime );
}
sub _set_courier_autoremove_file {
return if -e $courier_autoremove_time_file;
open my $fh, '>', $courier_autoremove_time_file;
print $fh time() + ( 29 * 86400 ); # 29 days from now.
close $fh;
return;
}
sub _fetch_legacy_courier_message {
my ( $days_left, $hrs_left, $failed_to_convert, $script_output ) = @_;
my $message;
if ( defined $days_left || defined $hrs_left ) {
$days_left = ( defined $days_left ? $days_left : 0 );
$hrs_left = ( defined $hrs_left ? $hrs_left : 0 );
$message = <<END_OF_MESSAGE;
The cPanel & WHM update cannot proceed because the following service has been deprecated: Courier
You have $days_left day(s) and $hrs_left hour(s) until we remove Courier and replace it with Dovecot.
To continue using Courier, you must change your Update Preferences in WHM to Long Term Support (LTS). By switching to LTS, you will not receive new features and eventually will stop receiving security updates.
cPanel & WHM version 11.52 will be the last LTS version to support Courier.
For more information about Long Term Support: https://go.cpanel.net/longtermsupport
END_OF_MESSAGE
}
else {
if ($failed_to_convert) {
$message = 'The system failed to automatically remove Courier.';
}
else {
$message = 'The deprecated service, Courier, has been removed and replaced with Dovecot.';
}
$message .= "\n\nReview the log for further details:\n\n$script_output\n\n";
}
return $message;
}
sub _vulnerable_os {
my $rpm_distro = Cpanel::GenSysInfo::get_rpm_distro();
my $rpm_distro_ver = Cpanel::GenSysInfo::get_rpm_distro_version();
return 0 if ( !( $rpm_distro =~ m/^(centos|red|rhel)/i ) );
return 0 if ( $rpm_distro_ver != 6 );
return 1;
}
sub _check_openssl_vulnerable {
my ($self) = @_;
my $error = 0;
return $self->{'IS_OPENSSL_VULNERABLE'} if ( exists $self->{'IS_OPENSSL_VULNERABLE'} );
return 0 if !_vulnerable_os();
my $ret = eval {
local $ENV{'LC_ALL'} = 'C';
my $result = `openssl ciphers -v TLSv1.2`;
my $ret_code = $?;
if ( $ret_code < 0 ) {
$error = 1;
}
elsif ( $ret_code & 127 ) {
$error = 1;
}
else {
$ret_code = $ret_code >> 8;
$error = 1 if $ret_code != 0;
}
if ( !$error ) {
$error = 1 if ( $result =~ m/Error in cipher list/ );
}
};
$error = 1 if !defined $ret;
return $error;
}
our $openssl_vulnerable_autoremove_time_file = '/var/cpanel/openssl_vulnerable_autoremoval_time';
sub _read_file_contents {
my ($fname) = @_;
my $FH;
open $FH, "<", $fname or return;
my $contents = <$FH>;
close $FH;
chomp $contents;
chomp $contents;
return $contents;
}
sub _get_test_values {
my ($self) = @_;
my $file_yum_update_openssl = "/var/cpanel/test_flag_yum_update_openssl";
if ( -e $file_yum_update_openssl ) {
$self->{'YUM_UPDATE_OPENSSL'} = _read_file_contents($file_yum_update_openssl);
}
my $file_openssl_vulnerable = "/var/cpanel/test_flag_openssl_is_vulnerable";
if ( -e $file_openssl_vulnerable ) {
$self->{'IS_OPENSSL_VULNERABLE'} = _read_file_contents($file_openssl_vulnerable);
}
$self->{'USE_LEGACY'} = 0;
my $file_use_legacy = "/var/cpanel/test_flag_use_legacy";
if ( -e $file_use_legacy ) {
$self->{'USE_LEGACY'} = _read_file_contents($file_use_legacy);
}
return;
}
sub is_openssl_vulnerable {
my $self = shift or die;
ref $self eq __PACKAGE__ or die('This is a method call.');
$self->_get_test_values();
my $auto_resolved = 0;
my $vulnerable = $self->_check_openssl_vulnerable();
if ($vulnerable) {
_set_openssl_autoremove_file();
my ( $time_passed, $time_left ) = $self->_check_openssl_autoremove_time();
my ( $subject, $days_left, $hrs_left, $failed_to_upgrade, $script_output );
if ($time_passed) {
if ( exists $self->{'YUM_UPDATE_OPENSSL'} && $self->{'YUM_UPDATE_OPENSSL'} eq "1" ) {
$? = 0;
$self->{'IS_OPENSSL_VULNERABLE'} = 1;
$script_output = "yum update succeeded\nbut we are still vulnerable\n";
}
elsif ( exists $self->{'YUM_UPDATE_OPENSSL'} && $self->{'YUM_UPDATE_OPENSSL'} eq "2" ) {
$? = 1;
$self->{'IS_OPENSSL_VULNERABLE'} = 1;
$script_output = "yum update failed\nand we are still vulnerable\n";
}
elsif ( exists $self->{'YUM_UPDATE_OPENSSL'} && $self->{'YUM_UPDATE_OPENSSL'} eq "0" ) {
$? = 0;
$self->{'IS_OPENSSL_VULNERABLE'} = 0;
$script_output = "yum update succeeded\nand we are no longer vulnerable\n";
}
else {
$script_output = Cpanel::SafeRun::Simple::saferunallerrors('/usr/local/cpanel/scripts/yum_update_openssl');
}
if ( $? != 0 ) {
$failed_to_upgrade = 1;
$subject = 'Failed to automatically upgrade OpenSSL.';
}
else {
$vulnerable = $self->_check_openssl_vulnerable();
if ($vulnerable) {
$failed_to_upgrade = 1;
$subject = 'Failed to automatically upgrade OpenSSL.';
}
else {
$subject = 'OpenSSL upgraded successfully.';
$auto_resolved = 1;
}
}
}
else {
$days_left = int( $time_left / ( 24 * 60 * 60 ) );
$hrs_left = ( $time_left / ( 60 * 60 ) ) % 24;
$subject = _fetch_openssl_subject( $days_left, $hrs_left, $failed_to_upgrade, $script_output );
$self->block_version_change("The server cannot upgrade cPanel & WHM. Your system is running an old version of OpenSSL that does not support TLS1.2 which is required to help maintain PCI compliance.");
}
$failed_to_upgrade = 0 if !defined $failed_to_upgrade;
if ( !$self->{'USE_LEGACY'} && try { Cpanel::LoadModule::load_perl_module('Cpanel::iContact::Class::Update::UpgradeRequired') } ) {
$self->send_icontact_class_notification(
'class' => 'Update::UpgradeRequired',
'application' => 'Update::UpgradeRequired',
'constructor_args' => [
'origin' => 'upcp',
'service_name' => 'OpenSSL',
'days_left' => $days_left,
'hrs_left' => $hrs_left,
'last_version' => '11.52',
'failed_to_upgrade' => $failed_to_upgrade || 0,
'script_output' => $script_output || '',
]
);
}
else {
my $message = _fetch_openssl_message( $days_left, $hrs_left, $failed_to_upgrade, $script_output );
$self->send_icontact_openssl_notification( $subject, $message );
}
}
return $auto_resolved;
}
sub _check_openssl_autoremove_time {
my $time_to_check = Cpanel::LoadFile::loadfile($openssl_vulnerable_autoremove_time_file);
chomp $time_to_check;
my $curtime = time();
if ( $time_to_check <= $curtime ) {
return ( 1, 0 );
}
return ( 0, $time_to_check - $curtime );
}
sub _set_openssl_autoremove_file {
return if -e $openssl_vulnerable_autoremove_time_file;
open my $fh, '>', $openssl_vulnerable_autoremove_time_file;
print $fh time() + ( 29 * 86400 ); # 29 days from now.
close $fh;
return;
}
sub _fetch_openssl_subject {
my ( $days_left, $hrs_left, $failed_to_upgrade, $script_output ) = @_;
my $subject;
if ( defined $days_left && defined $hrs_left ) {
$subject = "Notice: The system will automatically upgrade the OpenSSL in $days_left and $hrs_left in order to continue receiving updates.";
}
else {
if ($failed_to_upgrade) {
$subject = "Failed to automatically upgrade the OpenSSL service on the server.";
}
else {
$subject = 'The system upgraded the service: OpenSSL.';
}
}
return $subject;
}
sub _fetch_openssl_message {
my ( $days_left, $hrs_left, $failed_to_upgrade, $script_output ) = @_;
my $message;
if ( defined $days_left || defined $hrs_left ) {
$days_left = ( defined $days_left ? $days_left : 0 );
$hrs_left = ( defined $hrs_left ? $hrs_left : 0 );
my $day_units = "day";
my $hour_units = "hour";
$day_units = "days" if $days_left > 1.0;
$hour_units = "hours" if $hrs_left > 1.0;
$message = <<END_OF_MESSAGE;
The cPanel & WHM update cannot proceed because the following service needs to be upgraded: OpenSSL
You have $days_left $day_units and $hrs_left $hour_units until we attempt to upgrade OpenSSL.
To continue using this version of OpenSSL, you must change your Update Preferences in WHM to Long Term Support (LTS).
By switching to LTS, you will not receive new features and eventually will stop receiving security updates.
cPanel & WHM version 11.52 will be the last LTS version to support this outdated version of OpenSSL.'
For more information about Long Term Support, read the following: https://go.cpanel.net/longtermsupport.
END_OF_MESSAGE
}
else {
if ($failed_to_upgrade) {
$message = 'Failed to upgrade the service, OpenSSL, automatically.';
}
else {
$message = 'The outdated service, OpenSSL, has been upgraded.';
}
$message .= "\n\nReview the log for further details:\n\n$script_output\n\n";
}
return $message;
}
1;
} # --- END Cpanel/Update/Blocker.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 strict;
use Try::Tiny;
# use Cpanel::LoadModule ();
# use Cpanel::CloudLinux ();
# use Cpanel::Config::FlushConfig ();
# use Cpanel::Config::LoadConfig ();
# use Cpanel::Config::Sources ();
# use Cpanel::Crypt::GPG::Settings ();
# use Cpanel::Crypt::GPG::VendorKeys ();
# use Cpanel::FileUtils::Copy ();
# use Cpanel::FileUtils::TouchFile ();
# use Cpanel::FindBin ();
# use Cpanel::Exception ();
# use Cpanel::GenSysInfo ();
# use Cpanel::Sys::Uname ();
# use Cpanel::RPM::Versions::File ();
# use Cpanel::SafeDir ();
# use Cpanel::SafeDir::MK ();
# use Cpanel::SafeFile ();
# use Cpanel::Sync::v2 ();
# use Cpanel::Sync::v2_shared_list ();
# use Cpanel::Sysup ();
# use Cpanel::TempFile ();
# use Cpanel::Themes::List ();
# use Cpanel::Update ();
# use Cpanel::Update::Blocker ();
# use Cpanel::Update::Config ();
# use Cpanel::Update::Logger ();
# 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::FastInstall ();
# use Cpanel::ConfigFiles::RpmVersions ();
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'} ||= -e '/var/cpanel/dnsonly' ? 1 : 0;
$self->{'update_is_available_exit_code'} = 42;
$self->{'cpanel_config_file'} ||= '/var/cpanel/cpanel.config';
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' ) } );
$self->{'starting_version'} ||= $self->get_local_version();
$self->{'shared_list'} = Cpanel::Sync::v2_shared_list->new();
$self->_advertise_startup();
return $self;
}
sub _determine_staging_dir {
my $self = shift;
my $staging_dir = $self->upconf->{'STAGING_DIR'};
if ( $staging_dir !~ m{^/usr/local/cpanel/?$} ) {
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;
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) = @_;
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 { shift->{'logger'} }
sub dry_run { return shift->{'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 remote_tiers {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->{'remote_tiers'} ||= Cpanel::Update::get_remote_tiers_info( $self->cpsrc, $self->{'logger'} );
return $self->{'remote_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,
'dry_run' => 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'},
}
);
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->{'log_file_path'} ? ( '--log=' . $self->{'log_file_path'} ) : (),
);
return @argv;
}
sub run {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->validate_staging_dir();
$self->validate_config();
Cpanel::Crypt::GPG::VendorKeys::download_public_keys( 'logger' => $self->{'logger'} );
$self->set_tier_or_sync_version();
if ( $self->{'target_version'} && $self->{'target_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." } );
}
$self->current_lts_first();
$self->next_lts_before_target();
$self->can_update();
$self->logger->info("Switching to version '$self->{target_version}' of updatenow to perform sync.");
$self->become_a_new_updatenow();
my $sysup = Cpanel::Sysup->new( { 'logger' => $self->logger() } );
unless ( $sysup->run() ) {
$self->logger->fatal("Cannot proceed. Needed system RPMs were not installed.");
die( { 'exit' => 18, 'remove_blocker_file' => 0, 'message' => "Cannot proceed. Needed system RPMs were not installed." } );
}
$self->stage_files();
$self->test_rpm_transaction();
$self->install_files();
$self->log_update_completed();
unlink '/var/cpanel/upgrade_deferred' if ( -e '/var/cpanel/upgrade_deferred' && !$self->{'update_not_upgrade'} );
die( { 'exit' => 0, 'remove_blocker_file' => 1 } );
}
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 RPMS 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 RPMs 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 RPMs will install: $error_as_string see https://go.cpanel.net/rpmcheckfailed for more information" } );
}
}
sub get_lts_version {
my ( $self, $tiers ) = @_;
return unless $tiers;
return $self->remote_tiers->{$tiers} if $self->remote_tiers->{$tiers};
my $current_version = current_updatenow_version();
if ( $current_version && $current_version =~ m{^([0-9]+)\.([0-9]+)} ) {
my ( $main, $major ) = ( $1, $2 );
if ( $major % 2 == 1 ) {
if ( $tiers =~ m{^[0-9]+\.[0-9]+$} ) {
return $tiers if $main . "." . ( $major + 1 ) eq $tiers;
}
}
}
return;
}
sub current_lts_first {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my ( $current_lts_tier, $target_lts_tier ) = $self->get_major_versions_in_upgrade();
if ( $current_lts_tier < 11.30 ) {
if ( $target_lts_tier > 11.30 ) {
$self->set_target_from_tier('11.30');
}
return 1;
}
return if ( !$self->get_upgrade_direction() );
my $current_lts_version = $self->get_lts_version($current_lts_tier);
if ( !$current_lts_version ) {
$self->logger->fatal("No LTS version exists for tier $current_lts_tier");
die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "No LTS version exists for tier $current_lts_tier" } );
}
return if ( Cpanel::Version::Compare::compare( $self->{'starting_version'}, '>=', $current_lts_version ) );
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" } );
}
$self->set_target_from_tier($current_lts_tier);
if ( $self->{'target_version'} ne $self->current_updatenow_version() ) { # Only print this once.
$self->logger->info("Need to upgrade to the LTS version before switching to another major version");
}
return 1;
}
sub can_update {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
return if ( $ENV{'UPDATE_IS_ALLOWED'} && $ENV{'UPDATE_IS_ALLOWED'} eq $self->{'target_version'} );
if ( $ENV{'UPDATE_IS_ALLOWED'} ) {
$self->logger->debug("\$ENV{UPDATE_IS_ALLOWED} = $ENV{UPDATE_IS_ALLOWED}");
}
my $major_version_change_type = $self->get_upgrade_direction();
my $current_lts_tier = Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} );
if ( $current_lts_tier < 11.29 ) {
$ENV{'UPDATE_IS_ALLOWED'} = $self->{'target_version'};
return;
}
my $blocker_object = Cpanel::Update::Blocker->new(
{
'logger' => $self->logger,
'starting_version' => $self->{'starting_version'},
'target_version' => $self->{'target_version'},
'upconf_ref' => $self->upconf,
'remote_tiers' => $self->remote_tiers,
'force' => $self->{'force'},
}
);
if ( $major_version_change_type > 0 ) { # Upgrade
if ( $self->current_updatenow_version ne $self->{'target_version'} ) {
$self->logger->info("Switching to $self->{target_version} to determine if we can reach that version without failure.");
$self->become_a_new_updatenow();
}
$blocker_object->is_upgrade_blocked();
}
elsif ( $major_version_change_type < 0 ) {
$blocker_object->is_downgrade_blocked(); # Downgrades are always blocked.
}
else { # Even update checks need to be done by target version.
if ( $self->current_updatenow_version ne $self->{'target_version'} ) {
$self->logger->info("Switching to $self->{target_version} to determine if we can reach that version without failure.");
$self->become_a_new_updatenow();
}
$blocker_object->is_update_blocked();
$self->{'update_not_upgrade'} = 1;
}
if ( $blocker_object->is_fatal_block() ) {
$self->logger->warning("An attempt to up/downgrade to $self->{target_version} was blocked. Please review blockers.");
die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "An attempt to up/downgrade 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" } );
}
$ENV{'UPDATE_IS_ALLOWED'} = $self->{'target_version'};
return;
}
sub next_lts_before_target {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $major_version_change_type = $self->get_upgrade_direction();
return if ( !$major_version_change_type );
my ( $starting_major_release, $target_major_release ) = $self->get_major_versions_in_upgrade();
if ( $major_version_change_type > 0 ) {
my $next_lts = get_neighbor_lts_tier( $self->{'starting_version'}, 2 );
return if ( Cpanel::Version::Compare::get_major_release( $self->{'target_version'} ) eq $next_lts );
$self->set_target_from_tier($next_lts);
$self->{target_version} = $self->{'remote_tiers'}->{$next_lts};
$self->logger->info("Upgrade requested to a version more than 1 LTS away. Will upgrade to next LTS first ($self->{target_version}).");
if ( Cpanel::Version::Compare::compare( $next_lts, '<', '11.46' ) ) {
$self->become_a_new_updatenow( 'use_target_updatenow.static' => 1 );
}
return;
}
my $previous_lts = get_neighbor_lts_tier( $self->{'starting_version'}, -2 );
return if ( Cpanel::Version::Compare::get_major_release( $self->{'target_version'} ) eq $previous_lts );
$self->set_target_from_tier($previous_lts);
$self->logger->info("Downgrade requested to a version more than 1 LTS away. Will downgrade to the previous LTS first ($self->{target_version}).");
return;
}
sub get_major_versions_in_upgrade {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->{'starting_version'} or return; # Must be a new install?
$self->{'target_version'} or die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "The target version was unexpectedly missing." } ); # determine_sync_version should prevent this from ever happening.
return ( Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} ), Cpanel::Version::Compare::get_major_release( $self->{'target_version'} ) );
}
sub get_upgrade_direction {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my ( $starting_major_release, $target_major_release ) = $self->get_major_versions_in_upgrade();
return
!$starting_major_release ? 0
: ( $target_major_release eq $starting_major_release ) ? 0
: ( $target_major_release > $starting_major_release ) ? 1
: -1;
}
sub current_updatenow_version { $Cpanel::Version::Tiny::VERSION_BUILD }
sub become_a_new_updatenow {
my ( $self, %opts ) = @_;
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('/usr/bin/perl', 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( '/usr/bin/perl', $static_script, $self->rebuild_argv ) ) {
$self->logger->fatal("Failed to run downloaded updatenow.static");
die( { 'exit' => 0, 'remove_blocker_file' => 0, 'message' => "Failed to run downloaded updatenow.static" } );
}
die( { 'exit' => 99, 'remove_blocker_file' => 0 } );
}
sub update_script_with_update_conf {
my ( $self, $script, $tmp_cpupdate ) = @_;
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 ) = @_;
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'} );
if ( $self->{'starting_version'} && Cpanel::Version::Compare::get_major_release( $self->{'starting_version'} ) < 11.30 ) {
if ( $self->{'sync'} ) {
$self->logger->fatal('--sync is an invalid option prior to 11.30');
die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => '--sync is an invalid option prior to 11.30' } );
}
$self->{'starting_version'} = '11.28.0.0';
$self->logger->info("Adjusting starting version to 11.28.0.0 to simplify pre 11.30 update");
}
if ( !$ENV{'CPANEL_BASE_INSTALL'} && version_is_invalid( $self->{'starting_version'} ) ) {
$self->logger->warning("Could not determine starting version from /usr/local/cpanel/version. Trying to guess starting version from Cpanel/Version/Tiny.pm");
$self->{'starting_version'} = $self->get_version_from_cv_tiny();
if ( version_is_invalid( $self->{'starting_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" } );
}
}
return;
}
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;
}
$self->set_target_from_tier( $self->upconf->{'CPANEL'} );
if ( $ENV{'CPANEL_BASE_INSTALL'} && !$self->{'starting_version'} ) {
$self->{'starting_version'} = $self->{'target_version'};
$self->logger->info("Initial cPanel installation detected as in progress.");
return;
}
return if ( $self->{'force'} );
my $lock_file = $self->get_upgrade_in_progress_lock_file_name();
return if ( -e $self->{'ulc'} . '/' . $lock_file );
if ( $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;
}
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 'upgrade_in_progress.txt';
}
sub set_target_from_tier {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $target_tier = shift || $self->upconf->{'CPANEL'} || '';
if ( $target_tier =~ m{^\d+} && $target_tier !~ m{^11\.} ) {
$target_tier = '11.' . $target_tier;
}
if ( $ENV{'CPANEL_BASE_INSTALL'} && $self->remote_tiers->{$target_tier} && $self->remote_tiers->{$target_tier} eq 'disabled' && $self->remote_tiers->{'install-fallback'} ) {
$self->remote_tiers->{$target_tier} = $self->remote_tiers->{'install-fallback'};
}
if ( !version_is_invalid($target_tier) ) {
$self->logger->warning("version explicitly hardcoded to CPANEL=$target_tier in /etc/cpupdate.conf");
$self->{'target_version'} = $target_tier;
return $target_tier;
}
if ( !$self->remote_tiers->{$target_tier} ) {
$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!" } );
}
$self->{'target_version'} = $self->remote_tiers->{$target_tier};
$self->logger->info("Target version set to '$self->{target_version}'");
}
sub get_binary_sync_source {
my ( $self, %opts ) = @_;
ref $self eq __PACKAGE__ or die("must be called as a method");
my ( $kernel_type, $machine_arch ) = ( Cpanel::Sys::Uname::get_uname_cached() )[ 0, 4 ];
if ( $kernel_type !~ m/^linux$/i ) {
$self->logger->fatal("cPanel & WHM does not support the $kernel_type kernel");
die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "cPanel & WHM does not support the $kernel_type kernel" } );
}
$kernel_type = lc($kernel_type);
my $sysinfo = Cpanel::GenSysInfo::run() || {};
if ( !$sysinfo->{rpm_dist_ver} || $sysinfo->{rpm_dist_ver} < 5 || $sysinfo->{rpm_dist_ver} > 7 ) {
$self->logger->fatal("Could not figure out RPM distribution version");
die( { 'exit' => 1, 'remove_blocker_file' => 0, 'message' => "Could not figure out RPM distribution version; The RPM database may be corrupt." } );
}
my $distro = 'c' . $sysinfo->{rpm_dist_ver};
if ( $machine_arch =~ m/64/ ) {
$machine_arch = 'x86_64';
}
else {
$machine_arch = 'i386';
}
return $kernel_type . '-' . $distro . '-' . $machine_arch;
}
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_fast_install = Cpanel::FastInstall::is_enabled();
my %stage_opts_tree;
foreach my $source ( 'cpanel', Cpanel::Themes::List::get_list() ) {
$stage_opts_tree{$source} = { no_download => $is_fast_install };
}
if ($is_fast_install) {
$self->logger->info('Staging first installation tarballs');
my $tarbin = Cpanel::FindBin::findbin('tar') || die( { 'exit' => 7, 'remove_blocker_file' => 1, 'message' => "Cannot find tar binary" } );
my @tarballs;
if ( !$self->cpanel()->already_done() || !-d '/var/cpanel/locale' ) {
if ( !$self->cpanel()->already_done() ) {
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');
}
if ( !-d '/var/cpanel/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('lcoale tarball will be staged and installed');
}
else {
$self->logger->debug('locale 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');
}
my $needs_at_least_one_theme = grep { !$self->get_theme_synctree($_)->already_done() } Cpanel::Themes::List::get_list();
$self->logger->debug("detected $needs_at_least_one_theme theme tarballs that will be staged and installed");
if ( !$self->{'dnsonly'} && $needs_at_least_one_theme ) {
$self->_call_stage( 'sync_target' => 'install_themes', 'failure_exit_code' => 9 );
$self->install_themes->commit();
foreach my $theme ( Cpanel::Themes::List::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");
}
my $distro = eval { return Cpanel::GenSysInfo::run()->{'rpm_dist'}; } || '';
if ( !$self->{'dnsonly'}
&& !has_ea_custom_profile()
&& !-x '/usr/local/apache/bin/httpd'
&& !Cpanel::CloudLinux::installed()
&& $distro ne 'rhel' ) {
my $success = eval {
$self->_call_stage( 'sync_target' => 'easyapache', 'failure_exit_code' => 11 );
$self->easyapache->commit();
1;
};
if ($success) {
push @tarballs,
{
file => qq{apache.tar.xz},
absolute => 1,
syncto => '/',
from => _install_ea_root(),
};
$self->logger->debug("EA tarball will be staged and installed");
}
}
else {
$self->logger->debug("EA tarballs is not required");
}
foreach my $tb (@tarballs) {
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', '-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} } );
}
Cpanel::SafeDir::RM::safermdir( $self->{ulc} . '/firstinstall' );
}
if ( !$self->{'dnsonly'} ) {
foreach my $theme ( Cpanel::Themes::List::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->_call_stage( 'sync_target' => 'cpanel', 'failure_exit_code' => 12, 'message' => 'cpanel changes', 'stage_opts' => $stage_opts_tree{'cpanel'} );
if ($is_fast_install) {
$self->_call_stage( 'sync_target' => 'binaries', 'failure_exit_code' => 12, 'message' => 'cpanel binaries changes' );
}
$self->_call_stage( 'message' => 'new RPMS', 'sync_target' => 'rpms', 'failure_exit_code' => 13, 'help_message' => 'see https://go.cpanel.net/rpmcheckfailed for more information' );
$self->logger->info("All files Staged");
return;
}
sub has_ea_custom_profile {
return -e q{/etc/cp_easyapache_profile.yaml} ? 1 : 0;
}
sub _call_stage {
my ( $self, %OPTS ) = @_;
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 $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;
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 ( -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: $!");
}
}
chomp( my $tailwatch_was_running = qx{/usr/local/cpanel/scripts/restartsrv_tailwatchd --status 2> /dev/null} );
if ( $tailwatch_was_running =~ m/\brunning.+?PID\b/ ) {
system('/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose --stop');
$self->logger->info(' Disabling service monitoring.');
system(qw{ touch /var/run/chkservd.suspend });
system('/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose');
$monitoring_disabled_from = $$;
eval q{
END {
if ( $monitoring_disabled_from && $monitoring_disabled_from == $$ && -e '/var/run/chkservd.suspend' ) {
unlink '/var/run/chkservd.suspend';
system(q{/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose 2>&1 | grep -v 'service is disabled'});
}
}
};
}
$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 ( Cpanel::FastInstall::is_enabled() ) {
$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." } );
};
}
if ( $^X ne '/usr/bin/perl' ) {
system(q{/usr/local/cpanel/scripts/restartsrv_tailwatchd --no-verbose 2>&1 | grep -v 'service is disabled'});
}
if ( $self->{'dnsonly'} ) {
$self->logger->info(" Removing x3 themes.");
my $ulc = $self->{'ulc'} or die;
for my $_dir ( Cpanel::Themes::List::get_list() ) {
my $dir_path = "$ulc/base/frontend/$_dir";
if ( -e $dir_path ) {
my $rv = Cpanel::SafeDir::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::List::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 RPMS.");
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" } );
};
$self->logger->info(' Restoring service monitoring.');
unlink '/var/run/chkservd.suspend';
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'},
'options' => $options,
);
my $object = Cpanel::Sync::v2->new( { 'shared_list' => $self->{'shared_list'}, %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 ) = @_;
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 ( Cpanel::FastInstall::is_enabled() ) {
$self->{'cpanel_cpanelsync'} ||= $self->_make_cpanelsync_object( ['cpanel'] );
}
else {
$self->{'cpanel_cpanelsync'} ||= $self->_make_cpanelsync_object( [ 'binaries/' . $self->get_binary_sync_source( 'for' => $self->{'target_version'} ), 'cpanel' ], undef, { 'ignore_xz' => 1 } );
}
return $self->{'cpanel_cpanelsync'};
}
sub _install_ea_root {
return "firstinstall/ea";
}
sub use_easyapache {
my $self = shift or die;
return exists $self->{'easyapache_cpanelsync'} ? 1 : 0;
}
sub easyapache {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
$self->{'easyapache_cpanelsync'} ||= $self->_make_cpanelsync_object( [ 'install/ea/' . $self->get_binary_sync_source( 'for' => $self->{'target_version'} ) ], _install_ea_root() );
return $self->{'easyapache_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( [ 'binaries/' . $self->get_binary_sync_source( 'for' => $self->{'target_version'} ) ] );
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 ( Cpanel::FastInstall::is_enabled() ) {
$self->{'new_rpm_versions_file'} = $rpm_versions_destination;
}
$self->merge_cpanel_config() if $ENV{'CPANEL_BASE_INSTALL'};
$self->{'new_rpm_versions_file'} ||= $rpm_versions_destination;
$self->{'new_rpm_versions_file'} = $rpm_versions_destination if !-e $self->{'new_rpm_versions_file'};
my $old_rpm_versions_file;
if ( -e $rpm_versions_destination && $self->{'new_rpm_versions_file'} ne $rpm_versions_destination ) {
$old_rpm_versions_file = $rpm_versions_destination;
}
$self->{'rpm_manager'} = Cpanel::RPM::Versions::File->new(
{
'file' => $self->{'new_rpm_versions_file'},
'logger' => $self->logger(),
'temp_dir' => $self->{'staging_dir'} . '/rpm_downloads',
$old_rpm_versions_file ? ( 'old_rpm_versions_file' => $old_rpm_versions_file ) : (),
}
);
return $self->{'rpm_manager'};
}
sub merge_cpanel_config {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
my $cpanel_config = {};
my $cpconfig_file = $self->{'ulc'} . '/etc/cpanel.config';
my $config_defaults_file;
if ( Cpanel::FastInstall::is_enabled() ) {
$config_defaults_file = $cpconfig_file;
}
else {
$config_defaults_file = $self->cpanel()->get_staged_file($cpconfig_file);
}
Cpanel::Config::LoadConfig::loadConfig( $config_defaults_file, $cpanel_config );
$cpanel_config->{'signature_validation'} = Cpanel::Crypt::GPG::Settings::validation_setting_for_configured_mirror();
if ( -e $self->{'cpanel_config_file'} ) {
$self->logger->info("Merging custom cpanel.config entries provided by installer with cPanel defaults.");
Cpanel::Config::LoadConfig::loadConfig( $self->{'cpanel_config_file'}, $cpanel_config );
}
else {
$self->logger->info("Installing default cpanel.config, located in etc/cpanel.config");
}
Cpanel::Config::FlushConfig::flushConfig( $self->{'cpanel_config_file'}, $cpanel_config, '=', undef, { 'sort' => 1 } );
return 1;
}
sub terminate {
my $self = shift or die;
$self->isa(__PACKAGE__) or Carp::confess("must be called as a method");
my $error = shift;
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 ( ref($error) eq 'HASH' ) {
if ( $error->{'remove_blocker_file'} && -e $Cpanel::Update::Blocker::update_blocks_fname ) {
unlink $Cpanel::Update::Blocker::update_blocks_fname;
}
if ( $error->{'message'} && !$error->{'success'} ) {
$self->logger->error( "The install encountered a fatal error: " . $error->{'message'} );
}
exit( $error->{'exit'} || 0 );
}
my $error_as_string = Cpanel::Exception::get_string($error);
$self->logger->error( "The install encountered a fatal error: " . ( $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);
}
}
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 ) = @_;
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 ) = @_;
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;
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 get_local_version {
my $self = shift or die;
ref $self eq __PACKAGE__ or die("must be called as a method");
open( my $fh, '<', $self->{'ulc'} . "/version" ) or return;
my $version = <$fh> || '';
chomp $version;
$self->logger->info("Detected version '$version' from version file.");
return $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 = '/ );
chomp $version;
$version =~ s/^our \$VERSION_BUILD = '//;
$version =~ s/';\s*//;
$self->logger->info("Detected version '$version' from Tiny.pm");
return $version;
}
return;
}
sub get_neighbor_lts_tier {
my $version = shift or die;
my $direction = shift or die;
$version =~ s/\s*//g;
my ( $major, $minor ) = $version =~ m/^(\d+)\.(\d+)/ or return;
$minor++ if ( $minor % 2 );
$minor += $direction; # Move a direction.
return "$major.$minor";
}
our $update_summary_log = '/var/cpanel/updatelogs/summary.log';
sub log_update_completed {
my $self = shift;
return if $self->dry_run();
my $summary = Cpanel::Update::Logger->new( { logfile => $update_summary_log, brief => 1, stdout => 0 } );
$summary->info( "Completed update " . $self->{'starting_version'} . ' -> ' . $self->{'target_version'} );
}
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",
);
%Cpanel::CPAN::Locales::DB::Territory::en::name_to_code = (
'afghanistan' => 'af',
'africa' => '002',
'albania' => 'al',
'algeria' => 'dz',
'americansamoa' => 'as',
'americas' => '019',
'andorra' => 'ad',
'angola' => 'ao',
'anguilla' => 'ai',
'antarctica' => 'aq',
'antiguaandbarbuda' => 'ag',
'argentina' => 'ar',
'armenia' => 'am',
'aruba' => 'aw',
'ascensionisland' => 'ac',
'asia' => 142,
'australia' => 'au',
'australiaandnewzealand' => '053',
'austria' => 'at',
'azerbaijan' => 'az',
'bahamas' => 'bs',
'bahrain' => 'bh',
'bangladesh' => 'bd',
'barbados' => 'bb',
'belarus' => 'by',
'belgium' => 'be',
'belize' => 'bz',
'benin' => 'bj',
'bermuda' => 'bm',
'bhutan' => 'bt',
'bolivia' => 'bo',
'bosniaandherzegovina' => 'ba',
'botswana' => 'bw',
'bouvetisland' => 'bv',
'brazil' => 'br',
'britishantarcticterritory' => 'bq',
'britishindianoceanterritory' => 'io',
'britishvirginislands' => 'vg',
'brunei' => 'bn',
'bulgaria' => 'bg',
'burkinafaso' => 'bf',
'burundi' => 'bi',
'cambodia' => 'kh',
'cameroon' => 'cm',
'canada' => 'ca',
'canaryislands' => 'ic',
'cantonandenderburyislands' => 'ct',
'capeverde' => 'cv',
'caribbean' => '029',
'caymanislands' => 'ky',
'centralafricanrepublic' => 'cf',
'centralamerica' => '013',
'centralasia' => 143,
'ceutaandmelilla' => 'ea',
'chad' => 'td',
'channelislands' => 830,
'chile' => 'cl',
'china' => 'cn',
'christmasisland' => 'cx',
'clippertonisland' => 'cp',
'cocoskeelingislands' => 'cc',
'colombia' => 'co',
'commonwealthofindependentstates' => 172,
'comoros' => 'km',
'congodrc' => 'cd',
'congorepublic' => 'cg',
'cookislands' => 'ck',
'costarica' => 'cr',
'croatia' => 'hr',
'cuba' => 'cu',
'cyprus' => 'cy',
'czechoslovakia' => 200,
'czechrepublic' => 'cz',
'denmark' => 'dk',
'diegogarcia' => 'dg',
'djibouti' => 'dj',
'dominica' => 'dm',
'dominicanrepublic' => 'do',
'dronningmaudland' => 'nq',
'easternafrica' => '014',
'easternasia' => '030',
'easterneurope' => 151,
'eastgermany' => 'dd',
'easttimor' => 'tl',
'ecuador' => 'ec',
'egypt' => 'eg',
'elsalvador' => 'sv',
'equatorialguinea' => 'gq',
'eritrea' => 'er',
'estonia' => 'ee',
'ethiopia' => 'et',
'europe' => 150,
'europeanunion' => 'eu',
'falklandislandsislasmalvinas' => 'fk',
'faroeislands' => 'fo',
'fiji' => 'fj',
'finland' => 'fi',
'france' => 'fr',
'frenchguiana' => 'gf',
'frenchpolynesia' => 'pf',
'frenchsouthernandantarcticterritories' => 'fq',
'frenchsouthernterritories' => 'tf',
'gabon' => 'ga',
'gambia' => 'gm',
'georgia' => 'ge',
'germany' => 'de',
'ghana' => 'gh',
'gibraltar' => 'gi',
'greece' => 'gr',
'greenland' => 'gl',
'grenada' => 'gd',
'guadeloupe' => 'gp',
'guam' => 'gu',
'guatemala' => 'gt',
'guernsey' => 'gg',
'guinea' => 'gn',
'guineabissau' => 'gw',
'guyana' => 'gy',
'haiti' => 'ht',
'heardislandandmcdonaldislands' => 'hm',
'honduras' => 'hn',
'hongkong' => 'hk',
'hungary' => 'hu',
'iceland' => 'is',
'india' => 'in',
'indonesia' => 'id',
'iran' => 'ir',
'iraq' => 'iq',
'ireland' => 'ie',
'isleofman' => 'im',
'israel' => 'il',
'italy' => 'it',
'ivorycoast' => 'ci',
'jamaica' => 'jm',
'japan' => 'jp',
'jersey' => 'je',
'johnstonisland' => 'jt',
'jordan' => 'jo',
'kazakhstan' => 'kz',
'kenya' => 'ke',
'kiribati' => 'ki',
'kuwait' => 'kw',
'kyrgyzstan' => 'kg',
'laos' => 'la',
'latinamerica' => 419,
'latvia' => 'lv',
'lebanon' => 'lb',
'lesotho' => 'ls',
'liberia' => 'lr',
'libya' => 'ly',
'liechtenstein' => 'li',
'lithuania' => 'lt',
'luxembourg' => 'lu',
'macau' => 'mo',
'macedoniafyrom' => 'mk',
'madagascar' => 'mg',
'malawi' => 'mw',
'malaysia' => 'my',
'maldives' => 'mv',
'mali' => 'ml',
'malta' => 'mt',
'marshallislands' => 'mh',
'martinique' => 'mq',
'mauritania' => 'mr',
'mauritius' => 'mu',
'mayotte' => 'yt',
'melanesia' => '054',
'metropolitanfrance' => 'fx',
'mexico' => 'mx',
'micronesia' => 'fm',
'micronesianregion' => '057',
'middleafrica' => '017',
'midwayislands' => 'mi',
'moldova' => 'md',
'monaco' => 'mc',
'mongolia' => 'mn',
'montenegro' => 'me',
'montserrat' => 'ms',
'morocco' => 'ma',
'mozambique' => 'mz',
'myanmarburma' => 'mm',
'namibia' => 'na',
'nauru' => 'nr',
'nepal' => 'np',
'netherlands' => 'nl',
'netherlandsantilles' => 'an',
'neutralzone' => 'nt',
'newcaledonia' => 'nc',
'newzealand' => 'nz',
'nicaragua' => 'ni',
'niger' => 'ne',
'nigeria' => 'ng',
'niue' => 'nu',
'norfolkisland' => 'nf',
'northamerica' => '003',
'northernafrica' => '015',
'northernamerica' => '021',
'northerneurope' => 154,
'northernmarianaislands' => 'mp',
'northkorea' => 'kp',
'northvietnam' => 'vd',
'norway' => 'no',
'oceania' => '009',
'oman' => 'om',
'outlyingoceania' => 'qo',
'pacificislandstrustterritory' => 'pc',
'pakistan' => 'pk',
'palau' => 'pw',
'palestinianterritories' => 'ps',
'panama' => 'pa',
'panamacanalzone' => 'pz',
'papuanewguinea' => 'pg',
'paraguay' => 'py',
'people’sdemocraticrepublicofyemen' => 'yd',
'peru' => 'pe',
'philippines' => 'ph',
'pitcairnislands' => 'pn',
'poland' => 'pl',
'polynesia' => '061',
'portugal' => 'pt',
'puertorico' => 'pr',
'qatar' => 'qa',
'romania' => 'ro',
'russia' => 'ru',
'rwanda' => 'rw',
'réunion' => 're',
'saintbarthélemy' => 'bl',
'sainthelena' => 'sh',
'saintkittsandnevis' => 'kn',
'saintlucia' => 'lc',
'saintmartin' => 'mf',
'saintpierreandmiquelon' => 'pm',
'saintvincentandthegrenadines' => 'vc',
'samoa' => 'ws',
'sanmarino' => 'sm',
'saudiarabia' => 'sa',
'senegal' => 'sn',
'serbia' => 'rs',
'serbiaandmontenegro' => 'cs',
'seychelles' => 'sc',
'sierraleone' => 'sl',
'singapore' => 'sg',
'slovakia' => 'sk',
'slovenia' => 'si',
'solomonislands' => 'sb',
'somalia' => 'so',
'southafrica' => 'za',
'southamerica' => '005',
'southcentralasia' => '062',
'southeasternasia' => '035',
'southernafrica' => '018',
'southernasia' => '034',
'southerneurope' => '039',
'southgeorgiaandthesouthsandwichislands' => 'gs',
'southkorea' => 'kr',
'spain' => 'es',
'srilanka' => 'lk',
'sudan' => 'sd',
'suriname' => 'sr',
'svalbardandjanmayen' => 'sj',
'swaziland' => 'sz',
'sweden' => 'se',
'switzerland' => 'ch',
'syria' => 'sy',
'sãotoméandpríncipe' => 'st',
'taiwan' => 'tw',
'tajikistan' => 'tj',
'tanzania' => 'tz',
'thailand' => 'th',
'togo' => 'tg',
'tokelau' => 'tk',
'tonga' => 'to',
'trinidadandtobago' => 'tt',
'tristandacunha' => 'ta',
'tunisia' => 'tn',
'turkey' => 'tr',
'turkmenistan' => 'tm',
'turksandcaicosislands' => 'tc',
'tuvalu' => 'tv',
"u\.s\.minoroutlyingislands" => 'um',
"u\.s\.miscellaneouspacificislands" => 'pu',
"u\.s\.virginislands" => 'vi',
'uganda' => 'ug',
'ukraine' => 'ua',
'unionofsovietsocialistrepublics' => 'su',
'unitedarabemirates' => 'ae',
'unitedkingdom' => 'gb',
'unitedstates' => 'us',
'unknownregion' => 'zz',
'uruguay' => 'uy',
'uzbekistan' => 'uz',
'vanuatu' => 'vu',
'vaticancity' => 'va',
'venezuela' => 've',
'vietnam' => 'vn',
'wakeisland' => 'wk',
'wallisandfutuna' => 'wf',
'westernafrica' => '011',
'westernasia' => 145,
'westerneurope' => 155,
'westernsahara' => 'eh',
'world' => '001',
'yemen' => 'ye',
'zambia' => 'zm',
'zimbabwe' => 'zw',
'Ålandislands' => 'ax',
);
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::code_to_name = (
'aa' => 'Afar',
'ab' => 'Abkhazian',
'ace' => 'Achinese',
'ach' => 'Acoli',
'ada' => 'Adangme',
'ady' => 'Adyghe',
'ae' => 'Avestan',
'af' => 'Afrikaans',
'afa' => "Afro\-Asiatic\ Language",
'afh' => 'Afrihili',
'agq' => 'Aghem',
'ain' => 'Ainu',
'ak' => 'Akan',
'akk' => 'Akkadian',
'ale' => 'Aleut',
'alg' => "Algonquian\ Language",
'alt' => "Southern\ Altai",
'am' => 'Amharic',
'an' => 'Aragonese',
'ang' => "Old\ English",
'anp' => 'Angika',
'apa' => "Apache\ Language",
'ar' => 'Arabic',
'arc' => 'Aramaic',
'arn' => 'Araucanian',
'arp' => 'Arapaho',
'art' => "Artificial\ Language",
'arw' => 'Arawak',
'as' => 'Assamese',
'asa' => 'Asu',
'ast' => 'Asturian',
'ath' => "Athapascan\ Language",
'aus' => "Australian\ Language",
'av' => 'Avaric',
'awa' => 'Awadhi',
'ay' => 'Aymara',
'az' => 'Azeri',
'ba' => 'Bashkir',
'bad' => 'Banda',
'bai' => "Bamileke\ Language",
'bal' => 'Baluchi',
'ban' => 'Balinese',
'bas' => 'Basaa',
'bat' => "Baltic\ Language",
'be' => 'Belarusian',
'bej' => 'Beja',
'bem' => 'Bemba',
'ber' => 'Berber',
'bez' => 'Bena',
'bg' => 'Bulgarian',
'bh' => 'Bihari',
'bho' => 'Bhojpuri',
'bi' => 'Bislama',
'bik' => 'Bikol',
'bin' => 'Bini',
'bla' => 'Siksika',
'bm' => 'Bambara',
'bn' => 'Bengali',
'bnt' => 'Bantu',
'bo' => 'Tibetan',
'br' => 'Breton',
'bra' => 'Braj',
'brx' => 'Bodo',
'bs' => 'Bosnian',
'btk' => 'Batak',
'bua' => 'Buriat',
'bug' => 'Buginese',
'byn' => 'Blin',
'ca' => 'Catalan',
'cad' => 'Caddo',
'cai' => "Central\ American\ Indian\ Language",
'car' => 'Carib',
'cau' => "Caucasian\ Language",
'cay' => 'Cayuga',
'cch' => 'Atsam',
'ce' => 'Chechen',
'ceb' => 'Cebuano',
'cel' => "Celtic\ Language",
'cgg' => 'Chiga',
'ch' => 'Chamorro',
'chb' => 'Chibcha',
'chg' => 'Chagatai',
'chk' => 'Chuukese',
'chm' => 'Mari',
'chn' => "Chinook\ Jargon",
'cho' => 'Choctaw',
'chp' => 'Chipewyan',
'chr' => 'Cherokee',
'chy' => 'Cheyenne',
'cmc' => "Chamic\ Language",
'co' => 'Corsican',
'cop' => 'Coptic',
'cpe' => "English\-based\ Creole\ or\ Pidgin",
'cpf' => "French\-based\ Creole\ or\ Pidgin",
'cpp' => "Portuguese\-based\ Creole\ or\ Pidgin",
'cr' => 'Cree',
'crh' => "Crimean\ Turkish",
'crp' => "Creole\ or\ Pidgin",
'cs' => 'Czech',
'csb' => 'Kashubian',
'cu' => "Church\ Slavic",
'cus' => "Cushitic\ Language",
'cv' => 'Chuvash',
'cy' => 'Welsh',
'da' => 'Danish',
'dak' => 'Dakota',
'dar' => 'Dargwa',
'dav' => 'Taita',
'day' => 'Dayak',
'de' => 'German',
'de_at' => "Austrian\ German",
'de_ch' => "Swiss\ High\ German",
'del' => 'Delaware',
'den' => 'Slave',
'dgr' => 'Dogrib',
'din' => 'Dinka',
'dje' => 'Zarma',
'doi' => 'Dogri',
'dra' => "Dravidian\ Language",
'dsb' => "Lower\ Sorbian",
'dua' => 'Duala',
'dum' => "Middle\ Dutch",
'dv' => 'Divehi',
'dyo' => "Jola\-Fonyi",
'dyu' => 'Dyula',
'dz' => 'Dzongkha',
'ebu' => 'Embu',
'ee' => 'Ewe',
'efi' => 'Efik',
'egy' => "Ancient\ Egyptian",
'eka' => 'Ekajuk',
'el' => 'Greek',
'elx' => 'Elamite',
'en' => 'English',
'en_au' => "Australian\ English",
'en_ca' => "Canadian\ English",
'en_gb' => "British\ English",
'en_us' => "U\.S\.\ English",
'enm' => "Middle\ English",
'eo' => 'Esperanto',
'es' => 'Spanish',
'es_419' => "Latin\ American\ Spanish",
'es_es' => "Iberian\ Spanish",
'et' => 'Estonian',
'eu' => 'Basque',
'ewo' => 'Ewondo',
'fa' => 'Persian',
'fan' => 'Fang',
'fat' => 'Fanti',
'ff' => 'Fulah',
'fi' => 'Finnish',
'fil' => 'Filipino',
'fiu' => "Finno\-Ugrian\ Language",
'fj' => 'Fijian',
'fo' => 'Faroese',
'fon' => 'Fon',
'fr' => 'French',
'fr_ca' => "Canadian\ French",
'fr_ch' => "Swiss\ French",
'frm' => "Middle\ French",
'fro' => "Old\ French",
'frr' => "Northern\ Frisian",
'frs' => "Eastern\ Frisian",
'fur' => 'Friulian',
'fy' => "Western\ Frisian",
'ga' => 'Irish',
'gaa' => 'Ga',
'gay' => 'Gayo',
'gba' => 'Gbaya',
'gd' => "Scottish\ Gaelic",
'gem' => "Germanic\ Language",
'gez' => 'Geez',
'gil' => 'Gilbertese',
'gl' => 'Galician',
'gmh' => "Middle\ High\ German",
'gn' => 'Guarani',
'goh' => "Old\ High\ German",
'gon' => 'Gondi',
'gor' => 'Gorontalo',
'got' => 'Gothic',
'grb' => 'Grebo',
'grc' => "Ancient\ Greek",
'gsw' => "Swiss\ German",
'gu' => 'Gujarati',
'guz' => 'Gusii',
'gv' => 'Manx',
'gwi' => 'Gwichʼin',
'ha' => 'Hausa',
'hai' => 'Haida',
'haw' => 'Hawaiian',
'he' => 'Hebrew',
'hi' => 'Hindi',
'hil' => 'Hiligaynon',
'him' => 'Himachali',
'hit' => 'Hittite',
'hmn' => 'Hmong',
'ho' => "Hiri\ Motu",
'hr' => 'Croatian',
'hsb' => "Upper\ Sorbian",
'ht' => 'Haitian',
'hu' => 'Hungarian',
'hup' => 'Hupa',
'hy' => 'Armenian',
'hz' => 'Herero',
'ia' => 'Interlingua',
'iba' => 'Iban',
'id' => 'Indonesian',
'ie' => 'Interlingue',
'ig' => 'Igbo',
'ii' => "Sichuan\ Yi",
'ijo' => 'Ijo',
'ik' => 'Inupiaq',
'ilo' => 'Iloko',
'inc' => "Indic\ Language",
'ine' => "Indo\-European\ Language",
'inh' => 'Ingush',
'io' => 'Ido',
'ira' => "Iranian\ Language",
'iro' => "Iroquoian\ Language",
'is' => 'Icelandic',
'it' => 'Italian',
'iu' => 'Inuktitut',
'ja' => 'Japanese',
'jbo' => 'Lojban',
'jmc' => 'Machame',
'jpr' => "Judeo\-Persian",
'jrb' => "Judeo\-Arabic",
'jv' => 'Javanese',
'ka' => 'Georgian',
'kaa' => "Kara\-Kalpak",
'kab' => 'Kabyle',
'kac' => 'Kachin',
'kaj' => 'Jju',
'kam' => 'Kamba',
'kar' => 'Karen',
'kaw' => 'Kawi',
'kbd' => 'Kabardian',
'kcg' => 'Tyap',
'kde' => 'Makonde',
'kea' => 'Kabuverdianu',
'kfo' => 'Koro',
'kg' => 'Kongo',
'kha' => 'Khasi',
'khi' => "Khoisan\ Language",
'kho' => 'Khotanese',
'khq' => "Koyra\ Chiini",
'ki' => 'Kikuyu',
'kj' => 'Kuanyama',
'kk' => 'Kazakh',
'kl' => 'Kalaallisut',
'kln' => 'Kalenjin',
'km' => 'Khmer',
'kmb' => 'Kimbundu',
'kn' => 'Kannada',
'ko' => 'Korean',
'kok' => 'Konkani',
'kos' => 'Kosraean',
'kpe' => 'Kpelle',
'kr' => 'Kanuri',
'krc' => "Karachay\-Balkar",
'krl' => 'Karelian',
'kro' => 'Kru',
'kru' => 'Kurukh',
'ks' => 'Kashmiri',
'ksb' => 'Shambala',
'ksf' => 'Bafia',
'ksh' => 'Colognian',
'ku' => 'Kurdish',
'kum' => 'Kumyk',
'kut' => 'Kutenai',
'kv' => 'Komi',
'kw' => 'Cornish',
'ky' => 'Kirghiz',
'la' => 'Latin',
'lad' => 'Ladino',
'lag' => 'Langi',
'lah' => 'Lahnda',
'lam' => 'Lamba',
'lb' => 'Luxembourgish',
'lez' => 'Lezghian',
'lg' => 'Ganda',
'li' => 'Limburgish',
'ln' => 'Lingala',
'lo' => 'Lao',
'lol' => 'Mongo',
'loz' => 'Lozi',
'lt' => 'Lithuanian',
'lu' => "Luba\-Katanga",
'lua' => "Luba\-Lulua",
'lui' => 'Luiseno',
'lun' => 'Lunda',
'luo' => 'Luo',
'lus' => 'Lushai',
'luy' => 'Luyia',
'lv' => 'Latvian',
'mad' => 'Madurese',
'mag' => 'Magahi',
'mai' => 'Maithili',
'mak' => 'Makasar',
'man' => 'Mandingo',
'map' => "Austronesian\ Language",
'mas' => 'Masai',
'mdf' => 'Moksha',
'mdr' => 'Mandar',
'men' => 'Mende',
'mer' => 'Meru',
'mfe' => 'Morisyen',
'mg' => 'Malagasy',
'mga' => "Middle\ Irish",
'mgh' => "Makhuwa\-Meetto",
'mh' => 'Marshallese',
'mi' => 'Maori',
'mic' => 'Micmac',
'min' => 'Minangkabau',
'mis' => "Miscellaneous\ Language",
'mk' => 'Macedonian',
'mkh' => "Mon\-Khmer\ Language",
'ml' => 'Malayalam',
'mn' => 'Mongolian',
'mnc' => 'Manchu',
'mni' => 'Manipuri',
'mno' => "Manobo\ Language",
'mo' => 'Moldavian',
'moh' => 'Mohawk',
'mos' => 'Mossi',
'mr' => 'Marathi',
'ms' => 'Malay',
'mt' => 'Maltese',
'mua' => 'Mundang',
'mul' => "Multiple\ Languages",
'mun' => "Munda\ Language",
'mus' => 'Creek',
'mwl' => 'Mirandese',
'mwr' => 'Marwari',
'my' => 'Burmese',
'myn' => "Mayan\ Language",
'myv' => 'Erzya',
'na' => 'Nauru',
'nah' => 'Nahuatl',
'nai' => "North\ American\ Indian\ Language",
'nap' => 'Neapolitan',
'naq' => 'Nama',
'nb' => "Norwegian\ Bokmål",
'nd' => "North\ Ndebele",
'nds' => "Low\ German",
'ne' => 'Nepali',
'new' => 'Newari',
'ng' => 'Ndonga',
'nia' => 'Nias',
'nic' => "Niger\-Kordofanian\ Language",
'niu' => 'Niuean',
'nl' => 'Dutch',
'nl_be' => 'Flemish',
'nmg' => 'Kwasio',
'nn' => "Norwegian\ Nynorsk",
'no' => 'Norwegian',
'nog' => 'Nogai',
'non' => "Old\ Norse",
'nqo' => 'N’Ko',
'nr' => "South\ Ndebele",
'nso' => "Northern\ Sotho",
'nub' => "Nubian\ Language",
'nus' => 'Nuer',
'nv' => 'Navajo',
'nwc' => "Classical\ Newari",
'ny' => 'Nyanja',
'nym' => 'Nyamwezi',
'nyn' => 'Nyankole',
'nyo' => 'Nyoro',
'nzi' => 'Nzima',
'oc' => 'Occitan',
'oj' => 'Ojibwa',
'om' => 'Oromo',
'or' => 'Oriya',
'os' => 'Ossetic',
'osa' => 'Osage',
'ota' => "Ottoman\ Turkish",
'oto' => "Otomian\ Language",
'pa' => 'Punjabi',
'paa' => "Papuan\ Language",
'pag' => 'Pangasinan',
'pal' => 'Pahlavi',
'pam' => 'Pampanga',
'pap' => 'Papiamento',
'pau' => 'Palauan',
'peo' => "Old\ Persian",
'phi' => "Philippine\ Language",
'phn' => 'Phoenician',
'pi' => 'Pali',
'pl' => 'Polish',
'pon' => 'Pohnpeian',
'pra' => "Prakrit\ Language",
'pro' => "Old\ Provençal",
'ps' => 'Pushto',
'pt' => 'Portuguese',
'pt_br' => "Brazilian\ Portuguese",
'pt_pt' => "Iberian\ Portuguese",
'qu' => 'Quechua',
'raj' => 'Rajasthani',
'rap' => 'Rapanui',
'rar' => 'Rarotongan',
'rm' => 'Romansh',
'rn' => 'Rundi',
'ro' => 'Romanian',
'roa' => "Romance\ Language",
'rof' => 'Rombo',
'rom' => 'Romany',
'ru' => 'Russian',
'rup' => 'Aromanian',
'rw' => 'Kinyarwanda',
'rwk' => 'Rwa',
'sa' => 'Sanskrit',
'sad' => 'Sandawe',
'sah' => 'Sakha',
'sai' => "South\ American\ Indian\ Language",
'sal' => "Salishan\ Language",
'sam' => "Samaritan\ Aramaic",
'saq' => 'Samburu',
'sas' => 'Sasak',
'sat' => 'Santali',
'sbp' => 'Sangu',
'sc' => 'Sardinian',
'scn' => 'Sicilian',
'sco' => 'Scots',
'sd' => 'Sindhi',
'se' => "Northern\ Sami",
'see' => 'Seneca',
'seh' => 'Sena',
'sel' => 'Selkup',
'sem' => "Semitic\ Language",
'ses' => "Koyraboro\ Senni",
'sg' => 'Sango',
'sga' => "Old\ Irish",
'sgn' => "Sign\ Language",
'sh' => "Serbo\-Croatian",
'shi' => 'Tachelhit',
'shn' => 'Shan',
'si' => 'Sinhala',
'sid' => 'Sidamo',
'sio' => "Siouan\ Language",
'sit' => "Sino\-Tibetan\ Language",
'sk' => 'Slovak',
'sl' => 'Slovenian',
'sla' => "Slavic\ Language",
'sm' => 'Samoan',
'sma' => "Southern\ Sami",
'smi' => "Sami\ Language",
'smj' => "Lule\ Sami",
'smn' => "Inari\ Sami",
'sms' => "Skolt\ Sami",
'sn' => 'Shona',
'snk' => 'Soninke',
'so' => 'Somali',
'sog' => 'Sogdien',
'son' => 'Songhai',
'sq' => 'Albanian',
'sr' => 'Serbian',
'srn' => "Sranan\ Tongo",
'srr' => 'Serer',
'ss' => 'Swati',
'ssa' => "Nilo\-Saharan\ Language",
'ssy' => 'Saho',
'st' => "Southern\ Sotho",
'su' => 'Sundanese',
'suk' => 'Sukuma',
'sus' => 'Susu',
'sux' => 'Sumerian',
'sv' => 'Swedish',
'sw' => 'Swahili',
'swb' => 'Comorian',
'swc' => "Congo\ Swahili",
'syc' => "Classical\ Syriac",
'syr' => 'Syriac',
'ta' => 'Tamil',
'tai' => "Tai\ Language",
'te' => 'Telugu',
'tem' => 'Timne',
'teo' => 'Teso',
'ter' => 'Tereno',
'tet' => 'Tetum',
'tg' => 'Tajik',
'th' => 'Thai',
'ti' => 'Tigrinya',
'tig' => 'Tigre',
'tiv' => 'Tiv',
'tk' => 'Turkmen',
'tkl' => 'Tokelau',
'tl' => 'Tagalog',
'tlh' => 'Klingon',
'tli' => 'Tlingit',
'tmh' => 'Tamashek',
'tn' => 'Tswana',
'to' => 'Tonga',
'tog' => "Nyasa\ Tonga",
'tpi' => "Tok\ Pisin",
'tr' => 'Turkish',
'trv' => 'Taroko',
'ts' => 'Tsonga',
'tsi' => 'Tsimshian',
'tt' => 'Tatar',
'tum' => 'Tumbuka',
'tup' => "Tupi\ Language",
'tut' => "Altaic\ Language",
'tvl' => 'Tuvalu',
'tw' => 'Twi',
'twq' => 'Tasawaq',
'ty' => 'Tahitian',
'tyv' => 'Tuvinian',
'tzm' => "Central\ Morocco\ Tamazight",
'udm' => 'Udmurt',
'ug' => 'Uyghur',
'uga' => 'Ugaritic',
'uk' => 'Ukrainian',
'umb' => 'Umbundu',
'und' => "Unknown\ Language",
'ur' => 'Urdu',
'uz' => 'Uzbek',
'vai' => 'Vai',
've' => 'Venda',
'vi' => 'Vietnamese',
'vo' => 'Volapük',
'vot' => 'Votic',
'vun' => 'Vunjo',
'wa' => 'Walloon',
'wae' => 'Walser',
'wak' => "Wakashan\ Language",
'wal' => 'Walamo',
'war' => 'Waray',
'was' => 'Washo',
'wen' => "Sorbian\ Language",
'wo' => 'Wolof',
'xal' => 'Kalmyk',
'xh' => 'Xhosa',
'xog' => 'Soga',
'yao' => 'Yao',
'yap' => 'Yapese',
'yav' => 'Yangben',
'yi' => 'Yiddish',
'yo' => 'Yoruba',
'ypk' => "Yupik\ Language",
'yue' => 'Cantonese',
'za' => 'Zhuang',
'zap' => 'Zapotec',
'zbl' => 'Blissymbols',
'zen' => 'Zenaga',
'zh' => 'Chinese',
'znd' => 'Zande',
'zu' => 'Zulu',
'zun' => 'Zuni',
'zxx' => "No\ linguistic\ content",
'zza' => 'Zaza',
);
%Cpanel::CPAN::Locales::DB::Language::en::name_to_code = (
'abkhazian' => 'ab',
'achinese' => 'ace',
'acoli' => 'ach',
'adangme' => 'ada',
'adyghe' => 'ady',
'afar' => 'aa',
'afrihili' => 'afh',
'afrikaans' => 'af',
'afroasiaticlanguage' => 'afa',
'aghem' => 'agq',
'ainu' => 'ain',
'akan' => 'ak',
'akkadian' => 'akk',
'albanian' => 'sq',
'aleut' => 'ale',
'algonquianlanguage' => 'alg',
'altaiclanguage' => 'tut',
'amharic' => 'am',
'ancientegyptian' => 'egy',
'ancientgreek' => 'grc',
'angika' => 'anp',
'apachelanguage' => 'apa',
'arabic' => 'ar',
'aragonese' => 'an',
'aramaic' => 'arc',
'arapaho' => 'arp',
'araucanian' => 'arn',
'arawak' => 'arw',
'armenian' => 'hy',
'aromanian' => 'rup',
'artificiallanguage' => 'art',
'assamese' => 'as',
'asturian' => 'ast',
'asu' => 'asa',
'athapascanlanguage' => 'ath',
'atsam' => 'cch',
'australianenglish' => 'en_au',
'australianlanguage' => 'aus',
'austriangerman' => 'de_at',
'austronesianlanguage' => 'map',
'avaric' => 'av',
'avestan' => 'ae',
'awadhi' => 'awa',
'aymara' => 'ay',
'azeri' => 'az',
'bafia' => 'ksf',
'balinese' => 'ban',
'balticlanguage' => 'bat',
'baluchi' => 'bal',
'bambara' => 'bm',
'bamilekelanguage' => 'bai',
'banda' => 'bad',
'bantu' => 'bnt',
'basaa' => 'bas',
'bashkir' => 'ba',
'basque' => 'eu',
'batak' => 'btk',
'beja' => 'bej',
'belarusian' => 'be',
'bemba' => 'bem',
'bena' => 'bez',
'bengali' => 'bn',
'berber' => 'ber',
'bhojpuri' => 'bho',
'bihari' => 'bh',
'bikol' => 'bik',
'bini' => 'bin',
'bislama' => 'bi',
'blin' => 'byn',
'blissymbols' => 'zbl',
'bodo' => 'brx',
'bosnian' => 'bs',
'braj' => 'bra',
'brazilianportuguese' => 'pt_br',
'breton' => 'br',
'britishenglish' => 'en_gb',
'buginese' => 'bug',
'bulgarian' => 'bg',
'buriat' => 'bua',
'burmese' => 'my',
'caddo' => 'cad',
'canadianenglish' => 'en_ca',
'canadianfrench' => 'fr_ca',
'cantonese' => 'yue',
'carib' => 'car',
'catalan' => 'ca',
'caucasianlanguage' => 'cau',
'cayuga' => 'cay',
'cebuano' => 'ceb',
'celticlanguage' => 'cel',
'centralamericanindianlanguage' => 'cai',
'centralmoroccotamazight' => 'tzm',
'chagatai' => 'chg',
'chamiclanguage' => 'cmc',
'chamorro' => 'ch',
'chechen' => 'ce',
'cherokee' => 'chr',
'cheyenne' => 'chy',
'chibcha' => 'chb',
'chiga' => 'cgg',
'chinese' => 'zh',
'chinookjargon' => 'chn',
'chipewyan' => 'chp',
'choctaw' => 'cho',
'churchslavic' => 'cu',
'chuukese' => 'chk',
'chuvash' => 'cv',
'classicalnewari' => 'nwc',
'classicalsyriac' => 'syc',
'colognian' => 'ksh',
'comorian' => 'swb',
'congoswahili' => 'swc',
'coptic' => 'cop',
'cornish' => 'kw',
'corsican' => 'co',
'cree' => 'cr',
'creek' => 'mus',
'creoleorpidgin' => 'crp',
'crimeanturkish' => 'crh',
'croatian' => 'hr',
'cushiticlanguage' => 'cus',
'czech' => 'cs',
'dakota' => 'dak',
'danish' => 'da',
'dargwa' => 'dar',
'dayak' => 'day',
'delaware' => 'del',
'dinka' => 'din',
'divehi' => 'dv',
'dogri' => 'doi',
'dogrib' => 'dgr',
'dravidianlanguage' => 'dra',
'duala' => 'dua',
'dutch' => 'nl',
'dyula' => 'dyu',
'dzongkha' => 'dz',
'easternfrisian' => 'frs',
'efik' => 'efi',
'ekajuk' => 'eka',
'elamite' => 'elx',
'embu' => 'ebu',
'english' => 'en',
'englishbasedcreoleorpidgin' => 'cpe',
'erzya' => 'myv',
'esperanto' => 'eo',
'estonian' => 'et',
'ewe' => 'ee',
'ewondo' => 'ewo',
'fang' => 'fan',
'fanti' => 'fat',
'faroese' => 'fo',
'fijian' => 'fj',
'filipino' => 'fil',
'finnish' => 'fi',
'finnougrianlanguage' => 'fiu',
'flemish' => 'nl_be',
'fon' => 'fon',
'french' => 'fr',
'frenchbasedcreoleorpidgin' => 'cpf',
'friulian' => 'fur',
'fulah' => 'ff',
'ga' => 'gaa',
'galician' => 'gl',
'ganda' => 'lg',
'gayo' => 'gay',
'gbaya' => 'gba',
'geez' => 'gez',
'georgian' => 'ka',
'german' => 'de',
'germaniclanguage' => 'gem',
'gilbertese' => 'gil',
'gondi' => 'gon',
'gorontalo' => 'gor',
'gothic' => 'got',
'grebo' => 'grb',
'greek' => 'el',
'guarani' => 'gn',
'gujarati' => 'gu',
'gusii' => 'guz',
'gwichʼin' => 'gwi',
'haida' => 'hai',
'haitian' => 'ht',
'hausa' => 'ha',
'hawaiian' => 'haw',
'hebrew' => 'he',
'herero' => 'hz',
'hiligaynon' => 'hil',
'himachali' => 'him',
'hindi' => 'hi',
'hirimotu' => 'ho',
'hittite' => 'hit',
'hmong' => 'hmn',
'hungarian' => 'hu',
'hupa' => 'hup',
'iban' => 'iba',
'iberianportuguese' => 'pt_pt',
'iberianspanish' => 'es_es',
'icelandic' => 'is',
'ido' => 'io',
'igbo' => 'ig',
'ijo' => 'ijo',
'iloko' => 'ilo',
'inarisami' => 'smn',
'indiclanguage' => 'inc',
'indoeuropeanlanguage' => 'ine',
'indonesian' => 'id',
'ingush' => 'inh',
'interlingua' => 'ia',
'interlingue' => 'ie',
'inuktitut' => 'iu',
'inupiaq' => 'ik',
'iranianlanguage' => 'ira',
'irish' => 'ga',
'iroquoianlanguage' => 'iro',
'italian' => 'it',
'japanese' => 'ja',
'javanese' => 'jv',
'jju' => 'kaj',
'jolafonyi' => 'dyo',
'judeoarabic' => 'jrb',
'judeopersian' => 'jpr',
'kabardian' => 'kbd',
'kabuverdianu' => 'kea',
'kabyle' => 'kab',
'kachin' => 'kac',
'kalaallisut' => 'kl',
'kalenjin' => 'kln',
'kalmyk' => 'xal',
'kamba' => 'kam',
'kannada' => 'kn',
'kanuri' => 'kr',
'karachaybalkar' => 'krc',
'karakalpak' => 'kaa',
'karelian' => 'krl',
'karen' => 'kar',
'kashmiri' => 'ks',
'kashubian' => 'csb',
'kawi' => 'kaw',
'kazakh' => 'kk',
'khasi' => 'kha',
'khmer' => 'km',
'khoisanlanguage' => 'khi',
'khotanese' => 'kho',
'kikuyu' => 'ki',
'kimbundu' => 'kmb',
'kinyarwanda' => 'rw',
'kirghiz' => 'ky',
'klingon' => 'tlh',
'komi' => 'kv',
'kongo' => 'kg',
'konkani' => 'kok',
'korean' => 'ko',
'koro' => 'kfo',
'kosraean' => 'kos',
'koyraborosenni' => 'ses',
'koyrachiini' => 'khq',
'kpelle' => 'kpe',
'kru' => 'kro',
'kuanyama' => 'kj',
'kumyk' => 'kum',
'kurdish' => 'ku',
'kurukh' => 'kru',
'kutenai' => 'kut',
'kwasio' => 'nmg',
'ladino' => 'lad',
'lahnda' => 'lah',
'lamba' => 'lam',
'langi' => 'lag',
'lao' => 'lo',
'latin' => 'la',
'latinamericanspanish' => 'es_419',
'latvian' => 'lv',
'lezghian' => 'lez',
'limburgish' => 'li',
'lingala' => 'ln',
'lithuanian' => 'lt',
'lojban' => 'jbo',
'lowersorbian' => 'dsb',
'lowgerman' => 'nds',
'lozi' => 'loz',
'lubakatanga' => 'lu',
'lubalulua' => 'lua',
'luiseno' => 'lui',
'lulesami' => 'smj',
'lunda' => 'lun',
'luo' => 'luo',
'lushai' => 'lus',
'luxembourgish' => 'lb',
'luyia' => 'luy',
'macedonian' => 'mk',
'machame' => 'jmc',
'madurese' => 'mad',
'magahi' => 'mag',
'maithili' => 'mai',
'makasar' => 'mak',
'makhuwameetto' => 'mgh',
'makonde' => 'kde',
'malagasy' => 'mg',
'malay' => 'ms',
'malayalam' => 'ml',
'maltese' => 'mt',
'manchu' => 'mnc',
'mandar' => 'mdr',
'mandingo' => 'man',
'manipuri' => 'mni',
'manobolanguage' => 'mno',
'manx' => 'gv',
'maori' => 'mi',
'marathi' => 'mr',
'mari' => 'chm',
'marshallese' => 'mh',
'marwari' => 'mwr',
'masai' => 'mas',
'mayanlanguage' => 'myn',
'mende' => 'men',
'meru' => 'mer',
'micmac' => 'mic',
'middledutch' => 'dum',
'middleenglish' => 'enm',
'middlefrench' => 'frm',
'middlehighgerman' => 'gmh',
'middleirish' => 'mga',
'minangkabau' => 'min',
'mirandese' => 'mwl',
'miscellaneouslanguage' => 'mis',
'mohawk' => 'moh',
'moksha' => 'mdf',
'moldavian' => 'mo',
'mongo' => 'lol',
'mongolian' => 'mn',
'monkhmerlanguage' => 'mkh',
'morisyen' => 'mfe',
'mossi' => 'mos',
'multiplelanguages' => 'mul',
'mundalanguage' => 'mun',
'mundang' => 'mua',
'nahuatl' => 'nah',
'nama' => 'naq',
'nauru' => 'na',
'navajo' => 'nv',
'ndonga' => 'ng',
'neapolitan' => 'nap',
'nepali' => 'ne',
'newari' => 'new',
'nias' => 'nia',
'nigerkordofanianlanguage' => 'nic',
'nilosaharanlanguage' => 'ssa',
'niuean' => 'niu',
'nogai' => 'nog',
'nolinguisticcontent' => 'zxx',
'northamericanindianlanguage' => 'nai',
'northernfrisian' => 'frr',
'northernsami' => 'se',
'northernsotho' => 'nso',
'northndebele' => 'nd',
'norwegian' => 'no',
'norwegianbokmål' => 'nb',
'norwegiannynorsk' => 'nn',
'nubianlanguage' => 'nub',
'nuer' => 'nus',
'nyamwezi' => 'nym',
'nyanja' => 'ny',
'nyankole' => 'nyn',
'nyasatonga' => 'tog',
'nyoro' => 'nyo',
'nzima' => 'nzi',
'n’ko' => 'nqo',
'occitan' => 'oc',
'ojibwa' => 'oj',
'oldenglish' => 'ang',
'oldfrench' => 'fro',
'oldhighgerman' => 'goh',
'oldirish' => 'sga',
'oldnorse' => 'non',
'oldpersian' => 'peo',
'oldprovençal' => 'pro',
'oriya' => 'or',
'oromo' => 'om',
'osage' => 'osa',
'ossetic' => 'os',
'otomianlanguage' => 'oto',
'ottomanturkish' => 'ota',
'pahlavi' => 'pal',
'palauan' => 'pau',
'pali' => 'pi',
'pampanga' => 'pam',
'pangasinan' => 'pag',
'papiamento' => 'pap',
'papuanlanguage' => 'paa',
'persian' => 'fa',
'philippinelanguage' => 'phi',
'phoenician' => 'phn',
'pohnpeian' => 'pon',
'polish' => 'pl',
'portuguese' => 'pt',
'portuguesebasedcreoleorpidgin' => 'cpp',
'prakritlanguage' => 'pra',
'punjabi' => 'pa',
'pushto' => 'ps',
'quechua' => 'qu',
'rajasthani' => 'raj',
'rapanui' => 'rap',
'rarotongan' => 'rar',
'romancelanguage' => 'roa',
'romanian' => 'ro',
'romansh' => 'rm',
'romany' => 'rom',
'rombo' => 'rof',
'rundi' => 'rn',
'russian' => 'ru',
'rwa' => 'rwk',
'saho' => 'ssy',
'sakha' => 'sah',
'salishanlanguage' => 'sal',
'samaritanaramaic' => 'sam',
'samburu' => 'saq',
'samilanguage' => 'smi',
'samoan' => 'sm',
'sandawe' => 'sad',
'sango' => 'sg',
'sangu' => 'sbp',
'sanskrit' => 'sa',
'santali' => 'sat',
'sardinian' => 'sc',
'sasak' => 'sas',
'scots' => 'sco',
'scottishgaelic' => 'gd',
'selkup' => 'sel',
'semiticlanguage' => 'sem',
'sena' => 'seh',
'seneca' => 'see',
'serbian' => 'sr',
'serbocroatian' => 'sh',
'serer' => 'srr',
'shambala' => 'ksb',
'shan' => 'shn',
'shona' => 'sn',
'sichuanyi' => 'ii',
'sicilian' => 'scn',
'sidamo' => 'sid',
'signlanguage' => 'sgn',
'siksika' => 'bla',
'sindhi' => 'sd',
'sinhala' => 'si',
'sinotibetanlanguage' => 'sit',
'siouanlanguage' => 'sio',
'skoltsami' => 'sms',
'slave' => 'den',
'slaviclanguage' => 'sla',
'slovak' => 'sk',
'slovenian' => 'sl',
'soga' => 'xog',
'sogdien' => 'sog',
'somali' => 'so',
'songhai' => 'son',
'soninke' => 'snk',
'sorbianlanguage' => 'wen',
'southamericanindianlanguage' => 'sai',
'southernaltai' => 'alt',
'southernsami' => 'sma',
'southernsotho' => 'st',
'southndebele' => 'nr',
'spanish' => 'es',
'sranantongo' => 'srn',
'sukuma' => 'suk',
'sumerian' => 'sux',
'sundanese' => 'su',
'susu' => 'sus',
'swahili' => 'sw',
'swati' => 'ss',
'swedish' => 'sv',
'swissfrench' => 'fr_ch',
'swissgerman' => 'gsw',
'swisshighgerman' => 'de_ch',
'syriac' => 'syr',
'tachelhit' => 'shi',
'tagalog' => 'tl',
'tahitian' => 'ty',
'tailanguage' => 'tai',
'taita' => 'dav',
'tajik' => 'tg',
'tamashek' => 'tmh',
'tamil' => 'ta',
'taroko' => 'trv',
'tasawaq' => 'twq',
'tatar' => 'tt',
'telugu' => 'te',
'tereno' => 'ter',
'teso' => 'teo',
'tetum' => 'tet',
'thai' => 'th',
'tibetan' => 'bo',
'tigre' => 'tig',
'tigrinya' => 'ti',
'timne' => 'tem',
'tiv' => 'tiv',
'tlingit' => 'tli',
'tokelau' => 'tkl',
'tokpisin' => 'tpi',
'tonga' => 'to',
'tsimshian' => 'tsi',
'tsonga' => 'ts',
'tswana' => 'tn',
'tumbuka' => 'tum',
'tupilanguage' => 'tup',
'turkish' => 'tr',
'turkmen' => 'tk',
'tuvalu' => 'tvl',
'tuvinian' => 'tyv',
'twi' => 'tw',
'tyap' => 'kcg',
"u\.s\.english" => 'en_us',
'udmurt' => 'udm',
'ugaritic' => 'uga',
'ukrainian' => 'uk',
'umbundu' => 'umb',
'unknownlanguage' => 'und',
'uppersorbian' => 'hsb',
'urdu' => 'ur',
'uyghur' => 'ug',
'uzbek' => 'uz',
'vai' => 'vai',
'venda' => 've',
'vietnamese' => 'vi',
'volapük' => 'vo',
'votic' => 'vot',
'vunjo' => 'vun',
'wakashanlanguage' => 'wak',
'walamo' => 'wal',
'walloon' => 'wa',
'walser' => 'wae',
'waray' => 'war',
'washo' => 'was',
'welsh' => 'cy',
'westernfrisian' => 'fy',
'wolof' => 'wo',
'xhosa' => 'xh',
'yangben' => 'yav',
'yao' => 'yao',
'yapese' => 'yap',
'yiddish' => 'yi',
'yoruba' => 'yo',
'yupiklanguage' => 'ypk',
'zande' => 'znd',
'zapotec' => 'zap',
'zarma' => 'dje',
'zaza' => 'zza',
'zenaga' => 'zen',
'zhuang' => 'za',
'zulu' => 'zu',
'zuni' => 'zun',
);
1;
} # --- END Cpanel/CPAN/Locales/DB/Language/en.pm
package main;
# cpanel - updatenow Copyright(c) 2015 cPanel, Inc.
# 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.
unshift @INC, q{/usr/local/cpanel};
# 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;
# dynamic definition of the INIT block
eval "INIT { exit(0); }";
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 );
}
}
# use Cpanel::CleanINC ();
# use Cpanel::Update::Now;
# use Cpanel::CPAN::Locales::DB::Territory::en (); #preload for perlstatic
# use Cpanel::CPAN::Locales::DB::Language::en (); #preload for perlstatic
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;