1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 
<?php
    declare(strict_types=1);

    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    /**
     * Class Pman_Module
     *
     * Process management
     *
     * @package core
     */
    class Pman_Module extends Module_Skeleton
    {
        const PROC_PATH = '/proc';
        const PROC_CACHE_KEY = 'pman.all';
        const MAX_WAIT_TIME = 600;
        /* biggest signal number + 1 taken from bits/signum.h */
        const _NSIG = 65;
        // conditionally defined if pcntl enabled
        const SIGKILL = 9;

        public $exportedFunctions = array(
            '*'                      => PRIVILEGE_ALL,
            'schedule_api_cmd_admin' => PRIVILEGE_ADMIN
        );

        public function __construct()
        {
            parent::__construct();
        }

        /**
         * Terminal a process with SIGKILL
         *
         * @param int $pid process
         * @return bool
         */
        public function kill($pid)
        {
            // SIGKILL isn't defined in ISAPI?
            return $this->signal($pid, self::SIGKILL);
        }

        /**
         * Send a POSIX signal a process
         *
         * @param int $pid
         * @param int $signal
         * @return bool
         */
        public function signal($pid, $signal = self::SIGKILL)
        {
            if (!IS_CLI) {
                return $this->query('pman_signal', $pid, $signal);
            }

            if (!ctype_digit($pid)) {
                return error("invalid pid `%s'", $pid);
            }
            $signal = (int)$signal;
            if ($signal < -1 || $signal > self::_NSIG) {
                return error('invalid signal %d', $signal);
            }

            if ($this->permission_level & PRIVILEGE_ADMIN) {
                return posix_kill((int)$pid, $signal);
            }

            $status = Util_Process_Sudo::exec('/bin/kill -%d %d ', $signal, (int)$pid);
            if (!$status['success']) {
                return error('kill failed: %s', $status['stderr']);
            }

            return $status['success'];
        }

        /**
         * Stat a running process
         *
         * @param int $pid process id
         * @return array stat or empty array
         *
         * Sample response:
         * Array
         * (
         * [pid] => 8849
         * [comm] => bash
         * [stat] => S
         * [ppid] => 8848
         * [pgrp] => 8849
         * [session] => 5185
         * [tty_nr] => 34816
         * [tpgid] => 27992
         * [flags] => 4219136
         * [minflt] => 47250071
         * [cminflt] => 154934160
         * [majflt] => 0
         * [cmajflt] => 0
         * [utime] => 101.48
         * [stime] => 403.61
         * [cutime] => 0
         * [cstime] => 0
         * [priority] => 39
         * [nice] => 19
         * [num_threads] => 1
         * [itrealvalue] => 0
         * [starttime] => 50639.3
         * [vsize] => 4988
         * [rss] => 2516
         * [rsslim] => 524288
         * [user] => 514
         * [cwd] => /
         * [startutime] => 1430844663
         * [args] => Array
         * (
         * )
         *
         * pid: process id
         * comm: raw command name
         * args: command arguments
         * stat: process state, one char of RSDZTW, R = running
         * ppid: parent PID
         * pgrp: process group ID
         * session: process session ID
         * tty_nr: controlling terminal in bitmap
         * tpgid: ID of foreground process group of controlling terminal proc
         * flags: task flags
         * minflt: number of minor faults
         * cminflt: number of minor faults in children
         * majflt: number of major faults
         * cmajflt: number of major faults in children
         * utime: user time in seconds (NB: converted from jiffies)
         * stime: system time in seconds (NB: converted from jiffies)
         * cutime: user time of children in seconds (NB: converted from jiffies)
         * cstime: system time of chldren in seconds (NB: converted from jiffies)
         * priority: process priority level
         * nice: nice level
         * num_threads: number of threads
         * itrealvalue: obsolete (always 0)
         * starttime: time the process started after boot
         * startutime: time the process started after boot in unixtime
         * vsize: virtual memory size in KB (NB: converted from pages)
         * rss: resident set memory size in KB (NB: converted from pages)
         * rsslim: current limit in KB of the rss
         * user: user id of the process (translate w/ user_get_username_from_uid)
         *
         */
        public function stat($pid)
        {
            if (!IS_CLI) {
                return $this->query('pman_stat', $pid);
            }
            $procs = $this->_processAccumulator();
            if (isset($procs[$pid])) {
                return $procs[$pid];
            }

            return array();
        }

        /**
         * Collect all processes for a site
         *
         * @return array
         */
        private function _processAccumulator()
        {
            $cache = Cache_Account::spawn($this->getAuthContext());
            $all = $cache->get(self::PROC_CACHE_KEY);
            if ($all !== false && \is_array($all)) {
                return $all;
            }

            $that = $this;

            $pids = $this->_collectPids();
            $all = Error_Reporter::silence(static function() use($pids) {
                return \Opcenter\Process::stat($pids);
            });
            $uptime = file_get_contents('/proc/uptime');
            $now = time();
            [$uptime] = explode(' ', $uptime, 1);

            foreach ($all as &$proc) {
                if (!$this->permission_level & PRIVILEGE_ADMIN) {
                    $proc['cwd'] = $that->file_canonicalize_site($proc['cwd']);
                }
                $proc['startutime'] = round($now - ((int)$uptime - $proc['starttime']));
            }
            unset($proc);

            $cache->set(self::PROC_CACHE_KEY, $all, 60);
            return $all;
        }

        /**
         * Get active processes
         *
         * @return array
         */
        private function _collectPids()
        {
            $controllers = $this->cgroup_get_controllers();
            // memory + cpu proc lists are balanced
            $cgroupprocs = Cgroup_Module::CGROUP_LOCATION . '/' .
                array_pop($controllers) . '/' . $this->cgroup_get_cgroup() . '/cgroup.procs';
            $isAdmin = ($this->permission_level & PRIVILEGE_ADMIN);
            if (!$isAdmin && file_exists($cgroupprocs)) {
                return array_map('\intval',(array)file($cgroupprocs, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
            }
            $procpath = self::PROC_PATH;
            $dir = opendir($procpath);
            $procs = array();
            while (false !== ($file = readdir($dir))) {
                $path = $procpath . '/' . $file;
                if (!is_dir($path) || $file === '..' || $file === '.') {
                    continue;
                } else if (!$isAdmin && filegroup($path) !== $this->group_id) {
                    continue;
                }
                $procs[] = $file;
            }
            closedir($dir);

            return $procs;
        }

        /**
         * Get active process count
         *
         * Count is fetched from cache. {@see flush} may be necessary
         *
         * @return int
         */
        public function pcount()
        {
            $count = count($this->_processAccumulator());

            return $count;
        }

        /**
         * Flush process accumulator cache
         *
         * @return bool
         */
        public function flush()
        {
            $cache = Cache_Account::spawn($this->getAuthContext());

            return $cache->del(self::PROC_CACHE_KEY);
        }

        /**
         * Get all processes
         *
         * @return array {@see stat}
         */
        public function get_processes()
        {
            if (!IS_CLI) {
                return $this->query('pman_get_processes');
            }

            return $this->_processAccumulator();
        }

        /**
         * Run a process
         *
         * Sample response:
         *
         * Array
         * (
         * [stdin] =>
         * [stdout] => Hello World!!!
         * [0] => Hello World!!!
         * [stderr] =>
         * [1] =>
         * [output] => Hello World!!!
         * [errno] => 0
         * [return] => 0
         * [error] =>
         * [success] => 1
         * )
         *
         * @param string $cmd     process name, format specifiers allowed
         * @param array  $args    optional arguments to supply to format
         * @param array  $env     optional environment vars to set
         * @param array  $options optional options, tee: set tee output to file, user: run as user if site admin
         * @return bool|array
         */
        public function run($cmd, $args = null, array $env = null, array $options = [])
        {
            if (!IS_CLI) {
                if ($this->auth_is_demo()) {
                    return error('process execution forbidden in demo');
                }
                // store msg buffer in event app is killed for
                // exceeding max wait time
                $buffer = Error_Reporter::flush_buffer();
                $resp = $this->query('pman_run', $cmd, $args, $env, $options);
                if (null === $resp) {
                    // restore old buffer, ignore crash or other nasty error detected! msg
                    Error_Reporter::set_buffer($buffer);

                    return error('process lingered for %d seconds, ' .
                        'automatically abandoning', self::MAX_WAIT_TIME);
                }
                Error_Reporter::set_buffer(array_merge($buffer, \Error_Reporter::flush_buffer()));

                return $resp;
            }
            if (null === $env) {
                $env = $_ENV;
            }

            // always force
            $env['BASH_ENV'] = null;
            $proc = Util_Process_Sudo::instantiateContexted($this->getAuthContext());
            if ($env) {
                $proc->setEnvironment($env);
            }
            // suppress automatically generated errors
            $proc->setOption('mute_stderr', true);
            $user = $this->username;
            if (isset($options['user'])) {
                if (!$this->permission_level & PRIVILEGE_SITE) {
                    return error("failed to launch `%s': only site admin may specify user parameter to run as",
                        basename($cmd)
                    );
                }
                $pwd = $this->user_getpwnam($options['user']);
                if (!$pwd) {
                    report('Failed getpwnam - ' . $this->inContext() . "\n" . var_export($this->getAuthContext(),
                            true) . "\n" . var_export($this->user_get_users(), true));

                    return error("unknown user `%s'", $options['user']);
                }
                $minuid = apnscpFunctionInterceptor::get_autoload_class_from_module('user')::MIN_UID;
                if ($pwd['uid'] < $minuid) {
                    return error("uid `%d' is less than allowable uid `%d' - system user?", $pwd['uid'], $minuid);
                }
                $user = $options['user'];
            }

            if (isset($options['tee'])) {
                if ($options['tee'][0] != '/') {
                    // relative file listed, assume /tmp
                    $options['tee'] = TEMP_DIR . '/' . $options['tee'];
                }
                if (file_exists($options['tee']) || is_link($options['tee'])) {
                    // verify not trying to stream something like /etc/shadow
                    return error("tee file `%s' exists", $options['tee']);
                } else if (!touch($options['tee'])) {
                    return error("cannot use tee file `%s'", $options['tee']);
                }
                $tee = new Util_Process_Tee();
                $tee->setTeeFile($options['tee']);
                $tee->setProcess($proc);
                \Opcenter\Filesystem::chogp($options['tee'], WS_UID, WS_UID, 0600);
            }
            // capture & extract the safe command, then sudo
            $proc->setOption('umask', 0022)->
            setOption('timeout', self::MAX_WAIT_TIME)->
            setOption('user', $user)->
            setOption('home', true);
            // temp fix, last arg is checked for user/domain substitution,
            // wordpress sets user for example
            $ret = $proc->run($cmd, $args);

            return $ret;
        }

        /**
         * Background an apnscp function with an optional delay
         *
         * @param            $realcmd
         * @param array|null $args
         * @param string     $when
         */
        public function schedule_api_cmd($cmd, $args = array(), $when = 'now')
        {
            if (!IS_CLI) {
                return $this->query('pman_schedule_api_cmd', $cmd, $args, $when);
            }

            return $this->schedule_api_cmd_admin($this->site, $this->username, $cmd, $args, $when);
        }

        /**
         * Background an apnscp function as any user on any domain
         * with an optional delay
         *
         * @param string     $site domain or site to runas
         * @param null|string     $user username to run as
         * @param            $cmd  api command to run
         * @param array|null $args api arguments
         * @param string     $when optional time spec
         * @return bool
         * @internal param $realcmd
         */
        public function schedule_api_cmd_admin($site, ?string $user, $cmd, $args = array(), $when = 'now')
        {
            if (!IS_CLI) {
                return $this->query('pman_schedule_api_cmd_admin', $site, $user, $cmd, $args, $when);
            }
            // @XXX changing the username following api_cmd can result in a failed command

            $realcmd = '';
            if ($site) {
                $realcmd .= '-d ' . escapeshellarg($site) . ' ';
            }
            if ($user) {
                $realcmd .= '-u ' . escapeshellarg($user) . ' ';
            }
            // support multiple commands
            if (!is_array($cmd)) {
                $cmd = array(array($cmd, $args));
            } else if (is_scalar($args)) {
                // [site, user, [[cmd1, [args]], [cmd2, [args]]], when]
                $when = $args;
            }

            // avoid fatals
            $timespec = new DateTime($when);
            if (!$timespec) {
                return error("unparseable timespec `%s'", $when);
            }
            $proc = new Util_Process_Schedule($timespec);
            // send "cpcmd -m"
            $multi = true;
            $components = array();
            for ($i = 0, $n = sizeof($cmd); $i < $n; $i++) {
                $tmp = $cmd[$i];
                $cmdcom = $tmp[0];
                $argcom = $tmp[1] ?? array();
                $safeargs = array();
                foreach ($argcom as $a) {
                    if ($multi && array_filter((array)$argcom, static function ($v) {
                            return $v === ';';
                        })) {
                        debug('; detected as lone argument to %s, disabling multi mode to cpcmd', $cmdcom);
                        $multi = false;
                    }
                    if (is_array($a)) {
                        if (isset($a[0])) {
                            // array
                            $a = array_map('escapeshellarg', $a);
                        } else {
                            // hash
                            array_walk($a, static function (&$v, $k) {
                                $v = escapeshellarg($k) . ':' . escapeshellarg($v);
                            });
                        }
                        $a = '[' . join(',', $a) . ']';
                    }
                    $safeargs[] = is_string($a) ? escapeshellarg($a) : $a;
                }

                $safeargs = join(' ', $safeargs);
                $components[] = escapeshellarg($cmdcom) . ' ' . $safeargs;
            }
            $realcmd .= join(' \; ', $components);
            $multi &= count($components) > 1;
            $basecmd = bin_path('cmd' . ($multi ? ' -m' : ''));
            $ret = $proc->run($basecmd . ' ' . $realcmd);
            if (!$ret['success']) {
                return error("failed to schedule task `%s': %s", $realcmd, $ret['stderr']);
            }

            return true;
        }
    }