Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of Psy Shell.
5
 *
200 lars 6
 * (c) 2012-2023 Justin Hileman
148 lars 7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Psy\ExecutionLoop;
13
 
14
use Psy\Context;
15
use Psy\Exception\BreakException;
16
use Psy\Shell;
17
 
18
/**
19
 * An execution loop listener that forks the process before executing code.
20
 *
21
 * This is awesome, as the session won't die prematurely if user input includes
22
 * a fatal error, such as redeclaring a class or function.
23
 */
24
class ProcessForker extends AbstractListener
25
{
26
    private $savegame;
27
    private $up;
28
 
29
    private static $pcntlFunctions = [
30
        'pcntl_fork',
31
        'pcntl_signal_dispatch',
32
        'pcntl_signal',
33
        'pcntl_waitpid',
34
        'pcntl_wexitstatus',
35
    ];
36
 
37
    private static $posixFunctions = [
38
        'posix_getpid',
39
        'posix_kill',
40
    ];
41
 
42
    /**
43
     * Process forker is supported if pcntl and posix extensions are available.
44
     */
45
    public static function isSupported(): bool
46
    {
47
        return self::isPcntlSupported() && !self::disabledPcntlFunctions() && self::isPosixSupported() && !self::disabledPosixFunctions();
48
    }
49
 
50
    /**
51
     * Verify that all required pcntl functions are, in fact, available.
52
     */
53
    public static function isPcntlSupported(): bool
54
    {
55
        foreach (self::$pcntlFunctions as $func) {
56
            if (!\function_exists($func)) {
57
                return false;
58
            }
59
        }
60
 
61
        return true;
62
    }
63
 
64
    /**
65
     * Check whether required pcntl functions are disabled.
66
     */
67
    public static function disabledPcntlFunctions()
68
    {
69
        return self::checkDisabledFunctions(self::$pcntlFunctions);
70
    }
71
 
72
    /**
73
     * Verify that all required posix functions are, in fact, available.
74
     */
75
    public static function isPosixSupported(): bool
76
    {
77
        foreach (self::$posixFunctions as $func) {
78
            if (!\function_exists($func)) {
79
                return false;
80
            }
81
        }
82
 
83
        return true;
84
    }
85
 
86
    /**
87
     * Check whether required posix functions are disabled.
88
     */
89
    public static function disabledPosixFunctions()
90
    {
91
        return self::checkDisabledFunctions(self::$posixFunctions);
92
    }
93
 
94
    private static function checkDisabledFunctions(array $functions): array
95
    {
96
        return \array_values(\array_intersect($functions, \array_map('strtolower', \array_map('trim', \explode(',', \ini_get('disable_functions'))))));
97
    }
98
 
99
    /**
100
     * Forks into a main and a loop process.
101
     *
102
     * The loop process will handle the evaluation of all instructions, then
103
     * return its state via a socket upon completion.
104
     *
105
     * @param Shell $shell
106
     */
107
    public function beforeRun(Shell $shell)
108
    {
109
        list($up, $down) = \stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP);
110
 
111
        if (!$up) {
112
            throw new \RuntimeException('Unable to create socket pair');
113
        }
114
 
115
        $pid = \pcntl_fork();
116
        if ($pid < 0) {
117
            throw new \RuntimeException('Unable to start execution loop');
118
        } elseif ($pid > 0) {
119
            // This is the main thread. We'll just wait for a while.
120
 
121
            // We won't be needing this one.
122
            \fclose($up);
123
 
124
            // Wait for a return value from the loop process.
125
            $read = [$down];
126
            $write = null;
127
            $except = null;
128
 
129
            do {
130
                $n = @\stream_select($read, $write, $except, null);
131
 
132
                if ($n === 0) {
133
                    throw new \RuntimeException('Process timed out waiting for execution loop');
134
                }
135
 
136
                if ($n === false) {
137
                    $err = \error_get_last();
138
                    if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) {
139
                        $msg = $err['message'] ?
140
                            \sprintf('Error waiting for execution loop: %s', $err['message']) :
141
                            'Error waiting for execution loop';
142
                        throw new \RuntimeException($msg);
143
                    }
144
                }
145
            } while ($n < 1);
146
 
147
            $content = \stream_get_contents($down);
148
            \fclose($down);
149
 
150
            if ($content) {
151
                $shell->setScopeVariables(@\unserialize($content));
152
            }
153
 
154
            throw new BreakException('Exiting main thread');
155
        }
