From 26265f0b76e8f8e69af643bfefdb9d40090942af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Kure=C4=8Dka?= Date: Tue, 23 Nov 2021 23:48:02 +0100 Subject: [PATCH] Use random available port rather than randomly generated one --- .../Instance/Launcher.php | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/ChromeDevtoolsProtocol/Instance/Launcher.php b/src/ChromeDevtoolsProtocol/Instance/Launcher.php index 6794aaa4..7c02f6bc 100644 --- a/src/ChromeDevtoolsProtocol/Instance/Launcher.php +++ b/src/ChromeDevtoolsProtocol/Instance/Launcher.php @@ -40,16 +40,11 @@ class Launcher private $input; /** - * @param int $port If port <= 0, random port number is generated. - * @throws \Exception + * @param int $port If port <= 0, random available port is used. */ public function __construct($port = 0) { - if ($port <= 0) { - $port = random_int(1024 + 1, 65535); - } - - $this->port = $port; + $this->port = max(0, $port); } /** @@ -212,6 +207,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable, $temporaryUserDataDir = null; if (!$foundUserDataDir) { $temporaryUserDataDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "chrome-profile-" . $this->port; + if ($this->port === 0) { + $temporaryUserDataDir .= "-" . bin2hex(random_bytes(8)); + } + $fs->mkdir($temporaryUserDataDir); $args[] = "--user-data-dir=" . $temporaryUserDataDir; } @@ -226,6 +225,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable, ); $process->start(); + if ($this->port === 0) { + $process->waitUntil(function ($type, $buffer) { + if (preg_match('~DevTools listening on ws://.+:(\d+)/devtools~', $buffer, $m)) { + $this->port = (int)$m[1]; + return true; + } + return false; + }); + } + $instance = new ProcessInstance($process, $temporaryUserDataDir, $this->port); for (; ;) {