????

Your IP : 18.117.7.212


Current Path : /proc/329612/root/usr/share/cagefs/
Upload File :
Current File : //proc/329612/root/usr/share/cagefs/cagefs_ispmanager_lib.py

# -*- coding: utf-8 -*-
# ISP Manager function library
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions
#are met:
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#  * The names of its contributors may not be used to endorse or
#    promote products derived from this software without specific
#    prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#POSSIBILITY OF SUCH DAMAGE.
#

# Module functionality:
# Create php.ini files for DA PHP version selector
# Create symlink to user data directory
#

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import *
import os
import pwd
import shutil
import subprocess

import cagefslib
import cldetectlib as detect
import secureio
from cagefsctl import get_list_of_users, cagefs_is_enabled, save_dir_exists, get_exclude_user_list, get_min_uid, MIN_UID
from clcagefslib.io import read_file
from clcagefslib.selector.panel.isp import ispmanager_create_user_wrapper
from clcommon.utils import mod_makedirs


def install_ispmanager_directory_exclude():
    """
    Install exclude .cagefs folder from backup
    :return: None
    """
    # Only for ISP Manager
    detect.getCP()
    if not detect.is_ispmanager():
        return

    if detect.CP_VERSION.startswith('4'):
        # ISP Manager v4
        isp_command_list = ['/usr/local/ispmgr/sbin/mgrctl', 'backupplan']
        try:
            result = cagefslib.Execute(isp_command_list, check_return_code=False, exit_on_error=False).split('\n')
            for line in result:
                if line.find('id=') != -1:
                    plan_id = str(line.split('name=')[0].replace('id=', '').strip())
                    isp_command_list.extend(['.content.edit plid=' + plan_id, 'sok=ok', 'type=exclude',
                                                                    'module=file','filedata=.cagefs'])
                    cagefslib.Execute(isp_command_list, check_return_code=False, exit_on_error=False)
        except OSError as e:
            secureio.print_error('Failed to set exclude dir for ISPManager 4:', str(e))
    else:
        # ISP Manager v5
        if detect.ispmanager5_is_master():
            # ISP5 Master
            try:
                cagefs_exclude_is_found = False
                exclude_files_list = list()
                # Search .cagefs in excludes
                isp_command_list = ['/usr/local/mgr5/sbin/mgrctl', '-m', 'ispmgr', 'backup2.settings']
                result = cagefslib.Execute(isp_command_list, check_return_code=False, exit_on_error=False).split('\n')
                for line in result:
                    if line.startswith('exclude_files'):
                        # line as:
                        # exclude_files=data/.cagefs data/mod-tmp data/somedir
                        l_parts = line.strip().split('=')
                        if len(l_parts) != 2:
                            continue
                        # l_parts[1] as 'data/.cagefs data/mod-tmp data/somedir'
                        exclude_files_list = l_parts[1].split(' ')
                        # if .cagefs absent in exclude list, add it
                        for exclude_file in exclude_files_list:
                            if '.cagefs' in exclude_file:
                                cagefs_exclude_is_found = True
                                break
                        break
                if not cagefs_exclude_is_found:
                    # .cagefs not found in excludes, add it
                    add_line = ' '.join(exclude_files_list) + ' ' + 'data/.cagefs'
                    add_line = add_line.strip()
                    isp_command_list.extend(['exclude_files=%s' % add_line, 'sok=ok'])
                    cagefslib.Execute(isp_command_list, check_return_code=False, exit_on_error=False).split('\n')
            except (OSError, IOError,) as e:
                secureio.print_error('Failed to set exclude dir for ISPManager 5:', str(e))


def create_php_cgi_etc(filename, php_ini_path):
    if os.path.isfile(filename):
        # check file content
        content = read_file(filename)
        if content[0] == '#!/bin/bash\n':
            for line in content:
                parts = line.strip().split()
                if (len(parts) == 4) and (parts[0] == 'exec') and (parts[1] == '/usr/bin/php-cgi') and\
                                (parts[2] == '-c') and (parts[3] == php_ini_path):
                    return

    dirpath = os.path.dirname(filename)
    if not os.path.lexists(dirpath):
        mod_makedirs(dirpath, 0o755)

    f = open(filename, 'w')
    f.write('#!/bin/bash\n')
    f.write('exec /usr/bin/php-cgi -c ' + php_ini_path + '\n')
    f.close()
    # make it executable
    os.chmod(filename, 0o755)


