#!/bin/bash ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # # # Plesk script # #default values product_default_conf() { PRODUCT_ROOT_D=/opt/psa PRODUCT_RC_D=/etc/init.d PRODUCT_ETC_D=/opt/psa/etc PLESK_LIBEXEC_DIR=/usr/lib/plesk-9.0 HTTPD_VHOSTS_D=/var/www/vhosts HTTPD_CONF_D=/etc/apache2 HTTPD_INCLUDE_D=/etc/apache2/conf-enabled HTTPD_BIN=/usr/sbin/apache2 HTTPD_LOG_D=/var/log/apache2 HTTPD_SERVICE=apache2 QMAIL_ROOT_D=/var/qmail PLESK_MAILNAMES_D=/var/qmail/mailnames RBLSMTPD=/usr/sbin/rblsmtpd NAMED_RUN_ROOT_D=/var/named/run-root WEB_STAT=/usr/bin/webalizer MYSQL_VAR_D=/var/lib/mysql MYSQL_BIN_D=/usr/bin MYSQL_SOCKET=/var/run/mysqld/mysqld.sock PGSQL_DATA_D=/var/lib/postgresql/16/main PGSQL_CONF_D=/etc/postgresql/16/main PGSQL_BIN_D=/usr/lib/postgresql/16/bin DUMP_D=/var/lib/psa/dumps DUMP_TMP_D=/tmp MAILMAN_ROOT_D=/usr/lib/mailman MAILMAN_VAR_D=/var/lib/mailman PYTHON_BIN=/usr/bin/python2 GPG_BIN=/usr/bin/gpg TAR_BIN=/usr/lib/plesk-9.0/sw-tar AWSTATS_ETC_D=/etc/awstats AWSTATS_BIN_D=/usr/lib/cgi-bin AWSTATS_TOOLS_D=/usr/share/awstats/tools AWSTATS_DOC_D=/usr/share/awstats OPENSSL_BIN=/usr/bin/openssl LIB_SSL_PATH=/lib/libssl.so LIB_CRYPTO_PATH=/lib/libcrypto.so CLIENT_PHP_BIN=/opt/psa/bin/php-cli SNI_SUPPORT=true APS_DB_DRIVER_LIBRARY=/usr/lib/x86_64-linux-gnu/sw/libmysqlserver.so.2.0 SA_MAX_MAIL_SIZE=256000 } # db_test test_query awk_script # Runs test_query and processes it with awk_script. If the output is # not empty, return 0, otherwise return 1. Hint: supply '1' for # awk_script to test just for the presence of any output. db_test() { local any_db= eval `sh_get_args '--any-db) any_db=yes;;'` local test_query="$1" local awk_script="$2" local output if [ -n "$any_db" ]; then output="`mysql_raw_anydb -e \"$test_query\" 2>>\"$product_log\"`" else output="`mysql_raw -e \"$test_query\" 2>>\"$product_log\"`" fi local status=$? if [ "$status" -ne 0 ]; then p_echo "$output" die "run the following SQL query: $1" fi echo -n "$output" | awk -F '\t' -- "$awk_script" | test `wc -l` -ne 0 } # db_do [--inten ] query # Runs query. If it fails, die # the inten string describes the query reason (to make finding the bug simpler) db_do() { local desc="execute SQL query" eval `sh_get_args '--inten) desc=" (to $2)"; shift;;'` if [ "$db_fix_check_stage" = "yes" ]; then return fi local query="$1" dbclient_invoke -e "$query" >>"$product_log" 2>&1 || die "$desc, the query was: $query" } # db_select # runs via mysql_raw # writes output to db_select_output # if query fails, output errors and return 1 db_select() { local desc="execute SQL query" local query="$1" local output output="`mysql_raw -e \"$query\" 2>>\"$product_log\"`" local status="$?" if [ "$status" -ne "0" ]; then p_echo "$output" die "run the following SQL query: $query" fi db_select_output="$output" return 0 } db_drop_user() { # Drops all entries for given user name local user="$1" local mysql_db_name="mysql" db_select "(SELECT DISTINCT Host FROM user WHERE User = '$user') UNION (SELECT DISTINCT Host FROM db WHERE User = '$user') UNION (SELECT DISTINCT Host FROM tables_priv WHERE User = '$user') UNION (SELECT DISTINCT Host FROM columns_priv WHERE User = '$user') UNION (SELECT DISTINCT Host FROM procs_priv WHERE User = '$user') ORDER BY Host" [ -n "$db_select_output" ] || return 0 for host in $db_select_output; do db_do "DROP USER '$user'@'$host'" done db_do "FLUSH PRIVILEGES" } is_remote_db_feature_enabled() { [ -s "/etc/psa/private/dsn.ini" ] } get_dsn() { local section="$1" local param="$2" ! is_remote_db_feature_enabled || get_ini_conf_var "/etc/psa/private/dsn.ini" "$section" "$param" } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh # Usage: pleskrc pleskrc() { [ 2 -le $# ] || die "Not enough arguments" local service_name=${1//[-.@]/_} local action=$2 local ret=0 local inten shift shift # Now check redefined functions if test "$machine" = "linux" && is_function "${service_name}_${action}_${machine}_${linux_distr}"; then "${service_name}_${action}_${machine}_${linux_distr}" "$@" return $? elif is_function "${service_name}_${action}_${machine}"; then "${service_name}_${action}_${machine}" "$@" return $? elif is_function "${service_name}_${action}"; then "${service_name}_${action}" "$@" return $? fi # Not redefined - call default action eval "service=\$${service_name}_service" [ -n "$service" ] || die "$action $service_name service (Empty service name for '$service_name')" if [ "$action" = "name" ]; then echo "${service}.service" return 0 fi inten="$action service $service" pleskrc_is_failure_for_action_ok "$action" || echo_try "$inten" if [ -x "/bin/systemctl" -a "$do_upgrade" = "1" -a ! -f "/var/lock/parallels-panel-bootstrapper-running.lock" -a -z "$SYSTEMD_DAEMON_RELOADED" ]; then # reload systemd units if requested from an upgrade package script - in case a unit was changed /bin/systemctl daemon-reload SYSTEMD_DAEMON_RELOADED="yes" fi service_ctl "$action" "$service" "$service_name" ret="$?" pleskrc_is_failure_for_action_ok "$action" || { if [ "$ret" -eq 0 ]; then suc else if [ -x "/bin/systemctl" ]; then p_echo "`/bin/systemctl -l status \"${service}.service\" | awk 'BEGIN {s=0} s==1 {s=2} /^$/ {s=1} s==2 {print}'`" fi warn "$inten failed" fi } return $ret } pleskrc_is_failure_for_action_ok() { local action="$1" case "$action" in status|exists|is-active|is-enabled|is-failed) return 0 ;; esac return 1 } # NOTE: # Function service_ctl is just helper for pleskrc(). # Do not call it directly, use pleskrc()!!! service_ctl() { local action=$1 local service=$2 local service_name=$3 if [ "$action" != "exists" ]; then _service_exec $service exists if [ "$?" != "0" ]; then p_echo "attempt to ${inten} - service doesn't exist (missing unit file or not executable control script)" return 1 fi fi case "$action" in start) pleskrc "$service_name" status || _service_exec "$service" "$action" ;; stop) ! pleskrc "$service_name" status || _service_exec "$service" "$action" ;; restart) if pleskrc "$service_name" status; then _service_exec "$service" "$action" else _service_exec "$service" start fi ;; reload) ! pleskrc "$service_name" status || _service_exec "$service" "$action" ;; status) _service_exec "$service" status ;; try-restart) if [ -x "/bin/systemctl" ]; then _service_exec "$service" "$action" else ! pleskrc "$service_name" status || _service_exec "$service" "restart" fi ;; try-reload) ! pleskrc "$service_name" status || _service_exec "$service" "reload" ;; reload-or-restart) if [ -x "/bin/systemctl" ]; then _service_exec "$service" "$action" elif pleskrc "$service_name" status; then _service_exec "$service" "reload" else _service_exec "$service" "start" fi ;; *) _service_exec "$service" "$action" ;; esac >> "$product_log" } _service_exec() { # Keep in sync with pylibplesk/plesk_service.py local service=$1 local action=$2 local action_cmd local sysvinit_service="/etc/init.d/$service" if [ -x "/bin/systemctl" ]; then case "${action}" in exists) if /bin/systemctl cat "$service.service" >/dev/null 2>&1; then return 0 # systemd unit elif [ -f "/lib/systemd/system/$service.service" ]; then /bin/systemctl daemon-reload return 0 # systemd unit which exists but was changed and has not been reloaded before elif [ -x "$sysvinit_service" ]; then return 0 # sysvinit compat fi return 1 # not found ;; status) action="is-active" ;; reload|graceful) action='reload-or-try-restart' ;; esac /bin/systemctl "$action" "${service}.service" else warn "Cannot $action $service on this system: no executable /bin/systemctl" return 1 fi } is_function() { local type_output=$(type -t "$1") test "X${type_output}" = "Xfunction" } # echo message to product log, also to console in debug mode p_echo() { if [ -n "$product_log" ] ; then echo "$@" >> "$product_log" 2>&1 fi if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then echo "$@" >&2 fi } # same as p_echo, but without new line pnnl_echo() { p_echo -n "$@" } int_err() { report_problem "internal" "Internal error: $@" exit 1 } p_see_product_log() { log_is_in_dev "${product_log}" || printf " (see log file: ${product_log})" >&2 } die() { report_problem "fatal" "ERROR while trying to $@" printf "Check the error reason" >&2 p_see_product_log echo ", fix and try again" >&2 selinux_close exit 1 } warn() { local inten="$1" if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ]; then p_echo p_echo "WARNING!" pnnl_echo "Some problems are found during $inten" p_see_product_log p_echo p_echo "Continue..." p_echo fi report_problem "warning" "Warning: $inten" } echo_try() { msg="$*" pnnl_echo " Trying to $msg... " } suc() { p_echo "done" } write_structured_report() { # Write json error report into file $PLESK_INSTALLER_ERROR_REPORT if specified. # @params are tags in format "key=value" # Report body (human readable information) is read from stdin. local report_file="$PLESK_INSTALLER_ERROR_REPORT" [ -n "$report_file" ] || return 0 local python_bin= for bin in "/opt/psa/bin/python" "/usr/local/psa/bin/python" "/usr/bin/python2" "/usr/libexec/platform-python" "/usr/bin/python3"; do if [ -x "$bin" ]; then python_bin="$bin" break fi done if [ ! -x "$python_bin" ]; then p_echo "Cannot write structured error report: python interpreter not found." return 1 fi "$python_bin" -c 'import sys, json report_file = sys.argv[1] error = sys.stdin.read() data = { "error": error, } for tag in sys.argv[2:]: k, v = tag.split("=", 1) data[k] = v with open(report_file, "a") as f: json.dump(data, f) f.write("\n") ' "$report_file" "date=$(date --utc --iso-8601=ns)" "$@" } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. reexec_with_clean_env() { # Usage: call this function as 'reexec_with_clean_env "$@"' at the start of a script. # Don't use with scripts that require sensitive environment variables. # Don't put the call under any input/output redirection. # Purpose: make sure the script is executed with a sane environment. local lc="`get_default_locale`" export LANG="$lc" LC_MESSAGES="$lc" LC_ALL="$lc" export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin umask 022 PLESK_SCRIPT_COMMAND_LINE="$0 $*" [ -z "$PLESK_INSTALLER_ENV_CLEANED" ] || { unset PLESK_INSTALLER_ENV_CLEANED; return 0; } [ -n "$BASH" ] || exec /bin/bash "$0" "$@" # N.B.: the following code requires Bash. On Dash it would cause syntax error upon parse w/o eval. eval ' local extra_vars=() # list of variables to preserve for var in "${!PLESK_@}"; do # enumerate all PLESK_* variables extra_vars+=("$var=${!var}") done extra_vars+=("PLESK_INSTALLER_ENV_CLEANED=1") # Exec self with clean env except for extra_vars, shell opts, and arguments. exec /usr/bin/env -i "${extra_vars[@]}" /bin/bash ${-:+-$-} "$0" "$@" || { echo "Failed to reexec self ($0) with clean environment" >&2 exit 91 # Just some relatively unique error code } ' } get_default_locale() { # Note that CentOS 7 typically doesn't have C.UTF-8 for lc in "C.UTF-8" "en_US.UTF-8" "C"; do if [ -z "`LC_ALL=$lc locale 2>&1 >/dev/null`" ]; then echo "$lc" return 0 fi done echo "C" } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh mk_backup() { local target dup opts target="$1" dup="$2" opts="$3" if [ -L "$target" ]; then rm "$target" elif [ -$opts "$target" ]; then if [ ! -$opts "$target.$product_suffo" ]; then case "$dup" in mv) mv -f $target $target.$product_suffo || die "mv -f $target $target.$product_suffo" ;; cp) cp -fp $target $target.$product_suffo || die "cp -fp $target $target.$product_suffo" ;; *) p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'" die "mk_backup" ;; esac else case "$dup" in mv) mv -f $target $target.$product_suff || die "mv -f $target $target.$product_suff" ;; cp) cp -fp $target $target.$product_suff || die "cp -fp $target $target.$product_suff" ;; *) p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'" die "mk_backup" ;; esac fi else case "$opts" in f|d) ;; *) p_echo " mk_backup: wrong option -- must be 'f' or 'd'" die "mk_backup" ;; esac fi } # accumulates chown and chmod set_ac() { local u_owner g_owner perms node u_owner="$1" g_owner="$2" perms="$3" node="$4" # A very small optimization - replacing of two execs by one, # it works only if the following conditions are observed: # - u_owner is username (not UID); # - g_owner is group (not GID); # - perms is in octal mode. # If some conditions aren't observed, # optimization doesn't work, # but it doesn't break function [ "$(stat -c '%U:%G 0%a' $node)" != "$u_owner:$g_owner $perms" ] || return 0 chown $u_owner:$g_owner $node || die "chown $u_owner:$g_owner $node" chmod $perms $node || die "chmod $perms $node" } detect_vz() { [ -z "$PLESK_VZ_RESULT" ] || return $PLESK_VZ_RESULT PLESK_VZ_RESULT=1 PLESK_VZ=0 PLESK_VE_HW_NODE=0 PLESK_VZ_TYPE= local issue_file="/etc/issue" local vzcheck_file="/proc/self/status" [ -f "$vzcheck_file" ] || return 1 local env_id=`sed -ne 's|^envID\:[[:space:]]*\([[:digit:]]\+\)$|\1|p' "$vzcheck_file"` [ -n "$env_id" ] || return 1 if [ "$env_id" = "0" ]; then # Either VZ/OpenVZ HW node or unjailed CloudLinux PLESK_VE_HW_NODE=1 return 1 fi if grep -q "CloudLinux" "$issue_file" >/dev/null 2>&1 ; then return 1 fi if [ -f "/proc/vz/veredir" ]; then PLESK_VZ_TYPE="vz" elif [ -d "/proc/vz" ]; then PLESK_VZ_TYPE="openvz" fi PLESK_VZ=1 PLESK_VZ_RESULT=0 return 0 } # detects lxc and docker containers detect_lxc() { [ -z "$PLESK_LXC_RESULT" ] || return $PLESK_LXC_RESULT PLESK_LXC_RESULT=1 PLESK_LXC=0 if { [ -f /proc/1/cgroup ] && grep -q 'docker\|lxc' /proc/1/cgroup; } || \ { [ -f /proc/1/environ ] && cat /proc/1/environ | tr \\0 \\n | grep -q "container=lxc"; }; then PLESK_LXC_RESULT=0 PLESK_LXC=1 fi return "$PLESK_LXC_RESULT" } sh_get_args() { echo 'while true; do case "$1" in '"$1"'*) break;; esac; shift; done' } get_narg() { shift $1 2>/dev/null || return 0 echo $1 } get_random_string() { local str_length="$1" local str_symbols="$2" if [ -x "$PRODUCT_ROOT_D/admin/sbin/random_str" -a -z "$str_symbols" ]; then "$PRODUCT_ROOT_D/admin/sbin/random_str" "$str_length" else # random_str utility may be unavailable in pre phase if [ -z "$str_length" ]; then str_length="14" fi if [ -z "$str_symbols" ]; then str_symbols="A-Za-z0-9_" fi < /dev/urandom tr -dc "$str_symbols" 2>/dev/null | head -c "$str_length" 2>/dev/null fi } sequence() { if type seq >/dev/null 2>&1; then seq $* elif type jot >/dev/null 2>&1; then jot $* else die "Unable to find seq or jot command" fi } get_ini_conf_var() { local conf="$1" local section="$2" local param="$3" [ -n "$conf" -a -n "$param" ] || die "get_ini_conf_var(): required parameters missing" local section_empty=0 [ -n "$section" ] || section_empty=1 perl -n -e 'BEGIN { $insect='$section_empty' } next if (/^\s*;/); $insect=0 if (/^\s*\[.*\]/); $insect=1 if (/^\s*\['$section'\]/); $val = $2, $val =~ s/\s+$//, print $val . "\n" if ($insect && /^\s*('$param')\s*=\s*([^;\n]*)(;.*)?$/);' $conf | head -n 1 } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. #-*- vim:syntax=sh product_log_name_ex() { local aux_descr="$1" local action="${CUSTOM_LOG_ACTION_NAME-installation}" if [ -n "$aux_descr" ]; then aux_descr="_${aux_descr}" fi if [ -n "$CUSTOM_LOG_NAME" ]; then echo "${CUSTOM_LOG_NAME}${action:+_$action}${aux_descr}.log" else get_product_versions echo "plesk_${product_this_version}${action:+_$action}${aux_descr}.log" fi } product_log_name() { product_log_name_ex } product_problems_log_name() { product_log_name_ex "problems" } problems_log_tail() { [ -f "$product_problems_log" ] || return 0 { tac "$product_problems_log" | awk '/^START/ { exit } { print }' | tac } 2>/dev/null } product_log_tail() { [ -f "$product_log" ] || return 0 { tac "$product_log" | awk '/^START/ { exit } { print }' | tac } 2>/dev/null } product_and_problems_log_tail() { product_log_tail [ "$product_log" = "$product_problems_log" ] || problems_log_tail } set_log_action_name() { CUSTOM_LOG_ACTION_NAME="$1" } mktemp_log() { local logname="$1" local dir="$2" if [ "${logname:0:1}" != "/" ]; then logname="$dir/$logname" fi dir="`dirname $logname`" if [ ! -d "$dir" ]; then mkdir -p "$dir" || { echo "Unable to create log directory : $dir"; exit 1; } if [ "$EUID" -eq "0" ]; then set_ac root root 0700 "$dir" fi fi if [ "${logname%XXX}" != "$logname" ]; then mktemp "$logname" else echo "$logname" fi } log_is_in_dev() { test "${1:0:5}" = "/dev/" } start_writing_logfile() { local logfile="$1" local title="$2" ! log_is_in_dev "$logfile" || return 0 echo "START $title" >> "$logfile" || { echo "Cannot write installation log $logfile" >&2; exit 1; } [ "$EUID" -ne "0" ] || set_ac root root 0600 "$logfile" } log_start() { true product_log_name product_problems_log_name mktemp_log local title="$1" local custom_log="$2" local custom_problems_log="$3" local product_log_dir="/var/log/plesk/install" product_log="$product_log_dir/`product_log_name`" product_problems_log="$product_log_dir/`product_problems_log_name`" problems_occured=0 # init product log [ ! -n "$custom_log" ] || product_log="$custom_log" product_log=`mktemp_log "$product_log" "$product_log_dir"` # init problems log if [ -n "$custom_problems_log" ]; then product_problems_log=`mktemp_log "$custom_problems_log" "$product_log_dir"` elif [ -n "$custom_log" ]; then product_problems_log="$product_log" else product_problems_log=`mktemp_log "$product_problems_log" "$product_log_dir"` fi # write starting message into logs start_writing_logfile "$product_log" "$title" if [ "$product_log" != "$product_problems_log" ]; then start_writing_logfile "$product_problems_log" "$title" fi is_function profiler_setup && profiler_setup "$title" || : } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. construct_report_template() { local severity="${1:-error}" local summary="$2" local update_ticket="`get_update_ticket`" set_error_report_source set_error_report_component set_error_report_params set_error_report_environment true construct_report_code construct_report_debug construct_report_message cat <<-EOL $report_source $severity `date --iso-8601=seconds` $report_component /] ]>/g'`]]> `construct_report_message | base64` $report_params `construct_report_code | base64` `construct_report_debug | base64` $report_environment $update_ticket EOL } construct_report_code() { local call_level=${1:-5} local func_level=$[call_level - 1] local lineno_func=${BASH_LINENO[ $func_level ]} local script_name=${BASH_SOURCE[ $[func_level + 1] ]} echo "# Call of ${FUNCNAME[$func_level]}() from ${FUNCNAME[$[func_level + 1]]}() at `readlink -m $script_name`:${BASH_LINENO[$func_level]}" head -n $[lineno_func + 4] "$script_name" 2>/dev/null | tail -n 8 } construct_report_debug() { local call_level=${1:-5} call_level=$[call_level-1] # Generate calls stack trace. for i in `seq $call_level ${#FUNCNAME[@]}`; do [ "${FUNCNAME[$i]}" != "main" ] || break local func_call="`sed -n -e "${BASH_LINENO[$i]}p" "${BASH_SOURCE[$[i+1]]}" 2>/dev/null | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'`" [ -n "$func_call" -a -z "${func_call##*${FUNCNAME[$i]}*}" ] || func_call="${FUNCNAME[$i]}" echo "#$[i - $call_level] `readlink -m ${BASH_SOURCE[$[i+1]]}`(${BASH_LINENO[$i]}): $func_call" done } construct_report_message() { product_and_problems_log_tail echo "" if [ -n "$report_context" ]; then echo "Context: $report_context" echo "" fi if [ -n "$RP_LOADED_PATCHES" ]; then echo "Loaded runtime patches: $RP_LOADED_PATCHES" echo "" fi } # Construct report to send it to our errors tracker construct_report() { local severity="${1:-error}" local summary="$2" [ -n "$summary" ] || int_err "Unable to send error report. Some parameters are not defined." set_error_report_source get_product_versions construct_report_template "$severity" "$summary" \ | $PRODUCT_ROOT_D/admin/bin/send-error-report --version "$product_this_version" $report_source >/dev/null 2>&1 } # Use this function to report failed actions. # Typical report should contain # - reason or problem description (example: file copying failed) # - how to resolve or investigate problem (example: check file permissions, free disk space) # - how to re-run action (example: perform specific command, restart bootstrapper script, run installation again) report_problem() { local severity="${1:-error}" # Get first string of error as a summary of report shift local summary="$1" [ -n "$product_problems_log" ] || product_problems_log="/dev/stderr" p_echo if [ "0$problems_occured" -eq 0 ]; then echo "***** $process problem report *****" >> "$product_problems_log" 2>&1 fi for problem_message in "$@"; do p_echo "$problem_message" if [ "$product_log" != "$product_problems_log" ]; then echo "$problem_message" >> "$product_problems_log" 2>&1 fi done p_echo construct_report "$severity" "$summary" [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ] || \ product_log_tail problems_occured=1 } set_error_report_context() { report_context="$*" } set_error_report_source() { [ -z "$1" ] || report_source="$1" [ -n "$report_source" ] || { if [ -n "$PACKAGE_ID" -o -n "$PACKAGE_ACTION" -o -n "$PACKAGE_NAME" -o -n "$PACKAGE_VERSION" ]; then report_source="install" else report_source="backend" fi } } set_error_report_component() { local component="$1" if [ "$report_source" = "install" ]; then [ -n "$report_component" ] || report_component="$PACKAGE_ID" return 0 fi [ -z "$component" ] || report_component="$1" [ -n "$report_component" ] || report_component="`basename $0`" } set_error_report_params() { if [ "$report_source" = "install" ]; then [ -n "$report_params" ] || report_params="`echo "$PACKAGE_ACTION of $PACKAGE_NAME $PACKAGE_VERSION" | base64`" return 0 fi [ -z "$*" ] || report_params="`echo "$*" | base64`" [ -n "$report_params" ] || report_params="`echo "$PLESK_SCRIPT_COMMAND_LINE" | base64`" } detect_virtualization() { detect_vz detect_lxc local is_docker="`[ -f "/.dockerenv" ] && echo yes || :`" local systemd_detect_virt_ct="`/usr/bin/systemd-detect-virt -c 2>/dev/null | grep -v '^none$' || :`" local systemd_detect_virt_vm="`/usr/bin/systemd-detect-virt -v 2>/dev/null | grep -v '^none$' || :`" local virt_what="`/usr/sbin/virt-what 2>/dev/null | xargs || :`" if [ -n "$is_docker" ]; then echo "docker $virt_what" elif [ "$PLESK_VZ" = "1" ]; then echo "${PLESK_VZ_TYPE:-virtuozzo}" elif [ "$PLESK_LXC" = "1" ]; then echo "lxc $virt_what" elif [ -n "$systemd_detect_virt_ct" ]; then echo "$systemd_detect_virt_ct $systemd_detect_virt_vm" elif [ -n "$virt_what" ]; then echo "$virt_what" elif [ -n "$systemd_detect_virt_vm" ]; then echo "$systemd_detect_virt_vm" fi } default_error_report_environment() { local virtualization="`detect_virtualization`" if [ -n "$virtualization" ]; then echo "virtualization: $virtualization" fi } set_error_report_environment() { [ -z "$*" ] || report_environment="`echo "$*" | base64`" [ -n "$report_environment" ] || report_environment="`default_error_report_environment | base64`" } get_update_ticket() { [ -r $PRODUCT_ROOT_D/var/update_ticket ] && cat $PRODUCT_ROOT_D/var/update_ticket | awk '{$1=$1};1' } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh initial_conf() { PRODNAME="psa" PRODUCT_NAME="psa" product=${PRODNAME} PRODUCT_FULL_NAME="Plesk" product_etc="/etc/${PRODNAME}" prod_conf_t="/etc/psa/psa.conf" support_contact="https://support.plesk.com/" conceived_os_vendor=Ubuntu conceived_os_version="24.04" clients_group="psacln" clients_GID="10001" services_group="psaserv" services_GID="10003" product_suff="saved_by_${product}".`date "+%m.%d;%H:%M"` product_suffo="saved_by_${product}" # plesk default password PRODUCT_DEFAULT_PASSWORD="setup" } get_my_cnf_param() { local r= local my_cnf find_my_cnf "non-fatal" && \ r=`perl -e '$p="'"$1"'"; undef $/; $_=<>; s/#.*$//gm; /\[mysqld\](.*?)\[/sg; $_=substr($1, rindex $1,"$p") and /$p\s*=(.*)/m and print $1 ' ${my_cnf}` echo $r } get_mysql_socket() { # Marked as local as it's not used anywhere else now. local mysql_socket="/var/run/mysqld/mysqld.sock" local mysqlsock=`get_my_cnf_param socket` local MYSQL_SOCKETS="/var/lib/mysql/mysql.sock /tmp/mysql.sock /var/run/mysqld/mysqld.sock" for i in $mysql_socket $mysqlsock $MYSQL_SOCKETS; do if [ -S "$i" ]; then # This is used internally by mysqld_safe. Maybe this whole function isn't required nowadays. # See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-mysql-sock.html MYSQL_UNIX_PORT=$i export MYSQL_UNIX_PORT mysql_socket="$i" break fi done } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. #-*- vim:ft=sh register_service() { [ -n "$1" ] || die "register_service: service name not specified" local inten="register service $1" echo_try "$inten" { # sysvinit tools will not be called on systemd OS'es # since such OS'es are not explicitly supported enable_respawn_service "$1.service" # systemctl daemon-reload is performed implicitly unless --no-reload is passed /bin/systemctl enable --quiet "$1.service" local rs_db="$PRODUCT_ROOT_D/admin/sbin/register_service_db" [ ! -x "$rs_db" ] || "$rs_db" -a "$@" } suc } unregister_service() { [ -n "$1" ] || die "unregister_service: service name not specified" local inten="unregister service $1" echo_try $inten { local rs_db="$PRODUCT_ROOT_D/admin/sbin/register_service_db" [ ! -x "$rs_db" ] || "$rs_db" -r "$1" disable_respawn_service "$1.service" # systemctl daemon-reload is performed implicitly unless --no-reload is passed /bin/systemctl disable --quiet "$1.service" # purge sysvinit symlinks from /etc/rc.d which might be created by systemd-sysv-install # it spawns `update-rc.d defaults` or `chkconfig --add` if sysvinit script exists /usr/sbin/update-rc.d -f "$1" remove 1>/dev/null 2>&1 || : } >> $product_log 2>&1 suc } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. #-*- vim:ft=sh enable_respawn_service() { grep_q_recursive() { local val="$1" local file="$2" if [ -f "$file" ]; then ! grep -q "$val" "$file" || return 0 for f in `sed -n -e "s/^\.include\s//p" $file`; do ! grep_q_recursive "$val" "$f" || return 0 done fi return 1 } [ -n "$1" ] || die "enable_respawn_service: service name not specified" local inten="enable automatic respawn for service $1" echo_try "$inten" local service=$1 local main_unit=`systemctl show $service | sed -n -e "s/FragmentPath=//p"` local respawn_unit="/lib/systemd/system/$service.d/respawn.conf" local dropin_units=`systemctl show $service | sed -n -e "s/DropInPaths=//p" | sed "s|$respawn_unit||"` local ini="/opt/psa/admin/conf/panel.ini" local ini_section="systemd" local respawn [ ! -f "$ini" ] || respawn=`get_ini_conf_var "$ini" "$ini_section" respawn` if [ -z "${respawn/on/}" ]; then for unit in $main_unit $dropin_units; do ! grep_q_recursive "^Restart=" "$unit" || respawn="off" ! grep_q_recursive "^Type=oneshot" "$unit" || respawn="off" done fi rm -f "$respawn_unit" if [ -z "${respawn/on/}" ]; then mkdir -p "$(dirname $respawn_unit)" if [ -f "$ini" ]; then local restart=` get_ini_conf_var "$ini" "$ini_section" Service.Restart` local restartsec=` get_ini_conf_var "$ini" "$ini_section" Service.RestartSec` fi cat < "$respawn_unit" [Service] Restart=${restart:-"on-failure"} RestartSec=${restartsec:-"5"} EOT fi suc } disable_respawn_service() { [ -n "$1" ] || die "disable_respawn_service: service name not specified" local inten="disable automatic respawn for service $1" echo_try "$inten" local respawn_unit="/lib/systemd/system/$1.d/respawn.conf" rm -f "$respawn_unit" suc } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh selinux_is_active() { if [ -z "$SELINUX_ENFORCE" ]; then selinux_getenforce fi case "$SELINUX_ENFORCE" in Enforcing|Permissive) return 0;; *) return 1;; esac } selinux_support_is_installed() { # This function checks if Plesk SELinux support component is installed set_selinux_params [ -s "$selinux_module" ] } selinux_configuration_is_required() { # All public functions that modify SELinux state should check that this is true! selinux_is_active && selinux_support_is_installed } selinux_get_mount_dir() { unset SELINUX_MOUNT_DIR if awk '$2 == "/selinux"{exit(1)}' /proc/mounts && mkdir -p /selinux; then SELINUX_MOUNT_DIR=/selinux else SELINUX_MOUNT_DIR="`mktemp -d /tmp/selinuxXXXXXX`" fi >>"$product_log" 2>&1 } selinux_getenforce() { if [ "$1" = "--check" -a -n "$SELINUX_ENFORCE" ]; then return fi unset SELINUX_ENFORCE if ! ( command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled ); then SELINUX_ENFORCE=Disabled return fi if awk '$3 == "selinuxfs"{exit(1)}' /proc/mounts; then selinux_get_mount_dir mount -t selinuxfs none "$SELINUX_MOUNT_DIR" fi if ! command -v getenforce >/dev/null 2>&1; then SELINUX_ENFORCE=Disabled return fi SELINUX_ENFORCE="`getenforce`" if test $? -ne 0; then SELINUX_ENFORCE=Disabled return fi } selinux_close() { if [ -z "$SELINUX_ENFORCE" -o "$SELINUX_ENFORCE" = "Disabled" ]; then return fi setenforce "$SELINUX_ENFORCE" } selinux_relabel_dir() { selinux_configuration_is_required || return 0 if ! command -v restorecon >/dev/null 2>&1; then return fi local ret=0 if ! restorecon -i -R "$@" >>"$product_log" 2>&1; then warn "Error while setting SELinux types. Command was: restorecon -i -R $*" ret=1 fi [ -z "$do_repair" ] || return $ret } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh set_selinux_params() { selinux_module="$PRODUCT_ROOT_D/etc/plesk.pp" } get_product_versions() { # Don't use global variables set elsewhere in this code. Use substitutions if needed. local prod_root_d="/opt/psa" product_name="psa" if [ -z "$product_this_version" ]; then # 1. Try to fetch version from file created by bootstrapper (should be 3-component). product_this_version="`cat "/var/lock/plesk-target-version" 2>/dev/null`" # 2. Fallback to $PRODUCT_ROOT_D/version (should be 3-component). if [ -z "$product_this_version" -a -r "$prod_root_d/version" ]; then product_this_version="`awk '{ print $1 }' "$prod_root_d/version"`" fi # 3. Fallback to hardcoded version (2-component). This may cause some other code to fail. if [ -z "$product_this_version" ]; then product_this_version="18.0" echo "Unable to determine \$product_this_version, will use less precise value '$product_this_version'" >&2 fi fi product_version="$product_this_version" if [ -z "$product_prev_version" ]; then if [ -r "$prod_root_d/version.upg" ]; then product_prev_version=`awk '{ print $1 }' "$prod_root_d/version.upg"` elif [ -r "$prod_root_d/version" ]; then product_prev_version=`awk '{ print $1 }' "$prod_root_d/version"` else product_prev_version="$product_this_version" fi fi } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # -*- vim:ft=sh # MySQL server configuration # MySQL server configuration code writes error report into file $PLESK_INSTALLER_ERROR_REPORT # in json format with the following fields: # - "stage": "mysqlsetup" # - "level": "fatal" (installation cannot continue in case of mysql-related errors) # - "errtype": one of the following: # * "mysqlnomycnf" - my.cnf was not found. # List of my.cnf location is written into field "mycnffiles". # * "mysqlsetupfailed" - failed to establish connection to database. # * "mysqlcreateuserfailed" - failed to create 'admin' db user. # - "date": time of error occurance. # - "error": human readable error message. generate_mysql_credentials() { local args="$*" mysql_defaults=`echo $args | cut -d: -f 1` mysql_user=`echo $args | cut -d: -f 2` [ -n "$mysql_user" ] && mysql_user="--user=$mysql_user" mysql_passwd=`echo $args | cut -d: -f 3-` [ -n "$mysql_passwd" ] && mysql_passwd="$mysql_passwd" } # This function must be called *ONLY* for psa installation setup_admin_login() { true mysql_quote_string unset MYSQL_PWD local mysql_db_name="mysql" local sl local inten="define valid mysql credentials" local i echo_try "$inten" get_admin_passwd # --no-defaults:admin:$admin_passwd admin with pass # --no-defaults:root: root without pass # :root: root with pass in defaults # --no-defaults:admin: admin withiyt pass # --no-defaults:admin:$PRODUCT_DEFAULT_PASSWORD admin with default pass # :admin: admin with pass in defaults # :: user and pass in defaults # --defaults-file=/root/.my.cnf hspc defaults (paranoid) # for sl in `sequence 20`; do for i in "--no-defaults:admin:$admin_passwd" \ "--no-defaults:root:" \ ":root:" \ "--no-defaults:admin:" \ "--no-defaults:admin:$PRODUCT_DEFAULT_PASSWORD" \ ":admin:" \ "::" \ "--defaults-file=/root/.my.cnf::"; do generate_mysql_credentials "$i" if mysql_test_connection; then suc # create/Update admin superuser if [ "$mysql_user" = "--user=admin" ]; then reset_admin_passwd else echo "create user 'admin'@'localhost' identified by '`mysql_quote_string $admin_passwd`'; grant all privileges on *.* to 'admin'@'localhost' with grant option;flush privileges" | mysql_direct mysql || { if db_test "SELECT COUNT(*) FROM mysql.user WHERE User='admin' AND Host='localhost';" '$1!="0"'; then break else local msg="create 'admin' MySQL user. \ Plesk has been able to successfully connect to MySQL server, \ but assigning password and privileges to the new user failed. \ If you are installing Plesk on an already configured MySQL server with enabled \ password strength validation, you may need to disable it for the initial Plesk \ installation. After the installation is finished, you may re-enable it." echo "Failed to $msg" | write_structured_report 'stage=mysqlsetup' 'level=fatal' 'errtype=mysqlcreateuserfailed' || : die "$msg" fi } fi update_psa_shadow # backup private my.cnf if it contains password (vz/hspc related) rm -f /.my.cnf if grep -q '\s*password\s*=' /root/.my.cnf 2>/dev/null; then p_echo "WARNING: You current personal mysql config /root/.my.cnf has been renamed into /root/.my.cnf.bak" mv -f /root/.my.cnf /root/.my.cnf.bak fi set_mysql_auth return 0 fi done p_echo "One more attempt to connect" try_reset_mysql_auth sleep "$sl" done local msg="$inten. If you are installing Plesk on an already configured MySQL server, you need to specify the administrator's credentials to succeed with the installation. \ To do this, you need to create a file - /root/.my.cnf with the 'client' section where you need to provide user and its password \ (\"user = \$admin_name\" and \"password = \$admin_pass\"). \ After installation is finished, the file /root/.my.cnf will be renamed to /root/.my.cnf.bak" echo "Failed to $msg" | write_structured_report 'stage=mysqlsetup' 'level=fatal' 'errtype=mysqlsetupfailed' || : die "$msg" } update_psa_shadow() { echo "$admin_passwd" > $mysql_passwd_file || die chown $admin_user:$admin_group ${mysql_passwd_file} || die chmod 600 ${mysql_passwd_file} || die selinux_relabel_dir "$mysql_passwd_file" } set_mysql_auth() { # This function requires set_mysql_server_params and set_mysql_client_params (or set_mysqld_params) # to be called before local inten="set up mysql authentication" local dsn_plesk_host="`get_dsn plesk host`" local dsn_plesk_port="`get_dsn plesk port`" local dsn_plesk_username="`get_dsn plesk username`" local dsn_plesk_password="`get_dsn plesk password`" get_admin_passwd [ -n "$dsn_plesk_host" ] || pleskrc mysql start mysql_host="${dsn_plesk_host:+--host=$dsn_plesk_host}" mysql_port="${dsn_plesk_port:+--port=$dsn_plesk_port}" mysql_user="--user=${dsn_plesk_username:-admin}" mysql_passwd="${dsn_plesk_password:-$admin_passwd}" if find_my_cnf 'non-fatal'; then mysql_defaults="--defaults-file=$my_cnf" else mysql_defaults="--no-defaults" fi if [ -z "$PLESK_MYSQL_AUTH_SKIP_CONNECTION_CHECK" ]; then mysql_test_connection 10 || die "$inten" fi suc } get_admin_passwd() { [ -z "$admin_passwd" ] || return 0 if [ -f "$mysql_passwd_file" ]; then admin_passwd=`cat "$mysql_passwd_file"` return 0 fi admin_passwd=`get_random_string 1 'A-Z'` admin_passwd+=`get_random_string 1 'a-z'` admin_passwd+=`get_random_string 1 '0-9'` admin_passwd+=`get_random_string 1 '_%=+\-@<>:.,:'` admin_passwd+=`get_random_string 10 'A-Za-z0-9_%=+\-@<>:.,:'` admin_passwd=`printf "%s" "$admin_passwd" | fold -w 1 | shuf - | tr -d '\n'` [ -n "$admin_passwd" ] || admin_passwd="$PRODUCT_DEFAULT_PASSWORD" touch "$admin_password_needs_encryption_flag" } mysql_quote_string() { echo "$1" | perl -pe 's|\\|\\\\|g' } reset_admin_passwd() { true mysql_quote_string [ -n "$admin_passwd" ] || die "admin_passwd is not set yet" # I bet someone somewhere replaces 'localhost' with '%' (for weird automation purposes), so be nice echo "SET PASSWORD FOR 'admin'@'localhost' = PASSWORD('`mysql_quote_string $admin_passwd`')" | mysql_direct mysql || \ echo "SET PASSWORD FOR 'admin'@'%' = PASSWORD('`mysql_quote_string $admin_passwd`')" | mysql_direct mysql || \ echo "ALTER USER 'admin'@'localhost' IDENTIFIED BY '`mysql_quote_string $admin_passwd`')" | mysql_direct mysql || \ echo "ALTER USER 'admin'@'%' IDENTIFIED BY '`mysql_quote_string $admin_passwd`')" | mysql_direct mysql } mysql_test_connection() { inten="establish test connection" echo_try $inten attempts=${1:-1} for i in `sequence $attempts`; do echo "" | mysql_direct mysql >> "$product_log" 2>&1 if [ "$?" -eq "0" ]; then p_echo "connected" return 0 fi [ "$attempts" -eq "1" ] || sleep 1 done p_echo "failed" return 1 } configure_mysql_innodb() { local my_cnf="$1" if grep -q '^skip-innodb' "$my_cnf"; then sed -i -e '/^skip-innodb/ d' "$my_cnf" need_mysql_restart=yes fi } #bug #46837. Disable "LOAD DATA LOCAL INFILE" command. configure_mysql_infile() { local my_cnf="$1" local awk_script if ! (test -f $my_cnf && grep -q '^\[mysqld\]' "$my_cnf"); then echo "[mysqld]" >> $my_cnf echo "local-infile=0" >> $my_cnf need_mysql_restart=yes return fi awk_script='/^\[mysqld\]$/{print; print "local-infile=0"; next;} {print}' if ! grep -q '^local-infile' "$my_cnf"; then awk "$awk_script" "$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf" need_mysql_restart=yes fi } configure_mysql_address() { local my_cnf="$1" local address="$2" if ! grep -q "^bind-address\s*=\s*$address\s*$" "$my_cnf"; then sed -e "/^bind-address\s*=\s*/d" -i "$my_cnf" || \ die "remove 'bind-address' directive from '$my_cnf'" sed -e "s|^\(\[mysqld\].*\)|\1\nbind-address = $address|" -i "$my_cnf" || \ die "configure MySQL server via '$my_cnf' to listen on address $address" need_mysql_restart=yes fi } check_ipv6_network_available() { ping6 -c1 -q "::1" >/dev/null 2>&1 } configure_mysql_address_all() { local ipv6_supported_version="5.5.3" local current_version="`mysql_raw_anydb -e \"select version();\"`" local my_cnf="$1" local address="0.0.0.0" # if we cannot detect mysql-server version # use ipv4 only address if [ -n "$current_version" ]; then mysql_compare_versions "$current_version" "$ipv6_supported_version" if [ $? -ne 1 ] && check_ipv6_network_available; then address="::" fi # Before MariaDB 10.6.0 "::" implied listening additionally on IPv4 addresses like "*". From 10.6.0 onwards it refers to IPv6 stictly. mysql_compare_versions "$current_version" "10.6.0" if [ $? -ne 1 ] && check_ipv6_network_available; then address="*" fi fi configure_mysql_address "$my_cnf" "$address" } configure_mysql_address_local() { local ipv6_supported_version="5.5.3" local current_version="`mysql_raw_anydb -e \"select version();\"`" local my_cnf="$1" local address="127.0.0.1" # if we cannot detect mysql-server version # use ipv4 only address if [ -n "$current_version" ]; then mysql_compare_versions "$current_version" "$ipv6_supported_version" if [ $? -ne 1 ] && check_ipv6_network_available; then address="::ffff:127.0.0.1" fi # Before MariaDB 10.6.0 "::" implied listening additionally on IPv4 addresses like "*". From 10.6.0 onwards it refers to IPv6 stictly. mysql_compare_versions "$current_version" "10.6.0" if [ $? -ne 1 ]; then address="127.0.0.1" fi fi configure_mysql_address "$my_cnf" "$address" } configure_mysql_disable_old_passwords() { local my_cnf="$1" local awk_script='/^[[:space:]]*old_passwords/ { print "# Forced OLD_PASSWORD format is turned OFF by Plesk\n#" $0; next } { print }' if awk "$awk_script" "$my_cnf" > "$my_cnf.tmp" || die "edit $my_cnf"; then if diff -q "$my_cnf" "$my_cnf.tmp" 1>/dev/null ; then rm -f "$my_cnf.tmp" else mv "$my_cnf.tmp" "$my_cnf" || die "disable old_passwords in $my_cnf" need_mysql_restart=yes fi fi } configure_mysql_default_auth_plugin() { local my_cnf="$1" local mysql_db_name="mysql" db_select "SHOW VARIABLES LIKE 'default_authentication_plugin'" local default_auth_plugin=`get_narg 2 ${db_select_output}` if [ -z "$default_auth_plugin" -o "$default_auth_plugin" != "caching_sha2_password" ]; then p_echo "MySQL default authentication plugin is ok ($default_auth_plugin)" return fi # We need to also update admin password if it was set by incompatible with sw-engine plugin echo "ALTER USER 'admin'@'localhost' IDENTIFIED WITH mysql_native_password BY '`mysql_quote_string $admin_passwd`'" | mysql_direct mysql || die "execute SQL query to update 'admin' password" echo_try "switch MySQL default authentication from caching_sha2_password to mysql_native_password" if ! (test -f "$my_cnf" && grep -q '^\[mysqld\]' "$my_cnf"); then echo "[mysqld]" >> $my_cnf echo "default_authentication_plugin = mysql_native_password" >> $my_cnf suc need_mysql_restart=yes return fi local awk_script='/^\[mysqld\]$/{print; print "default_authentication_plugin = mysql_native_password"; next;} {print}' if ! grep -q '^default_authentication_plugin' "$my_cnf"; then awk "$awk_script" "$my_cnf" >"$my_cnf.tmp" && mv "$my_cnf.tmp" "$my_cnf" || die "edit $my_cnf" need_mysql_restart=yes fi suc } configure_mysql_no_strict_mode() { local my_cnf="$1" local mysql_db_name="mysql" db_select "SELECT @@""GLOBAL.sql_mode" local sql_mode="$db_select_output" [ -n "$sql_mode" ] || return 0 local ok_sql_mode="`echo "$sql_mode" | tr ',' '\n' | grep -E -v 'STRICT_TRANS_TABLES|STRICT_ALL_TABLES|NO_ZERO_DATE' | xargs | tr ' ' ','`" [ "$ok_sql_mode" != "$sql_mode" ] || return 0 sed -e "/^sql_mode.*=.*/d" -i "$my_cnf" || \ die "remove 'sql_mode' directive from '$my_cnf'" sed -e "s|^\(\[mysqld\].*\)|\1\nsql_mode=$ok_sql_mode|" -i "$my_cnf" || \ die "configure MySQL server via '$my_cnf' with no strict mode" need_mysql_restart=yes } configure_mysql_disable_password_checker() { local my_cnf="$1" local mysql_db_name="mysql" # Switch off MySQL 8+ password checking db_select "SHOW VARIABLES LIKE 'validate_password%'" if [ -z "$db_select_output" ]; then p_echo "builtin MySQL password checker is disabled" return fi local inten="switch off builtin MySQL password checker" echo_try "$inten" db_do --inten "$inten" "UNINSTALL COMPONENT 'file://component_validate_password'" suc } get_mysqldump_default_charset() { local dump_client="${MYSQL_BIN_D}/mysqldump" [ -f "$MYSQL_BIN_D/mariadb-dump" ] && dump_client="$MYSQL_BIN_D/mariadb-dump" env LC_ALL=C LANG=C "$dump_client" "$@" --help | awk '/default-character-set/{print $2}' | xargs } create_my_cnf_d() { [ -z "$my_cnf_d" ] || return 0 my_cnf_d="/etc/mysql/conf.d" [ -d "$my_cnf_d" ] || mkdir -p "$my_cnf_d" echo_try "configure and create MySQL conf.d $my_cnf_d" mk_backup "$my_cnf" cp f echo "!includedir $my_cnf_d" >> $my_cnf && suc need_mysql_restart=yes } configure_mysqldump_utf8mb4() { local inten="configure default charset for mysqldump to utf8mb4" local builtin_character_set=`get_mysqldump_default_charset --no-defaults` local configured_character_set=`get_mysqldump_default_charset --defaults-file="$my_cnf"` echo_try "$inten" if [ "$builtin_character_set" != "utf8" ]; then p_echo "not required: built-in character set is not utf8 ($builtin_character_set)." return 0 fi if [ "$configured_character_set" != "$builtin_character_set" ]; then p_echo "not required: configured character set ($configured_character_set) differs from built-in ($builtin_character_set)" return 0 fi if [ -z "$my_cnf_d" ]; then create_my_cnf_d fi local config="$my_cnf_d/plesk-utf8mb4.cnf" if [ -f "$config" ]; then p_echo "already configured in $config" return 0 fi cat < "$config" # Configure utf8mb4 default character set for mysqldump # If you don't need it, please comment out the lines below [mysqldump] default-character-set=utf8mb4 EOT suc } find_my_cnf() { local non_fatal="$1" local cnf_files="/etc/my.cnf /etc/mysql/my.cnf /var/db/mysql/my.cnf" for my_cnf in $cnf_files; do if [ -f ${my_cnf} ]; then break fi done [ -f "$my_cnf" -o -n "$non_fatal" ] || { local msg="find the MySQL server configuration file. \ If you use a third-party MySQL server build, make sure you do not use implicit default configuration \ and you have the MySQL configuration file in one of the following locations: $cnf_files" echo "Failed to $msg" | write_structured_report 'stage=mysqlsetup' 'level=fatal' 'errtype=mysqlnomycnf' "mycnffiles=$cnf_files" || : die "$msg" } [ -f "$my_cnf" ] || return 1 my_cnf_d=`awk '/^\s*!includedir\>/ {print $2}' "$my_cnf" | head -1` return 0 } run_configure_mysql_funcs() { local need_mysql_restart= local my_cnf= local my_cnf_d= find_my_cnf for func in "$@"; do eval "$func $my_cnf" done if [ -n "$need_mysql_restart" ]; then pleskrc mysql restart fi } mysql_install_init() { local with_managed="yes" [ "$1" != "--skip-managed" ] || with_managed= register_service "$mysql_service" run_configure_mysql_funcs \ configure_mysql_innodb \ configure_mysql_infile \ configure_mysql_disable_old_passwords \ setup_admin_login mysql_fix_remove_bad_users true configure_mysql_address_local run_configure_mysql_funcs \ ${with_managed:+configure_mysql_address_local} \ configure_mysql_no_strict_mode \ configure_mysql_default_auth_plugin \ configure_mysql_disable_password_checker \ configure_mysqldump_utf8mb4 \ } mysql_fix_remove_bad_users() { local mysql_db_name="mysql" db_do "drop database if exists test" db_drop_user '' # This removes the root user if possible. # On Debian > 8 and Ubuntu > 16.04 the debian-sys-maint user is no longer present/used # and got "replaced" with a root user, configured to be authenticated using the unix socket. # On RPM-based systems logrotate may rely on root, but failures are ignored before MariaDB 10.11. local needs_root= ! grep -E -q "^user\s*=\s*root\s*$" /etc/mysql/debian.cnf 2>/dev/null || needs_root="yes" ! grep -E -sq "^\s*($MYSQL_BIN_D/)?(mysqladmin|mariadb-admin)\>" \ /etc/logrotate.d/mysql /etc/logrotate.d/mysqld /etc/logrotate.d/mysql-server \ /etc/logrotate.d/mariadb 2>/dev/null || needs_root="yes" if [ -n "$needs_root" ]; then db_select "SELECT User FROM mysql.user WHERE User='root' AND Host='localhost'" if [ -z "$db_select_output" ]; then db_do "CREATE USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING 'invalid' OR unix_socket" db_do "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION" db_do "FLUSH PRIVILEGES" fi else db_drop_user 'root' fi } mysql_compare_versions() { local l_greater=2 local l_equal=0 local l_less=1 local lhs_major="`echo $1 | cut -d'.' -f1`" local lhs_minor="`echo $1 | cut -d'.' -f2`" local lhs_patch="`echo $1 | cut -d'.' -f3 | grep -o -e '^[0-9]\+'`" local rhs_major="`echo $2 | cut -d'.' -f1`" local rhs_minor="`echo $2 | cut -d'.' -f2`" local rhs_patch="`echo $2 | cut -d'.' -f3 | grep -o -e '^[0-9]\+'`" # TODO(galtukhov): rewrite string comparision as python one-liner if [ "$lhs_major" -gt "$rhs_major" ]; then return $l_greater elif [ "$lhs_major" -lt "$rhs_major" ]; then return $l_less else if [ "$lhs_minor" -gt "$rhs_minor" ]; then return $l_greater elif [ "$lhs_minor" -lt "$rhs_minor" ]; then return $l_less else if [ "$lhs_patch" -gt "$rhs_patch" ]; then return $l_greater elif [ "$lhs_patch" -lt "$rhs_patch" ]; then return $l_less else return $l_equal fi fi fi } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # -*- vim:ft=sh # mysql set_mysqld_params() { mysqld_user="mysql" mysqld_UID=3306 mysqld_group="mysql" mysqld_GID=3306 product_db_sql="$PRODUCT_BOOTSTRAPPER_DIR/db/${PRODNAME}_db.sql" admin_password_needs_encryption_flag="$PLESK_DB_DIR/.encrypt_admin_password.flag" set_mysql_server_params set_mysql_client_params } set_mysql_server_params() { get_mysql_socket if [ -n "/lib/systemd/system" -a -f "/lib/systemd/system/mariadb.service" ]; then mysql_service="mariadb" elif [ -n "/lib/systemd/system" -a -f "/lib/systemd/system/mysqld.service" ]; then # Percona server mysql_service="mysqld" elif [ -n "/lib/systemd/system" -a -f "/lib/systemd/system/mysql.service" ]; then # MySQL 8 installations on debian / ubuntu mysql_service="mysql" elif [ -x "${PRODUCT_RC_D}/mysql" ]; then mysql_service="mysql" elif [ -x "${PRODUCT_RC_D}/mysql.sh" ]; then mysql_service="mysql.sh" elif [ -x "${PRODUCT_RC_D}/mysqld" ]; then mysql_service="mysqld" elif [ -x "${PRODUCT_RC_D}/mysql" ]; then mysql_service="mysql" else die "detect MySQL service name" fi } set_mysql_client_params() { mysql_client="$MYSQL_BIN_D/mysql" [ -f "$MYSQL_BIN_D/mariadb" ] && mysql_client="$MYSQL_BIN_D/mariadb" # Override this variable as needed mysql_db_name="$PRODNAME" mysql_passwd_file="$product_etc/.${PRODNAME}.shadow" mysql_args="-N" mysql_args_raw="-Br" local dsn_plesk_dbname="`get_dsn plesk dbname`" [ -z "$dsn_plesk_dbname" ] || mysql_db_name="$dsn_plesk_dbname" } #Invoke mysql dbclient_invoke() { mysql_anydb -D$mysql_db_name "$@" } mysql_anydb() { ( export MYSQL_PWD="$mysql_passwd" $mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log" local status=$? if [ $status -gt 0 ]; then $mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args -D$mysql_db_name $mysql_args_raw -e "SHOW ENGINE innodb status" >>"$product_log" 2>&1 fi unset MYSQL_PWD return $status ) } # Invoke mysql without any wrapper or something else mysql_direct() { # a bit dirty but it works properly for passwords with spaces, quotes and double quotes: if [ -n "$mysql_passwd" ]; then ( export MYSQL_PWD="$mysql_passwd" $mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log" rc=$? unset MYSQL_PWD return $rc ) else $mysql_client $mysql_defaults $mysql_host $mysql_port $mysql_user $mysql_args "$@" 2>>"$product_log" fi } # Invoke mysql in raw mode mysql_raw() { dbclient_invoke $mysql_args_raw "$@" } mysql_raw_anydb() { mysql_anydb $mysql_args_raw "$@" } requires_configured_mysql() { # Initialize and configure local MySQL server if it is not usable yet. # This function is for use in components that require MySQL, particularly on SN. local reinitialize_mysql="$1" set_mysqld_params if is_remote_db_feature_enabled; then ! pleskrc mysql status || pleskrc mysql stop unregister_service "$mysql_service" set_mysql_auth [ -s "$mysql_passwd_file" ] || update_psa_shadow return 0 fi if [ ! -s "$mysql_passwd_file" -o -n "$reinitialize_mysql" ]; then mysql_install_init ${reinitialize_mysql:+--skip-managed} else set_mysql_auth fi } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # Get version of local mysql service get_local_mysqld_version() { PATH="$PATH:/usr/libexec:/libexec" mysqld -V 2>/dev/null| sed 's/.*Ver //' | awk '{print $1}' } # Reset mysqld authentication in case we are unable to guess password create_reset_mysql_auth_sql_file() { true mysql_quote_string ( umask 0027 local sql="`mktemp /tmp/plesk-reset-mysql-auth.XXXXXX.sql`" cat > "$sql" <<-EOT -- WARNING: each statement in this file MUST be on one line, no comments on statement lines. -- DB must be selected to create procedures. USE mysql; EOT local mysql_version=`get_local_mysqld_version` case "$mysql_version" in 8.*) cat >> "$sql" <<-EOT DROP USER IF EXISTS 'admin'@'localhost'; CREATE USER 'admin'@'localhost' IDENTIFIED BY '`mysql_quote_string "$admin_passwd"`'; GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION; EOT ;; *) cat >> "$sql" <<-EOT -- Remove password strength validation. CREATE PROCEDURE plesk_uninstall_validate_password() BEGIN IF EXISTS (SELECT * FROM mysql.plugin WHERE name = 'validate_password') THEN UNINSTALL PLUGIN validate_password; END IF; END; CALL plesk_uninstall_validate_password(); DROP PROCEDURE IF EXISTS plesk_uninstall_validate_password; -- Create or reset admin superuser. GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY '`mysql_quote_string "$admin_passwd"`' WITH GRANT OPTION; FLUSH PRIVILEGES; EOT ;; esac cat >> "$sql" <<-EOT -- Shut down mysqld. SHUTDOWN; EOT chgrp "$mysqld_group" "$sql" >&2 chmod 640 "$sql" >&2 echo "$sql" ) } try_reset_mysql_auth() { # Don't try this more than once. It won't succeed anyway. [ -z "$PLESK_INSTALLER_TRIED_MYSQL_AUTH_RESET" ] || return 0 PLESK_INSTALLER_TRIED_MYSQL_AUTH_RESET="yes" local inten="reset authentication for MySQL server" echo_try "$inten" pleskrc mysql stop get_admin_passwd # Run mysqld in "reset authentication" mode. p_echo "Starting mysqld in authentication reset mode." local init_sql="`create_reset_mysql_auth_sql_file`" PATH="$PATH:/usr/libexec:/libexec" mysqld --user "$mysqld_user" --init-file "$init_sql" >> "$product_log" 2>&1 & local pid="$!" # Normally the command above should stop by itself. Wait for it. local tries=60 i= pnnl_echo "Waiting for mysqld to stop ($tries seconds at most)" for i in `sequence $tries`; do kill -0 "$pid" 2>/dev/null || break pnnl_echo "." sleep 1 done pnnl_echo " " # If it didn't stop, likely error occurred before SHUTDOWN query. Request shutdown via signal. kill -s TERM "$pid" 2>/dev/null \ && p_echo "We had to send mysqld signal to shutdown. This likely means that authentication reset failed (see mysqld log for details, search for 'init_file')." \ || p_echo "Looks like mysqld stopped normally." # SIGTERM might not have been honored by mysqld, but I've seen no such behavior. pnnl_echo "Waiting for mysqld return code (if this hangs, try 'kill -9 $pid')... " wait "$pid" local rc="$?" if [ "$rc" -ne 0 ]; then p_echo "mysqld failed with code $rc, authentication reset failed (see mysqld log for details)." else suc fi rm -f "$init_sql" pleskrc mysql restart } ### Copyright 1999-2025. WebPros International GmbH. All rights reserved. # vim:ft=sh: usage() { cat >&2 <<-EOT Usage: $prog [OPTIONS] OPTIONS: --bind-address Configure MySQL server to listen only for local connections or for all connections --post-re-init Configure MySQL server after re-initialization EOT exit 2 } reexec_with_clean_env "$@" prog="`basename $0`" set_log_action_name "$prog" log_start "$prog" set_error_report_context "$prog" product_default_conf initial_conf configure_funcs_list= opt_post_re_init= ARGS=`getopt -o "" --longoptions help,bind-address:,post-re-init --name "$prog" -- "$@"` eval set -- "${ARGS}" while true; do case "$1" in --bind-address) if [ "$2" = "all" ]; then configure_funcs_list="$configure_funcs_list configure_mysql_address_all" elif [ "$2" = "local" ]; then configure_funcs_list="$configure_funcs_list configure_mysql_address_local" else echo "Unrecognized argument $2 for option $1" >&2 usage fi shift ;; --post-re-init) opt_post_re_init="yes" ;; --) shift break ;; --help) usage ;; *) echo "Unrecognized option: $1" >&2 usage ;; esac shift done [ -n "$configure_funcs_list" -o -n "$opt_post_re_init" ] || usage requires_configured_mysql ${opt_post_re_init:+--reinitialize-mysql} run_configure_mysql_funcs $configure_funcs_list