summaryrefslogtreecommitdiffstats
path: root/SessionHelpers.php
blob: 90ae73beb6e7d3531467999b51bfb3939e608ff8 (plain)
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
<?php

namespace SessionHelpers;

class PhpSpawner {
    protected static function appendPhpArgs(string $php): string {
        $modules   = shell_exec("$php --no-php-ini -m");

        /* Determine if we need to specifically add extensions */
        $extensions = array_filter(
            ['igbinary', 'msgpack', 'json', 'redis'],
            function ($module) use ($modules) {
                return strpos($modules, $module) === false;
            }
        );

        /* If any are needed add them to the command */
        if ($extensions) {
            $php .= ' --no-php-ini';
            foreach ($extensions as $extension) {
                /* We want to use the locally built redis extension */
                if ($extension == 'redis') {
                    $path = dirname(__DIR__) . '/modules/redis';
                    if (is_file("{$path}.so"))
                        $extension = $path;
                }

                $php .= " -dextension=$extension.so";
            }
        }

        return $php;
    }

    /**
     * Return command to launch PHP with built extension enabled
     * taking care of environment (TEST_PHP_EXECUTABLE and TEST_PHP_ARGS)
     *
     * @param string $script
     *
     * @return string
     */
    public static function cmd(string $script): string {
        static $cmd = NULL;

        if ( ! $cmd) {
            $cmd = getenv('TEST_PHP_EXECUTABLE') ?: PHP_BINARY;

            if ($test_args = getenv('TEST_PHP_ARGS')) {
                $cmd .= ' ' . $test_args;
            } else {
                $cmd = self::appendPhpArgs($cmd);
            }
        }

        return $cmd . ' ' . __DIR__ . '/' . $script . ' ';
    }
}

class Runner {
    const start_script = 'startSession.php';
    const regenerate_id_script = 'regenerateSessionId.php';
    const get_data_script = 'getSessionData.php';

    private $required = ['host', 'handler', 'id'];

    private $args = [
        'handler' => null,
        'save-path' => null,
        'id' => null,
        'sleep' => 0,
        'max-execution-time' => 300,
        'locking-enabled' => true,
        'lock-wait-time' => null,
        'lock-retries' => -1,
        'lock-expires' => 0,
        'data' => '',
        'lifetime' => 1440,
        'compression' => 'none',
    ];

    private $prefix = NULL;
    private $output_file;
    private $exit_code = -1;
    private $cmd = NULL;
    private $pid;
    private $output;

    public function __construct() {
        $this->args['id'] = $this->createId();
    }

    public function getExitCode(): int {
        return $this->exit_code;
    }

    public function getCmd(): ?string {
        return $this->cmd;
    }

    public function getId(): ?string {
        return $this->args['id'];
    }

    public function prefix(string $prefix): self {
        $this->prefix = $prefix;
        return $this;
    }

    public function getSessionKey(): string {
        return $this->prefix . $this->getId();
    }

    public function getSessionLockKey(): string {
        return $this->getSessionKey() . '_LOCK';
    }

    protected function set($setting, $v): self {
        $this->args[$setting] = $v;
        return $this;
    }

    public function handler(string $handler): self {
        return $this->set('handler', $handler);
    }

    public function savePath(string $path): self {
        return $this->set('save-path', $path);
    }

    public function id(string $id): self {
        return $this->set('id', $id);
    }

    public function sleep(int $sleep): self {
        return $this->set('sleep', $sleep);
    }

    public function maxExecutionTime(int $time): self {
        return $this->set('max-execution-time', $time);
    }

    public function lockingEnabled(bool $enabled): self {
        return $this->set('locking-enabled', $enabled);
    }

    public function lockWaitTime(int $time): self {
        return $this->set('lock-wait-time', $time);
    }

    public function lockRetries(int $retries): self {
        return $this->set('lock-retries', $retries);
    }

    public function lockExpires(int $expires): self {
        return $this->set('lock-expires', $expires);
    }

    public function data(string $data): self {
        return $this->set('data', $data);
    }

    public function lifetime(int $lifetime): self {
        return $this->set('lifetime', $lifetime);
    }

    public function compression(string $compression): self {
        return $this->set('compression', $compression);
    }

    protected function validateArgs(array $required) {
        foreach ($required as $req) {
            if ( ! isset($this->args[$req]) || $this->args[$req] === null)
                throw new \Exception("Command requires '$req' arg");
        }
    }

    private function createId(): string {
        if (function_exists('session_create_id'))
            return session_create_id();

        return uniqid();
    }

