Issues (16)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

Service/QueueService.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of HeriJobQueueBundle.
5
 *
6
 * (c) Alexandre Mogère
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Heri\Bundle\JobQueueBundle\Service;
13
14
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
15
use Symfony\Component\Console\Input\ArrayInput;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Console\Output\ConsoleOutput;
18
use Symfony\Component\Console\Output\StreamOutput;
19
use Symfony\Component\HttpKernel\Kernel;
20
use Symfony\Component\Process\Process;
21
use Psr\Log\LoggerInterface;
22
use Heri\Bundle\JobQueueBundle\Exception\InvalidUnserializedMessageException;
23
24
class QueueService
25
{
26
    const MICROSECONDS_PER_SECOND = 1000000;
27
28
    const PRIORITY_HIGH = 1;
29
30
    /**
31
     * var ZendQueue\Adapter\AbstractAdapter.
32
     */
33
    public $adapter;
34
35
    /**
36
     * var LoggerInterface.
37
     */
38
    protected $logger;
39
40
    /**
41
     * var ContainerAwareCommand.
42
     */
43
    protected $command;
44
45
    /**
46
     * var OutputInterface.
47
     */
48
    protected $output;
49
50
    /**
51
     * var \ZendQueue\Queue.
52
     */
53
    protected $queue;
54
55
    /**
56
     * var array.
57
     */
58
    protected $config;
59
60
    /**
61
     * var bool.
62
     */
63
    protected $running;
64
65
    /**
66
     * var integer.
67
     */
68
    protected $processTimeout = null;
69
70
    /**
71
     * @param LoggerInterface $logger
72
     * @param array           $config
73
     */
74
    public function __construct(LoggerInterface $logger, array $config = [])
75
    {
76
        $this->logger = $logger;
77
78
        $this->setUp($config);
79
80
        $this->running = true;
81
        $this->output = new ConsoleOutput();
82
83
        if (php_sapi_name() == 'cli') {
84
            pcntl_signal(SIGTERM, function () {
85
                $this->stop();
86
            });
87
88
            pcntl_signal(SIGINT, function () {
89
                $this->stop();
90
            });
91
        }
92
    }
93
94
    public function setUp($config)
95
    {
96
        $this->config = $config;
97
98
        $this->processTimeout = isset($this->config['process_timeout']) ? $this->config['process_timeout'] : null;
99
    }
100
101
    /**
102
     * @param string $name
103
     *
104
     * @return $this
105
     */
106
    public function attach($name)
107
    {
108
        $this->queue = new \ZendQueue\Queue($this->adapter, [
109
            'name' => $name,
110
        ]);
111
112
        return $this;
113
    }
114
115
    /**
116
     * @param int $maxMessages
117
     * @param int $timeout
118
     */
119
    public function receive($maxMessages = 1, $timeout = null)
120
    {
121
        $messages = $this->queue->receive($maxMessages, $timeout, $this->queue);
0 ignored issues
show
The call to Queue::receive() has too many arguments starting with $this->queue.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
122
123
        if ($messages && $messages->count() > 0) {
124
            $this->handle($messages);
125
        }
126
    }
127
128
    /**
129
     * @param array $args
130
     * @param int   $priority
0 ignored issues
show
There is no parameter named $priority. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
131
     */
132
    public function push(array $args)
133
    {
134
        if (!is_null($this->queue)) {
135
            if (class_exists('Zend\Json\Encoder')) {
136
                $body = \Zend\Json\Encoder::encode($args);
137
            } else {
138
                $body = json_encode($args);
139
            }
140
141
            $this->queue->send($body);
142
            $this->output->writeLn("<fg=green> [x] [{$this->queue->getName()}] {$args['command']} sent</>");
143
        }
144
    }
145
146
    /**
147
     * @param string $name
0 ignored issues
show
There is no parameter named $name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
148
     *
149
     * @return $this
150
     */
151
    public function highPriority()
152
    {
153
        $this->adapter->setPriority(self::PRIORITY_HIGH);
154
155
        return $this;
156
    }
157
158
    /**
159
     * @param string $name
160
     * @param int    $timeout
161
     */
162
    public function create($name, $timeout = null)
163
    {
164
        return $this->adapter->create($name, $timeout);
165
    }
166
167
    /**
168
     * @param string $name
169
     *
170
     * @return bool
171
     */
172
    public function delete($name)
173
    {
174
        return $this->adapter->delete($name);
175
    }
176
177
    /**
178
     * @param string $queueName
179
     */
180
    public function showMessages($queueName)
181
    {
182
        return $this->adapter->showMessages($queueName);
183
    }
184
185
    /**
186
     * @return bool
187
     */
188
    public function retry()
189
    {
190
        if (!method_exists($this->adapter, 'retry')) {
191
            return false;
192
        }
193
194
        return $this->adapter->retry();
195
    }
196
197
    /**
198
     * @paraam int $id
199
     *
200
     * @return bool
201
     */
202
    public function forget($id)
203
    {
204
        if (!method_exists($this->adapter, 'forget')) {
205
            return false;
206
        }
207
208
        return $this->adapter->forget($id);
209
    }
210
211
    /**
212
     * @return bool
213
     */
214
    public function flush()
215
    {
216
        return $this->adapter->flush();
217
    }
218
219
    /**
220
     * @return int
221
     */
222
    public function countMessages()
223
    {
224
        return $this->adapter->count();
225
    }
226
227
    /**
228
     * @return int
229
     */
230
    public function count()
231
    {
232
        return $this->adapter->count();
233
    }
234
235
    /**
236
     * @param ContainerAwareCommand $command
237
     */
238
    public function setCommand(ContainerAwareCommand $command)
239
    {
240
        $this->command = $command;
241
    }
242
243
    /**
244
     * @param OutputInterface $output
245
     */
246
    public function setOutput(OutputInterface $output)
247
    {
248
        $this->output = $output;
249
    }
250
251
    /**
252
     * @return OutputInterface
253
     */
254
    public function getOutput()
255
    {
256
        return $this->output;
257
    }
258
259
    public function isEnabled()
260
    {
261
        return $this->config['enabled'];
262
    }
263
264
    public function isRunning()
265
    {
266
        return $this->running;
267
    }
268
269
    public function setProcessTimeout($processTimeout)
270
    {
271
        $this->processTimeout = $processTimeout;
272
    }
273
274
    public function listen($name = null, $sleep = 0, $work = true)
275
    {
276
        if ($work) {
277
            $this->loop($name);
278
        } else {
279
            // event loop
280
            if (class_exists('React\EventLoop\Factory')) {
281
                $loop = \React\EventLoop\Factory::create();
282
                $loop->addPeriodicTimer($sleep, function (\React\EventLoop\Timer\Timer $timer) use ($name) {
283
                    $this->loop($name);
284
                    // stop closure loop on SIGINT
285
                    if (!$this->isRunning()) {
286
                        $timer->getLoop()->stop();
287
                    }
288
                });
289
                $loop->run();
290
            } else {
291
                do {
292
                    $this->loop($name);
293
                    usleep($sleep * self::MICROSECONDS_PER_SECOND);
294
                } while ($this->running);
295
            }
296
        }
297
    }
298
299
    protected function stop()
300
    {
301
        $this->running = false;
302
    }
303
304
    protected function loop($name = null)
305
    {
306
        $listQueues = [];
307
308
        if (php_sapi_name() == 'cli') {
309
            pcntl_signal_dispatch();
310
        }
311
        if (!$this->isRunning()) {
312
            return;
313
        }
314
315
        if ($name) {
316
            $listQueues[] = $name;
317
        } else {
318
            $listQueues = $this->config['queues'];
319
        }
320
321
        foreach ($listQueues as $name) {
322
            $this->attach($name);
323
            $this->receive($this->config['max_messages']);
324
325
            if (php_sapi_name() == 'cli') {
326
                pcntl_signal_dispatch();
327
            }
328
            if (!$this->isRunning()) {
329
                return;
330
            }
331
        }
332
    }
333
334
    /**
335
     * @param MessageIterator $messages
336
     */
337
    protected function handle(\ZendQueue\Message\MessageIterator $messages)
338
    {
339
        if (!$this->output instanceof OutputInterface) {
340
            $this->output = new StreamOutput(fopen('php://memory', 'w', false));
341
        }
342
343
        foreach ($messages as $message) {
344
            $this->run($message);
345
        }
346
    }
347
348
    protected function run($message)
349
    {
350
        if (property_exists($this->adapter, 'logger')) {
351
            $this->adapter->logger = $this->logger;
352
        }
353
354
        try {
355
            list(
356
                $commandName,
357
                $arguments
358
            ) = $this->getUnseralizedBody($message);
359
360
            $this->output->writeLn("<fg=yellow> [x] [{$this->queue->getName()}] {$commandName} received</> ");
361
362
            if (!isset($this->command)) {
363
                $console = 'app/console';
364
                if (Kernel::VERSION >= 3) {
365
                    $console = 'bin/console';
366
                }
367
368
                $process = new Process(sprintf('%s %s %s %s',
369
                    '/usr/bin/php', $console, $commandName,
370
                    implode(' ', $arguments)
371
                ));
372
                $process->setTimeout($this->processTimeout);
373
                $process->run();
374
375
                if (!$process->isSuccessful()) {
376
                    throw new \Exception($process->getErrorOutput());
377
                }
378
379
                echo $process->getOutput();
380
            } else {
381
                $input = new ArrayInput(array_merge([''], $arguments));
382
                $command = $this->command->getApplication()->find($commandName);
383
                $command->run($input, $this->output);
384
            }
385
386
            $this->queue->deleteMessage($message);
387
            $this->output->writeLn("<fg=green> [x] [{$this->queue->getName()}] {$commandName} done</>");
388
        } catch (\Exception $e) {
389
            $this->output->writeLn("<fg=white;bg=red> [!] [{$this->queue->getName()}] FAILURE: {$e->getMessage()}</>");
390
            $this->adapter->logException($message, $e);
391
        }
392
    }
393
394
    /**
395
     * @param ZendQueue\Message $message
396
     */
397
    protected function getUnseralizedBody(\ZendQueue\Message $message)
398
    {
399
        if (class_exists('Zend\Json\Json')) {
400
            $body = \Zend\Json\Json::decode($message->body, true);
401
        } else {
402
            $body = json_decode($message->body, true);
403
        }
404
405
        $arguments = [];
406
        $args = [];
407
        if (isset($body['argument'])) {
408
            $args = $body['argument'];
409
        } elseif (isset($body['arguments'])) {
410
            $args = $body['arguments'];
411
        }
412
413
        if (!isset($body['command']) || $body['command'] == '') {
414
            throw new InvalidUnserializedMessageException('Command name not found');
415
        }
416
417
        $commandName = $body['command'];
418
        foreach ($args as $key => $value) {
419
            if (is_string($key) && preg_match('/^--/', $key)) {
420
                if (is_bool($value)) {
421
                    $arguments[] = "{$key}";
422
                } else {
423
                    $arguments[] = "{$key}={$value}";
424
                }
425
            } else {
426
                $arguments[] = $value;
427
            }
428
        }
429
430
        return [
431
            $commandName,
432
            $arguments,
433
        ];
434
    }
435
}
436