# Call from cagefs
def configure_selector_for_ispmanager():
    # Only for ISP Manager v4.x
    detect.getCP()
    if not detect.is_ispmanager() or not detect.CP_VERSION.startswith('4'):
        return

    ISP_MANAGER_CONF_FILE = '/usr/local/ispmgr/etc/ispmgr.conf'
    if not os.path.isfile(ISP_MANAGER_CONF_FILE):
        return

    # 1. Read php.ini path from native conf
    cagefslib.read_native_conf()
    if not cagefslib.config_loaded:
        return
    content = cagefslib.orig_binaries
    php_ini_path = '/etc/php.ini'
    if 'php.ini' in content:
        php_ini_path = content['php.ini']

    # 2. Create /usr/local/bin/php-cgi-etc
    script_file = '/usr/local/bin/php-cgi-etc'
    create_php_cgi_etc(script_file, php_ini_path)

    # 3. Create in CageFs skeleton (/usr/share/cagefs-skeleton/usr/local/bin/php-cgi-etc)
    if os.path.isdir('/usr/share/cagefs-skeleton'):
        create_php_cgi_etc('/usr/share/cagefs-skeleton/usr/local/bin/php-cgi-etc', php_ini_path)

    # 4. Read /usr/local/ispmgr/etc/ispmgr.conf
    content = read_file(ISP_MANAGER_CONF_FILE)
    i = 0
    is_found = False
    old_path = ''
    for line in content:
        parts = line.strip().split()
        if (len(parts) == 3) and (parts[0] == 'path') and (parts[1] == 'phpcgibinary'):
            old_path = parts[2]
            is_found = True
            break
        i += 1

    if is_found:
        # directive found, check path in it
        if old_path != script_file:
            content[i] = 'path phpcgibinary ' + script_file + '\n'
            cagefslib.write_file(ISP_MANAGER_CONF_FILE, content)
    else:
        # directive not found, append it
        f = open(ISP_MANAGER_CONF_FILE, 'a')
        f.write('path phpcgibinary ' + script_file + '\n')
        f.close()

    # 5. Clear ISP Manager's cache and restart it
    shutil.rmtree('/usr/local/ispmgr/var/.xmlcache/ispmgr', True)
    p = subprocess.Popen(['killall', 'ispmgr'], shell=False, stdin=open('/dev/null'), stdout=subprocess.PIPE,
                                                    stderr=subprocess.STDOUT, close_fds=True)
    p.wait()

    # 6. Create user php wrappers
    #!/usr/local/bin/php-cgi-etc - for alt versions
    #!/usr/bin/php-cgi           - for native
    if (not cagefs_is_enabled()) or save_dir_exists():
        cagefs_enabled_users = []
    else:
        cagefs_enabled_users = get_list_of_users(True)

    exclude_list = get_exclude_user_list()
    get_min_uid()
    min_uid = MIN_UID

    pw = pwd.getpwall()
    for user_data in pw:
        if user_data.pw_uid < min_uid or user_data.pw_name in exclude_list:
            continue

        is_user_in_cagefs = user_data.pw_name in cagefs_enabled_users
        ispmanager_create_user_wrapper_detect_php_ver(user_data, is_user_in_cagefs, True)


# Creates user wrapper dependently user in cagefs or not
# This function for single-user operations in cagefsctl
def ispmanager_create_user_wrapper_detect_php_ver(user_data, is_user_in_cagefs, is_write_log=False):
    # Only for ISP Manager v4.x
    detect.getCP()
    if not detect.is_ispmanager() or not detect.CP_VERSION.startswith('4'):
        return

    if not is_user_in_cagefs:
        user_php_ver = "native"
    else:
        user_php_ver = cagefslib.get_php_version_for_user(user_data.pw_name)
        if user_php_ver is None:
            return

    ispmanager_create_user_wrapper(user_data.pw_name, user_php_ver, user_data, is_write_log)