    private function getTmpFileName() {
        return '/tmp/sessiontmp.txt';
        return tempnam(sys_get_temp_dir(), 'session');
    }

    /*
     * @param $client Redis client
     * @param string $max_wait_sec
     *
     * Sometimes we want to block until a session lock has been detected
     * This is better and faster than arbitrarily sleeping.  If we don't
     * detect the session key within the specified maximum number of
     * seconds, the function returns failure.
     *
     * @return bool
     */
    public function waitForLockKey($redis, $max_wait_sec) {
        $now = microtime(true);

        do {
            if ($redis->exists($this->getSessionLockKey()))
                return true;
            usleep(10000);
        } while (microtime(true) <= $now + $max_wait_sec);

        return false;
    }

    private function appendCmdArgs(array $args): string {
        $append = [];

        foreach ($args as $arg => $val) {
            if ( ! $val)
                continue;

            if (is_string($val))
                $val = escapeshellarg($val);

            $append[] = "--$arg";
            $append[] = $val;
        }

        return implode(' ', $append);
    }

    private function buildPhpCmd(string $script, array $args): string {
        return PhpSpawner::cmd($script) . ' ' . $this->appendCmdArgs($args);
    }

    private function startSessionCmd(): string {
        return $this->buildPhpCmd(self::start_script, $this->args);
    }

    public function output(?int $timeout = NULL): ?string {
        if ($this->output) {
            var_dump("early return");
            return $this->output;
        }

        if ( ! $this->output_file || ! $this->pid) {
            throw new \Exception("Process was not started in the background");
        }

        $st = microtime(true);

        do {
            if (pcntl_waitpid($this->pid, $exit_code, WNOHANG) == 0)
                break;
            usleep(100000);
        } while ((microtime(true) - $st) < $timeout);

        if ( ! file_exists($this->output_file))
            return "";

        $this->output      = file_get_contents($this->output_file);
        $this->output_file = NULL;
        $this->exit_code   = $exit_code;
        $this->pid         = NULL;

        return $this->output;
    }

    public function execBg(): bool {
        if ($this->cmd)
            throw new \Exception("Command already executed!");

        $output_file = $this->getTmpFileName();

        $this->cmd  = $this->startSessionCmd();
        $this->cmd .= " >$output_file 2>&1 & echo $!";

        $pid = exec($this->cmd, $output, $exit_code);
        $this->exit_code = $exit_code;

        if ($this->exit_code || !is_numeric($pid))
            return false;

        $this->pid = (int)$pid;
        $this->output_file = $output_file;

        return true;
    }

    public function execFg() {
        if ($this->cmd)
            throw new \Exception("Command already executed!");

        $this->cmd = $this->startSessionCmd() . ' 2>&1';

        exec($this->cmd, $output, $exit_code);
        $this->exit_code = $exit_code;
        $this->output = implode("\n", array_filter($output));

        return $this->output;
    }

    private function regenerateIdCmd($locking, $destroy, $proxy): string {
        $this->validateArgs(['handler', 'id', 'save-path']);

        $args = [
            'handler' => $this->args['handler'],
            'save-path' => $this->args['save-path'],
            'id' => $this->args['id'],
            'locking-enabled' => !!$locking,
            'destroy' => !!$destroy,
            'proxy' => !!$proxy,
        ];

        return $this->buildPhpCmd(self::regenerate_id_script, $args);
    }

    public function regenerateId($locking = false, $destroy = false, $proxy = false) {
        if ( ! $this->cmd)
            throw new \Exception("Cannot regenerate id before starting session!");

        $cmd = $this->regenerateIdCmd($locking, $destroy, $proxy);

        exec($cmd, $output, $exit_code);

        if ($exit_code != 0)
            return false;

        return $output[0];
    }

    private function getDataCmd(?int $lifetime): string {
        $this->validateArgs(['handler', 'save-path', 'id']);

        $args = [
            'handler' => $this->args['handler'],
            'save-path' => $this->args['save-path'],
            'id' => $this->args['id'],
            'lifetime' => is_int($lifetime) ? $lifetime : $this->args['lifetime'],
        ];

        return $this->buildPhpCmd(self::get_data_script, $args);
    }

    public function getData(?int $lifetime = NULL): string {
        $cmd = $this->getDataCmd($lifetime);

        exec($cmd, $output, $exit_code);
        if ($exit_code != 0) {
            return implode("\n", $output);
        }

        return $output[0];
    }
}