156
 
157
        // This is the child process. It's going to do all the work.
158
        if (!@\cli_set_process_title('psysh (loop)')) {
159
            // Fall back to `setproctitle` if that wasn't succesful.
160
            if (\function_exists('setproctitle')) {
161
                @\setproctitle('psysh (loop)');
162
            }
163
        }
164
 
165
        // We won't be needing this one.
166
        \fclose($down);
167
 
168
        // Save this; we'll need to close it in `afterRun`
169
        $this->up = $up;
170
    }
171
 
172
    /**
173
     * Create a savegame at the start of each loop iteration.
174
     *
175
     * @param Shell $shell
176
     */
177
    public function beforeLoop(Shell $shell)
178
    {
179
        $this->createSavegame();
180
    }
181
 
182
    /**
183
     * Clean up old savegames at the end of each loop iteration.
184
     *
185
     * @param Shell $shell
186
     */
187
    public function afterLoop(Shell $shell)
188
    {
189
        // if there's an old savegame hanging around, let's kill it.
190
        if (isset($this->savegame)) {
191
            \posix_kill($this->savegame, \SIGKILL);
192
            \pcntl_signal_dispatch();
193
        }
194
    }
195
 
196
    /**
197
     * After the REPL session ends, send the scope variables back up to the main
198
     * thread (if this is a child thread).
199
     *
200
     * @param Shell $shell
201
     */
202
    public function afterRun(Shell $shell)
203
    {
204
        // We're a child thread. Send the scope variables back up to the main thread.
205
        if (isset($this->up)) {
206
            \fwrite($this->up, $this->serializeReturn($shell->getScopeVariables(false)));
207
            \fclose($this->up);
208
 
209
            \posix_kill(\posix_getpid(), \SIGKILL);
210
        }
211
    }
212
 
213
    /**
214
     * Create a savegame fork.
215
     *
216
     * The savegame contains the current execution state, and can be resumed in
217
     * the event that the worker dies unexpectedly (for example, by encountering
218
     * a PHP fatal error).
219
     */
220
    private function createSavegame()
221
    {
222
        // the current process will become the savegame
223
        $this->savegame = \posix_getpid();
224
 
225
        $pid = \pcntl_fork();
226
        if ($pid < 0) {
227
            throw new \RuntimeException('Unable to create savegame fork');
228
        } elseif ($pid > 0) {
229
            // we're the savegame now... let's wait and see what happens
230
            \pcntl_waitpid($pid, $status);
231
 
232
            // worker exited cleanly, let's bail
233
            if (!\pcntl_wexitstatus($status)) {
234
                \posix_kill(\posix_getpid(), \SIGKILL);
235
            }
236
 
237
            // worker didn't exit cleanly, we'll need to have another go
238
            $this->createSavegame();
239
        }
240
    }
241
 
242
    /**
243
     * Serialize all serializable return values.
244
     *
245
     * A naïve serialization will run into issues if there is a Closure or
246
     * SimpleXMLElement (among other things) in scope when exiting the execution
247
     * loop. We'll just ignore these unserializable classes, and serialize what
248
     * we can.
249
     *
250
     * @param array $return
251
     */
252
    private function serializeReturn(array $return): string
253
    {
254
        $serializable = [];
255
 
256
        foreach ($return as $key => $value) {
257
            // No need to return magic variables
258
            if (Context::isSpecialVariableName($key)) {
259
                continue;
260
            }
261
 
262
            // Resources and Closures don't error, but they don't serialize well either.
263
            if (\is_resource($value) || $value instanceof \Closure) {
264
                continue;
265
            }
266
 
267
            if (\version_compare(\PHP_VERSION, '8.1', '>=') && $value instanceof \UnitEnum) {
268
                // Enums defined in the REPL session can't be unserialized.
269
                $ref = new \ReflectionObject($value);
270
                if (\strpos($ref->getFileName(), ": eval()'d code") !== false) {
271
                    continue;
272
                }
273
            }
274
 
275
            try {
276
                @\serialize($value);
277
                $serializable[$key] = $value;
278
            } catch (\Throwable $e) {
279
                // we'll just ignore this one...
280
            }
281
        }
282
 
283
        return @\serialize($serializable);
284
    }
285
}