Inheritance: extends Process
Esempio n. 1
0
function initServer()
{
    $process = new PhpProcess(file_get_contents(__DIR__ . '/worker.php'), __DIR__);
    $process->start();
    sleep(5);
    return $process;
}
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->securityContext->getToken()) {
         return;
     }
     $request = $event->getRequest();
     if (!$request->hasSession()) {
         throw new \RuntimeException('This authentication method requires a session.');
     }
     $cookies = array_intersect_key($request->cookies->all(), array_flip(array_filter(array_keys($request->cookies->all()), function ($input) {
         return strpos($input, 'wordpress_logged_in_') === 0;
     })));
     $logger = $this->logger;
     if (empty($cookies)) {
         return;
     }
     if (null !== $this->logger) {
         $this->logger->debug('Found eligible cookies prefixed with wordpress_logged_in_');
     }
     $script = call_user_func($this->script, InjectRequestGlobals::toSubprocessGlobals($request), "\$user = wp_get_current_user(); echo json_encode(\$user);");
     $process = new PhpProcess('<?php ' . $script, $this->documentRoot);
     $process->run();
     $output = $process->getOutput();
     $user = json_decode($output);
     // Attempt to load a WordPress user based on cookies for this site's domain.
     if (!$user || isset($user->ID) && $user->ID === 0) {
         return;
     }
     // Translate WordPress roles into Symfony Security component roles.
     $roles = array_map(function ($input) {
         return 'ROLE_WORDPRESS_' . strtoupper($input);
     }, $user->roles);
     $roles[] = 'ROLE_USER';
     // Generate token.
     $token = new WordpressUserToken($roles);
     $token->setUser($user->data->display_name);
     try {
         // Authorize token.
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         // To deny the authentication clear the token. This will redirect to the login page.
         // Make sure to only clear your token, not those of other authentication listeners.
         $token = $this->securityContext->getToken();
         if ($token instanceof WordpressUserToken) {
             $this->securityContext->setToken(null);
         }
         // Deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
Esempio n. 3
0
    public function testNonBlockingWorks()
    {
        $expected = 'hello world!';
        $process = new PhpProcess(<<<PHP
<?php echo '{$expected}';
PHP
);
        $process->start();
        $process->wait();
        $this->assertEquals($expected, $process->getOutput());
    }
 public function testWordpressBootstrap()
 {
     $app = $this->createApplication();
     $commandline = realpath('./vendor/wp-cli/wp-cli/bin/wp core config');
     $process = new \Symfony\Component\Process\Process($commandline);
     $process->setWorkingDirectory(realpath('./vendor/wordpress/wordpress'));
     $process->run();
     $output = $process->getOutput();
     $script = $app['php.wordpress36.bootstrap']();
     $process = new \Symfony\Component\Process\PhpProcess('<?php ' . $script, realpath('./vendor/wordpress/wordpress'));
     $process->setWorkingDirectory(realpath('./vendor/wordpress/wordpress'));
     $process->run();
     $output = $process->getOutput();
 }
 public function testDrupalBootstrap()
 {
     $app = $this->createApplication();
     $commandline = realpath('./vendor/bin/drush');
     $site = md5(microtime());
     $process = new \Symfony\Component\Process\Process($commandline . ' --yes site-install --db-url=sqlite://sites/' . $site . '/files/.ht.sqlite --sites-subdir=' . $site . ' --pipe');
     $process->setWorkingDirectory(realpath('./vendor/drupal/drupal'));
     $process->run();
     $output = $process->getOutput();
     $script = $app['php.drupal7.bootstrap']('http://' . $site . '/index.php', '', 'echo conf_path();');
     $process = new PhpProcess('<?php ' . $script, realpath('./vendor/drupal/drupal'));
     $process->run();
     $output = $process->getOutput();
     $this->assertEquals('sites/' . $site, $output);
 }
Esempio n. 6
0
 /**
  * Create process
  */
 protected function createProcess()
 {
     // initialisation du process
     $this->process = new PhpProcess($this->getScript(), $this->getConfiguration()->getCwd(), $this->getConfiguration()->getEnv(), $this->getConfiguration()->getTimeout());
     if ($this->configuration->getParameter('PHP_BINARY')) {
         $this->process->setPhpBinary($this->configuration->getParameter('PHP_BINARY'));
     }
 }
Esempio n. 7
0
 protected function createWorker($id)
 {
     $files = get_included_files();
     if ($_SERVER['PHP_SELF'] != '-') {
         array_shift($files);
     }
     $boostrap = "<?php \n        foreach (" . var_export($files, true) . " as \$file) {\n            require_once \$file;\n        }\n\n        define('__WORKER__', " . var_export($id, true) . ");\n\n        \$config = crodas\\Worker\\Config::import(" . $this->config->export() . ");\n        \$config['worker_id'] = __WORKER__;\n\n        \$server = new crodas\\Worker\\Server(\$config);\n        \$server->worker();\n        ";
     $this->log(null, "Starting process {$id}");
     $process = new PhpProcess($boostrap);
     $process->start();
     $process->id = $id;
     $process->time = time();
     $process->status = empty($args) ? 'idle' : 'busy';
     $process->jobs = 0;
     $process->failed = 0;
     return $process;
 }
Esempio n. 8
0
 function assertTranspile($yamlPath)
 {
     $input = new ArrayInput(array());
     $stream = fopen('php://memory', 'rw', false);
     $output = new StreamOutput($stream);
     $symfonyio = new SymfonyIO($input, $output);
     // Load and parse yaml
     $config = Yaml::parse(file_get_contents($yamlPath));
     if (!isset($config['stdout'])) {
         $this->fail('Stdout section not found in $yamlPath');
     }
     if (!isset($config['code'])) {
         $this->fail('Code section not found in $yamlPath');
     }
     // Create temp file for code to transpile
     $tmpPath = tempnam(sys_get_temp_dir(), 'transphpile');
     file_put_contents($tmpPath, "<?php\n" . $config['code']);
     // Transpile code and send to stdout
     $transpiler = new Transpile($symfonyio);
     $transpiler->transpile($tmpPath, '-');
     // unlink tmp file
     unlink($tmpPath);
     // Fetch php5 code written by transpiler
     rewind($stream);
     $php5 = stream_get_contents($stream);
     // Run php5 code
     $process = new PhpProcess($php5);
     $process->run();
     $stdout = $process->getOutput();
     $stderr = $process->getErrorOutput();
     // If we don't define stderr, there should not be any stderr output from our php5 file
     if (!empty($stderr) && !isset($config['stderr'])) {
         $this->fail('Error reported, but no stderr section found in $yamlPath');
     }
     // Check output
     $config['stdout'] = trim($config['stdout']);
     $this->assertRegExp('{' . $config['stdout'] . '}', $stdout, isset($config['name']) ? $config['name'] : "");
     // Check stderr if any
     if (isset($config['stderr'])) {
         $config['stderr'] = trim($config['stderr']);
         if (empty($stderr)) {
             $this->fail('stderr seems empty but should contain an error');
         }
         $this->assertRegExp('{' . $config['stderr'] . '}', $stderr, isset($config['name']) ? $config['name'] : "");
     }
 }
Esempio n. 9
0
    /**
     * Initiates new actor in a new PHP process
     * @param integer  $id An unique id of an actor, should be free tcp-port in current implementation
     * @param callable $handler
     * @return PhpProcess
     */
    public static function createAndRun($id, callable $handler)
    {
        $serializedHandler = base64_encode((new Serializer())->serialize($handler));
        $autoloadPath = Utils::getAutoloadPath();
        $process = new PhpProcess(<<<EOF
    <?php
        require '{$autoloadPath}';
        \\Phactor\\Phactor\\Actor::initializeChild({$id}, '{$serializedHandler}');
    ?>
EOF
);
        if (null === $process->getCommandLine()) {
            $process->setPhpBinary(PHP_BINARY);
        }
        // workaround for portable windows php
        $process->start();
        return $process;
    }
    /**
     * Submit a frontend request
     *
     * @param string $requestUrl URL to make a frontend request
     */
    public function requestCommand($requestUrl)
    {
        // TODO: this needs heavy cleanup!
        $template = file_get_contents(PATH_typo3 . 'sysext/core/Tests/Functional/Fixtures/Frontend/request.tpl');
        $arguments = array('documentRoot' => PATH_site, 'requestUrl' => $requestUrl);
        // No other solution atm than to fake a CLI request type
        $code = '<?php
		define(\'TYPO3_REQUESTTYPE\', 6);
		?>';
        $code .= str_replace(array('{originalRoot}', '{arguments}'), array(PATH_site, var_export($arguments, true)), $template);
        $process = new PhpProcess($code);
        $process->mustRun();
        $rawResponse = json_decode($process->getOutput());
        if ($rawResponse === NULL || $rawResponse->status === Response::STATUS_Failure) {
            $this->outputLine('<error>An error occurred while trying to request the specified URL.</error>');
            $this->outputLine(sprintf('<error>Error: %s</error>', !empty($rawResponse->error) ? $rawResponse->error : 'Could not decode response. Please check your error log!'));
            $this->outputLine(sprintf('<error>Content: %s</error>', $process->getOutput()));
            $this->sendAndExit(1);
        }
        $this->output($rawResponse->content);
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var FormatterHelper $formatter */
        $formatter = $this->getHelper('formatter');
        //        $process = new Process('wkhtmltopdf http://google.com/ test.pdf');
        //        $process->run();
        //        $process->stop(3, SIGINT);
        //        $process->mustRun(function ($type, $message) use ($output, $formatter) {
        //            if ($type === Process::ERR) {
        //                $output->writeln($formatter->formatBlock($message, 'error'));
        //            } else {
        //                $output->writeln($formatter->formatBlock($message, 'comment'));
        //            }
        //        });
        $process = new PhpProcess(<<<EOF
        <?php
            sleep(5);
            echo "OK
";
        ?>
EOF
);
        $process->start();
        $process->stop(2, SIGINT);
        if (!$process->isSuccessful()) {
            $output->writeln($formatter->formatBlock($process->getErrorOutput(), 'error', true));
            return;
        }
        $output->writeln($formatter->formatSection('success', $process->getOutput()));
    }
Esempio n. 12
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getArgument('filename');
     if (null !== $filename) {
         $filename = $this->getSnippetsPath() . DIRECTORY_SEPARATOR . $filename;
         if (!file_exists($filename)) {
             throw new InvalidArgumentException(sprintf('file "%s" does not exist', $filename));
         }
         $snippets = array(new \SplFileInfo($filename));
         $nbSnippets = 1;
     } else {
         $snippets = $this->listSnippets(new Finder());
         $nbSnippets = count($snippets->getIterator()->getIterator());
     }
     $dialog = $this->getHelperSet()->get('dialog');
     $i = 0;
     foreach ($snippets as $snippet) {
         $snippetCode = file_get_contents($snippet->getRealpath());
         $output->writeln(sprintf('<info>DEMO [%d/%d]:</info> %s', $i + 1, $nbSnippets, $snippet->getRealPath()));
         $this->hr($output, 20);
         $output->writeln('<info>CODE :</info>');
         $output->writeln($snippetCode);
         $this->hr($output, 20);
         $dialog->askConfirmation($output, '<question>Press enter to see result</question>');
         $output->writeln('<info>RESULT :</info>');
         $process = new PhpProcess($snippetCode);
         $process->run();
         if (!$process->isSuccessful()) {
             $output->writeln(array('<error>Error ::</error>', $process->getErrorOutput()));
         }
         $output->writeln(array('<comment>Output ::</comment>', $process->getOutput()));
         $this->hr($output);
         $i++;
         if ($i < $nbSnippets) {
             $dialog->askConfirmation($output, '<question>Press enter to continue</question>');
             $output->writeln("");
         }
     }
 }
Esempio n. 13
0
 /**
  * Starts the web server.
  *
  * @param callable $callback An output function to call whenever there is
  *     a log entry made to the server.
  */
 public function start($callback = null)
 {
     // Find the PHP executable.
     if (false === ($php = $this->executableFinder->find())) {
         throw new \RuntimeException('Unable to find the PHP executable.');
     }
     $options = ' -S ' . $this->addr . ':' . $this->port;
     if (isset($this->documentRoot)) {
         $options .= ' -t ' . $this->documentRoot;
     }
     $this->setCommandLine($php . $options);
     parent::start($callback);
 }
Esempio n. 14
0
    public function testCommandLine()
    {
        $process = new PhpProcess(<<<'PHP'
<?php echo 'foobar';
PHP
);
        $commandLine = $process->getCommandLine();
        $f = new PhpExecutableFinder();
        $this->assertContains($f->find(), $commandLine, '::getCommandLine() returns the command line of PHP before start');
        $process->start();
        $this->assertContains($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after start');
        $process->wait();
        $this->assertContains($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after wait');
    }
Esempio n. 15
0
 /**
  * {@inheritdoc}
  */
 public function run(JobReportInterface $report)
 {
     try {
         $this->process->start();
         $this->savePid($this->process->getPid(), $report);
         while ($this->process->isRunning()) {
             // waiting for process to finish
         }
         if ($this->process->isSuccessful()) {
             $report->setOutput(trim($this->process->getOutput()));
             return JobState::STATE_FINISHED;
         }
         $report->setErrorOutput(trim($this->process->getErrorOutput()));
     } catch (LogicException $e) {
         $report->setErrorOutput($e->getMessage());
     } catch (RuntimeException $e) {
         $report->setErrorOutput($e->getMessage());
     }
     return JobState::STATE_FAILED;
 }
Esempio n. 16
0
    public function testCommandLine()
    {
        if ('phpdbg' === PHP_SAPI) {
            $this->markTestSkipped('phpdbg SAPI is not supported by this test.');
        }
        $process = new PhpProcess(<<<PHP
<?php echo 'foobar';
PHP
);
        $f = new PhpExecutableFinder();
        $commandLine = $f->find();
        $this->assertSame($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP before start');
        $process->start();
        $this->assertSame($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after start');
        $process->wait();
        $this->assertSame($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after wait');
    }
Esempio n. 17
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     // We set the TMPDIR (for Macs) and TEMP (for Windows), because on these platforms the temp directory changes based on the user.
     $process = new PhpProcess($this->getScript($request), null, array('TMPDIR' => sys_get_temp_dir(), 'TEMP' => sys_get_temp_dir()));
     $process->run();
     if (!$process->isSuccessful() || !preg_match('/^O\\:\\d+\\:/', $process->getOutput())) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return unserialize($process->getOutput());
 }
Esempio n. 18
0
 /**
  * The return value of the callable.
  *
  * @return mixed
  */
 public function getReturnValue()
 {
     $value = ClosureReturnValue::unserialize(parent::getOutput());
     return $value->getReturnValue();
 }
Esempio n. 19
0
 /**
  * @medium
  * @dataProvider backends
  */
 public function testCompressEventsKate($backend)
 {
     // CREATE web.scssdx1493.new
     // MODIFY web.scssdx1493.new
     // MOVED_FROM web.scssdx1493.new
     // MOVED_TO web.scss
     if (!$backend->isAvailable()) {
         $this->markTestSkipped();
     }
     $f = __DIR__ . '/test/';
     sleep(1);
     $php = "<?php sleep(2);\n        file_put_contents('{$f}foo.txtdx1493.new', 'x');\n        rename('{$f}foo.txtdx1493.new', '{$f}foo.txt');\n\n        file_put_contents('{$f}stop.txt', 'x');\n        ";
     $process = new PhpProcess($php);
     $process->start();
     $gotEvents = array();
     $backend->setPath(__DIR__ . '/test');
     $backend->addListener(ModifyEvent::NAME, function ($e) use(&$gotEvents, $backend) {
         $gotEvents[] = 'modify';
     });
     $backend->addListener(CreateEvent::NAME, function ($e) use(&$gotEvents, $backend) {
         if ($e->filename == __DIR__ . '/test/stop.txt') {
             $backend->stop();
         } else {
             $gotEvents[] = 'create';
         }
     });
     $backend->addListener(DeleteEvent::NAME, function ($e) use(&$gotEvents, $backend) {
         $gotEvents[] = 'delete';
     });
     $backend->addListener(MoveEvent::NAME, function ($e) use(&$gotEvents, $backend) {
         $gotEvents[] = 'move';
     });
     $backend->start();
     $process->wait();
     $this->assertTrue($process->isSuccessful());
     $this->assertEquals($gotEvents, array('modify'));
 }
 protected function loadRaw($model, $parsePhp = false)
 {
     $content = file_get_contents(sprintf(__DIR__ . '/%s.yml', $model));
     if ($parsePhp) {
         $process = new PhpProcess($content);
         $process->run();
         if (!$process->isSuccessful()) {
             throw new \RuntimeException($process->getErrorOutput());
         }
         $content = $process->getOutput();
     }
     return Yaml::parse($content);
 }
Esempio n. 21
0
    public function updateCanonicalConfigFile(Bundle $bundle)
    {
        self::$canonicalConfiguration = '';
        $gitRepo = $this->gitRepoManager->getRepo($bundle);
        /**
         * Currently there is only support for bundles whose configuration is stored exactly under Configuration.php
         */
        $relativePath = 'DependencyInjection' . DIRECTORY_SEPARATOR . 'Configuration.php';
        if ($gitRepo->hasFile($relativePath)) {
            $absolutePath = $gitRepo->getDir() . DIRECTORY_SEPARATOR . $relativePath;
            $tokens = token_get_all(file_get_contents($absolutePath));
            $start = false;
            $namespace = '';
            foreach ($tokens as $token) {
                if ($token == ';') {
                    break;
                }
                $tokenName = is_array($token) ? $token[0] : null;
                if (T_NAMESPACE === $tokenName) {
                    $start = true;
                    continue;
                }
                // Still not found namespace, skip this part of code
                if ($start === false) {
                    continue;
                }
                $tokenData = is_array($token) ? $token[1] : $token;
                if ($tokenData == ' ') {
                    continue;
                }
                $namespace .= $tokenData;
            }
            unset($tokens);
            $autoloaderPath = __DIR__ . '/../../../../../vendor/autoload.php';
            $script = <<<EOF
<?php

include_once "{$autoloaderPath}";
include_once "{$absolutePath}";

use Knp\\Bundle\\KnpBundlesBundle\\Github\\Repo;

\$configuration = new \\ReflectionClass("{$namespace}\\Configuration");
// only dumps if it implements interface ConfigurationInterface
if (in_array('Symfony\\Component\\Config\\Definition\\ConfigurationInterface', \$configuration->getInterfaceNames())) {
    \$configuration = \$configuration->newInstance();
    \$configuration = Repo::outputNode(\$configuration->getConfigTreeBuilder()->buildTree());

    echo Repo::\$canonicalConfiguration;
} else {
    echo '';
}

?>
EOF;
            // Workaround for bundles with external deps called in DI configuration, i.e. FOSRestBundle
            $process = new PhpProcess($script);
            $process->run();
            if ($process->isSuccessful()) {
                $bundle->setCanonicalConfig(Repo::$canonicalConfiguration = $process->getOutput());
            }
        }
    }
Esempio n. 22
0
    public function runSubProcessInstaller()
    {
        $script = <<<'EOF'
<?php
$_REQUEST['goto'] = 'SilentInstall';
$_REQUEST['cli'] = 'true';
require('install.php');
EOF;
        $output = '';
        $process = new PhpProcess($script, $this->getPath());
        // This will be a long process so we allow up to an hour.
        $process->setTimeout(3600);
        try {
            $process->mustRun(function ($type, $buffer) use(&$output) {
                $output .= $buffer;
            });
        } catch (ProcessFailedException $e) {
            throw new InstallerException('The installer sub process failed with the following output:' . PHP_EOL . $e->getMessage());
        }
        return $output;
    }
 private function addFallbackAutoloader($phpunitXml)
 {
     $xml = simplexml_load_file($phpunitXml);
     $bootstrap = dirname($phpunitXml) . '/' . $xml['bootstrap'];
     // The bootstrap file does not exists, we can't run the tests
     if (!file_exists($bootstrap)) {
         return false;
     }
     $content = file_get_contents($bootstrap);
     $newPath = sprintf('require_once \'%s\';', realpath(__DIR__ . '/../../../app/autoload.php'));
     // The bundle is trying to run tests into a symfony project, change it!
     if (preg_match('#require(../){2,}app/autoload.php["\'];$#i', $content, $match)) {
         $content = str_replace($match[0], $newPath, $content);
     } else {
         $content .= "\n" . $newPath;
     }
     file_put_contents($bootstrap, $content);
     // test if the bootstrap script can be runned
     $process = new PhpProcess($bootstrap);
     $process->run(function ($type, $data) {
         echo $data;
     });
     if (!$process->isSuccessful()) {
         return false;
     }
     $xml->filter->whitelist->exclude->directory[] = dirname($phpunitXml) . '/vendor';
     $xml->filter->whitelist->exclude->directory[] = dirname($phpunitXml) . '/vendors';
     $xml->asXml($phpunitXml);
     return true;
 }
Esempio n. 24
0
 /**
  * Makes a request in another process.
  *
  * @param Request $request A Request instance
  *
  * @return Response A Response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     $process = new PhpProcess($this->getScript($request));
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
     return unserialize($process->getOutput());
 }
Esempio n. 25
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     $process = new PhpProcess($this->getScript($request), null, null);
     $process->run();
     if (!$process->isSuccessful() || !preg_match('/^O\\:\\d+\\:/', $process->getOutput())) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return unserialize($process->getOutput());
 }
Esempio n. 26
0
    /**
     * Test if it is safe to use the PHP function openssl_x509_parse().
     *
     * This checks if OpenSSL extensions is vulnerable to remote code execution
     * via the exploit documented as CVE-2013-6420.
     *
     * @return bool
     */
    public static function isOpensslParseSafe()
    {
        if (null !== self::$useOpensslParse) {
            return self::$useOpensslParse;
        }
        if (PHP_VERSION_ID >= 50600) {
            return self::$useOpensslParse = true;
        }
        // Vulnerable:
        // PHP 5.3.0 - PHP 5.3.27
        // PHP 5.4.0 - PHP 5.4.22
        // PHP 5.5.0 - PHP 5.5.6
        if (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328 || PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423 || PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507) {
            // This version of PHP has the fix for CVE-2013-6420 applied.
            return self::$useOpensslParse = true;
        }
        if ('\\' === DIRECTORY_SEPARATOR) {
            // Windows is probably insecure in this case.
            return self::$useOpensslParse = false;
        }
        $compareDistroVersionPrefix = function ($prefix, $fixedVersion) {
            $regex = '{^' . preg_quote($prefix) . '([0-9]+)$}';
            if (preg_match($regex, PHP_VERSION, $m)) {
                return (int) $m[1] >= $fixedVersion;
            }
            return false;
        };
        // Hard coded list of PHP distributions with the fix backported.
        if ($compareDistroVersionPrefix('5.3.3-7+squeeze', 18) || $compareDistroVersionPrefix('5.4.4-14+deb7u', 7) || $compareDistroVersionPrefix('5.3.10-1ubuntu3.', 9)) {
            return self::$useOpensslParse = true;
        }
        // This is where things get crazy, because distros backport security
        // fixes the chances are on NIX systems the fix has been applied but
        // it's not possible to verify that from the PHP version.
        //
        // To verify exec a new PHP process and run the issue testcase with
        // known safe input that replicates the bug.
        // Based on testcase in https://github.com/php/php-src/commit/c1224573c773b6845e83505f717fbf820fc18415
        // changes in https://github.com/php/php-src/commit/76a7fd893b7d6101300cc656058704a73254d593
        $cert = 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVwRENDQTR5Z0F3SUJBZ0lKQUp6dThyNnU2ZUJjTUEwR0NTcUdTSWIzRFFFQkJRVUFNSUhETVFzd0NRWUQKVlFRR0V3SkVSVEVjTUJvR0ExVUVDQXdUVG05eVpISm9aV2x1TFZkbGMzUm1ZV3hsYmpFUU1BNEdBMVVFQnd3SApTOE9Ed3Jac2JqRVVNQklHQTFVRUNnd0xVMlZyZEdsdmJrVnBibk14SHpBZEJnTlZCQXNNRmsxaGJHbGphVzkxCmN5QkRaWEowSUZObFkzUnBiMjR4SVRBZkJnTlZCQU1NR0cxaGJHbGphVzkxY3k1elpXdDBhVzl1WldsdWN5NWsKWlRFcU1DZ0dDU3FHU0liM0RRRUpBUlliYzNSbFptRnVMbVZ6YzJWeVFITmxhM1JwYjI1bGFXNXpMbVJsTUhVWQpaREU1TnpBd01UQXhNREF3TURBd1dnQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEKQUFBQUFBQVhEVEUwTVRFeU9ERXhNemt6TlZvd2djTXhDekFKQmdOVkJBWVRBa1JGTVJ3d0dnWURWUVFJREJOTwpiM0prY21obGFXNHRWMlZ6ZEdaaGJHVnVNUkF3RGdZRFZRUUhEQWRMdzRQQ3RteHVNUlF3RWdZRFZRUUtEQXRUClpXdDBhVzl1UldsdWN6RWZNQjBHQTFVRUN3d1dUV0ZzYVdOcGIzVnpJRU5sY25RZ1UyVmpkR2x2YmpFaE1COEcKQTFVRUF3d1liV0ZzYVdOcGIzVnpMbk5sYTNScGIyNWxhVzV6TG1SbE1Tb3dLQVlKS29aSWh2Y05BUWtCRmh0egpkR1ZtWVc0dVpYTnpaWEpBYzJWcmRHbHZibVZwYm5NdVpHVXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCCkR3QXdnZ0VLQW9JQkFRRERBZjNobDdKWTBYY0ZuaXlFSnBTU0RxbjBPcUJyNlFQNjV1c0pQUnQvOFBhRG9xQnUKd0VZVC9OYSs2ZnNnUGpDMHVLOURaZ1dnMnRIV1dvYW5TYmxBTW96NVBINlorUzRTSFJaN2UyZERJalBqZGhqaAowbUxnMlVNTzV5cDBWNzk3R2dzOWxOdDZKUmZIODFNTjJvYlhXczROdHp0TE11RDZlZ3FwcjhkRGJyMzRhT3M4CnBrZHVpNVVhd1Raa3N5NXBMUEhxNWNNaEZHbTA2djY1Q0xvMFYyUGQ5K0tBb2tQclBjTjVLTEtlYno3bUxwazYKU01lRVhPS1A0aWRFcXh5UTdPN2ZCdUhNZWRzUWh1K3ByWTNzaTNCVXlLZlF0UDVDWm5YMmJwMHdLSHhYMTJEWAoxbmZGSXQ5RGJHdkhUY3lPdU4rblpMUEJtM3ZXeG50eUlJdlZBZ01CQUFHalFqQkFNQWtHQTFVZEV3UUNNQUF3CkVRWUpZSVpJQVliNFFnRUJCQVFEQWdlQU1Bc0dBMVVkRHdRRUF3SUZvREFUQmdOVkhTVUVEREFLQmdnckJnRUYKQlFjREFqQU5CZ2txaGtpRzl3MEJBUVVGQUFPQ0FRRUFHMGZaWVlDVGJkajFYWWMrMVNub2FQUit2SThDOENhRAo4KzBVWWhkbnlVNGdnYTBCQWNEclk5ZTk0ZUVBdTZacXljRjZGakxxWFhkQWJvcHBXb2NyNlQ2R0QxeDMzQ2tsClZBcnpHL0t4UW9oR0QySmVxa2hJTWxEb214SE83a2EzOStPYThpMnZXTFZ5alU4QVp2V01BcnVIYTRFRU55RzcKbFcyQWFnYUZLRkNyOVRuWFRmcmR4R1ZFYnY3S1ZRNmJkaGc1cDVTanBXSDErTXEwM3VSM1pYUEJZZHlWODMxOQpvMGxWajFLRkkyRENML2xpV2lzSlJvb2YrMWNSMzVDdGQwd1lCY3BCNlRac2xNY09QbDc2ZHdLd0pnZUpvMlFnClpzZm1jMnZDMS9xT2xOdU5xLzBUenprVkd2OEVUVDNDZ2FVK1VYZTRYT1Z2a2NjZWJKbjJkZz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K';
        $script = <<<'EOT'

error_reporting(-1);
$info = openssl_x509_parse(base64_decode('%s'));
var_dump(PHP_VERSION, $info['issuer']['emailAddress'], $info['validFrom_time_t']);

EOT;
        $script = '<' . "?php\n" . sprintf($script, $cert);
        try {
            $process = new PhpProcess($script);
            $process->mustRun();
        } catch (\Exception $e) {
            // In the case of any exceptions just accept it is not possible to
            // determine the safety of openssl_x509_parse and bail out.
            return self::$useOpensslParse = false;
        }
        $output = preg_split('{\\r?\\n}', trim($process->getOutput()));
        $errorOutput = trim($process->getErrorOutput());
        if (count($output) === 3 && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) && $output[1] === 'string(27) "*****@*****.**"' && $output[2] === 'int(-1)' && preg_match('{openssl_x509_parse\\(\\): illegal (?:ASN1 data type for|length in) timestamp in - on line \\d+}', $errorOutput)) {
            // This PHP has the fix backported probably by a distro security team.
            return self::$useOpensslParse = true;
        }
        return self::$useOpensslParse = false;
    }
Esempio n. 27
0
 public function getPid()
 {
     return $this->symfonyProcess->getPid();
 }
Esempio n. 28
0
    /**
     * Makes a request in another process.
     *
     * @param Request $request A Request instance
     *
     * @return Response A Response instance
     *
     * @throws \RuntimeException When processing returns exit code
     */
    protected function doRequestInProcess($request)
    {
        // We set the TMPDIR because on Macs, the temp directory changes based on the user.
        $process = new PhpProcess($this->getScript($request), null, array('TMPDIR' => sys_get_temp_dir()));
        $process->run();

        if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
            throw new \RuntimeException($process->getErrorOutput());
        }

        return unserialize($process->getOutput());
    }
Esempio n. 29
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  * @see \Symfony\Component\BrowserKit\Client
  * @see \Symfony\Component\HttpKernel\Client
  */
 protected function doRequestInProcess($request)
 {
     // We set the TMPDIR (for Macs) and TEMP (for Windows), because on these platforms the temp directory changes based on the user.
     $process = new PhpProcess($this->getScript($request), $this->rootDir, array('TMPDIR' => sys_get_temp_dir(), 'TEMP' => sys_get_temp_dir()));
     $process->setPhpBinary('php-cgi');
     $process->run();
     // I think the second hcheck validates that the response is serialized, but that's not what we want here.
     //if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
     if (!$process->isSuccessful()) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return $process->getOutput();
 }