vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php

378 lines · 12464 bytes

  1<?php
  2
  3namespace GuzzleHttp\Cookie;
  4
  5use GuzzleHttp\Psr7;
  6use Psr\Http\Message\RequestInterface;
  7use Psr\Http\Message\ResponseInterface;
  8
  9/**
 10 * Cookie jar that stores cookies as an array
 11 */
 12class CookieJar implements CookieJarInterface
 13{
 14    private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
 15    private const MAX_SET_COOKIE_FIELDS = 50;
 16    private const MAX_REQUEST_COOKIES = 150;
 17    private const MAX_COOKIE_HEADER_LENGTH = 8190;
 18
 19    /**
 20     * @var SetCookie[] Loaded cookie data
 21     */
 22    private $cookies = [];
 23
 24    /**
 25     * @var bool
 26     */
 27    private $strictMode;
 28
 29    /**
 30     * @param bool  $strictMode  Set to true to throw exceptions when invalid
 31     *                           cookies are added to the cookie jar.
 32     * @param array $cookieArray Array of SetCookie objects or a hash of
 33     *                           arrays that can be used with the SetCookie
 34     *                           constructor
 35     */
 36    public function __construct(bool $strictMode = false, array $cookieArray = [])
 37    {
 38        $this->strictMode = $strictMode;
 39
 40        foreach ($cookieArray as $cookie) {
 41            if (!$cookie instanceof SetCookie) {
 42                $cookie = new SetCookie($cookie);
 43            }
 44            $this->setCookie($cookie);
 45        }
 46    }
 47
 48    /**
 49     * Create a new Cookie jar from an associative array and domain.
 50     *
 51     * @param array  $cookies Cookies to create the jar from
 52     * @param string $domain  Domain to set the cookies to
 53     */
 54    public static function fromArray(array $cookies, string $domain): self
 55    {
 56        $cookieJar = new self();
 57        foreach ($cookies as $name => $value) {
 58            $cookieJar->setCookie(new SetCookie([
 59                'Domain' => $domain,
 60                'Name' => $name,
 61                'Value' => $value,
 62                'Discard' => true,
 63            ]));
 64        }
 65
 66        return $cookieJar;
 67    }
 68
 69    /**
 70     * Evaluate if this cookie should be persisted to storage
 71     * that survives between requests.
 72     *
 73     * @param SetCookie $cookie              Being evaluated.
 74     * @param bool      $allowSessionCookies If we should persist session cookies
 75     */
 76    public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
 77    {
 78        if ($cookie->getExpires() || $allowSessionCookies) {
 79            if (!$cookie->getDiscard()) {
 80                return true;
 81            }
 82        }
 83
 84        return false;
 85    }
 86
 87    /**
 88     * Finds and returns the cookie based on the name
 89     *
 90     * @param string $name cookie name to search for
 91     *
 92     * @return SetCookie|null cookie that was found or null if not found
 93     */
 94    public function getCookieByName(string $name): ?SetCookie
 95    {
 96        foreach ($this->cookies as $cookie) {
 97            if ($cookie->getName() !== null && Psr7\Utils::caselessEquals($cookie->getName(), $name)) {
 98                return $cookie;
 99            }
100        }
101
102        return null;
103    }
104
105    public function toArray(): array
106    {
107        return \array_map(static function (SetCookie $cookie): array {
108            return $cookie->toArray();
109        }, $this->getIterator()->getArrayCopy());
110    }
111
112    public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
113    {
114        if ($domain === null) {
115            $this->cookies = [];
116
117            return;
118        } elseif ($path === null) {
119            $this->cookies = \array_filter(
120                $this->cookies,
121                static function (SetCookie $cookie) use ($domain): bool {
122                    return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
123                }
124            );
125        } elseif ($name === null) {
126            $this->cookies = \array_filter(
127                $this->cookies,
128                static function (SetCookie $cookie) use ($path, $domain): bool {
129                    return !($cookie->getDomain() !== null
130                        && $cookie->matchesPath($path)
131                        && $cookie->matchesDomain($domain));
132                }
133            );
134        } else {
135            $this->cookies = \array_filter(
136                $this->cookies,
137                static function (SetCookie $cookie) use ($path, $domain, $name) {
138                    return !($cookie->getDomain() !== null
139                        && $cookie->getName() === $name
140                        && $cookie->matchesPath($path)
141                        && $cookie->matchesDomain($domain));
142                }
143            );
144        }
145    }
146
147    public function clearSessionCookies(): void
148    {
149        $this->cookies = \array_filter(
150            $this->cookies,
151            static function (SetCookie $cookie): bool {
152                return !$cookie->getDiscard() && $cookie->getExpires();
153            }
154        );
155    }
156
157    public function setCookie(SetCookie $cookie): bool
158    {
159        // If the name string is empty (but not 0), ignore the set-cookie
160        // string entirely.
161        $name = $cookie->getName();
162        if (!$name && $name !== '0') {
163            return false;
164        }
165
166        // Only allow cookies with set and valid domain, name, value
167        $result = $cookie->validate();
168        if ($result !== true) {
169            if ($this->strictMode) {
170                throw new \RuntimeException('Invalid cookie: '.$result);
171            }
172            $this->removeCookieIfEmpty($cookie);
173
174            return false;
175        }
176
177        $maxAge = $cookie->getMaxAge();
178        if ($maxAge !== null && $maxAge <= 0) {
179            if ($cookie->getDomain() !== null) {
180                $this->removeCookie($cookie);
181            }
182
183            return false;
184        }
185
186        // Resolve conflicts with previously set cookies
187        foreach ($this->cookies as $i => $c) {
188            // Two cookies are identical, when their path, and domain are
189            // identical.
190            if ($c->getPath() !== $cookie->getPath()
191                || $c->getDomain() !== $cookie->getDomain()
192                || $c->getHostOnly() !== $cookie->getHostOnly()
193                || $c->getName() !== $cookie->getName()
194            ) {
195                continue;
196            }
197
198            // The previously set cookie is a discard cookie and this one is
199            // not so allow the new cookie to be set
200            if (!$cookie->getDiscard() && $c->getDiscard()) {
201                unset($this->cookies[$i]);
202                continue;
203            }
204
205            // If the new cookie's expiration is further into the future, then
206            // replace the old cookie
207            if ($cookie->getExpires() > $c->getExpires()) {
208                unset($this->cookies[$i]);
209                continue;
210            }
211
212            // If the value has changed, we better change it
213            if ($cookie->getValue() !== $c->getValue()) {
214                unset($this->cookies[$i]);
215                continue;
216            }
217
218            // The cookie exists, so no need to continue
219            return false;
220        }
221
222        $this->cookies[] = $cookie;
223
224        return true;
225    }
226
227    public function count(): int
228    {
229        return \count($this->cookies);
230    }
231
232    /**
233     * @return \ArrayIterator<int, SetCookie>
234     */
235    public function getIterator(): \ArrayIterator
236    {
237        return new \ArrayIterator(\array_values($this->cookies));
238    }
239
240    public function extractCookies(RequestInterface $request, ResponseInterface $response): void
241    {
242        if ($cookieHeader = $response->getHeader('Set-Cookie')) {
243            $accepted = 0;
244            foreach ($cookieHeader as $cookie) {
245                if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
246                    continue;
247                }
248
249                $sc = SetCookie::fromString($cookie);
250                $domain = $sc->getDomain();
251                if ($domain === null || $domain === '') {
252                    $sc->setDomain($request->getUri()->getHost());
253                    $sc->setHostOnly(true);
254                } elseif (\substr($domain, -1) === '.' && '' !== \trim($domain, '.')) {
255                    // Keep pure-dot domains rejected by the dot-only fix.
256                    $sc->setDomain($request->getUri()->getHost());
257                    $sc->setHostOnly(true);
258                } else {
259                    $sc->setHostOnly(false);
260                }
261                if (0 !== \strpos($sc->getPath(), '/')) {
262                    $sc->setPath($this->getCookiePathFromRequest($request));
263                }
264                if (!$sc->matchesDomain($request->getUri()->getHost())) {
265                    continue;
266                }
267                // Note: At this point `$sc->getDomain()` being a public suffix should
268                // be rejected, but we don't want to pull in the full PSL dependency.
269                if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
270                    break;
271                }
272            }
273        }
274    }
275
276    /**
277     * Computes cookie path following RFC 6265 section 5.1.4
278     *
279     * @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
280     */
281    private function getCookiePathFromRequest(RequestInterface $request): string
282    {
283        $uriPath = $request->getUri()->getPath();
284        if ('' === $uriPath) {
285            return '/';
286        }
287        if (0 !== \strpos($uriPath, '/')) {
288            return '/';
289        }
290        if ('/' === $uriPath) {
291            return '/';
292        }
293        $lastSlashPos = \strrpos($uriPath, '/');
294        if (0 === $lastSlashPos || false === $lastSlashPos) {
295            return '/';
296        }
297
298        return \substr($uriPath, 0, $lastSlashPos);
299    }
300
301    public function withCookieHeader(RequestInterface $request): RequestInterface
302    {
303        $values = [];
304        $headerLength = 8;
305        $uri = $request->getUri();
306        $scheme = $uri->getScheme();
307        $host = $uri->getHost();
308        $path = $uri->getPath() ?: '/';
309
310        foreach ($this->cookies as $cookie) {
311            if ($cookie->getDomain() !== null
312                && $cookie->matchesPath($path)
313                && $cookie->matchesDomain($host)
314                && !$cookie->isExpired()
315                && (!$cookie->getSecure() || $scheme === 'https')
316            ) {
317                $name = (string) $cookie->getName();
318                $value = (string) $cookie->getValue();
319                $separatorLength = $values === [] ? 0 : 2;
320                $valueLength = \strlen($name) + 1 + \strlen($value);
321                if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
322                    break;
323                }
324
325                $values[] = $name.'='.$value;
326                $headerLength += $separatorLength + $valueLength;
327                if (\count($values) === self::MAX_REQUEST_COOKIES) {
328                    break;
329                }
330            }
331        }
332
333        return $values
334            ? $request->withHeader('Cookie', \implode('; ', $values))
335            : $request;
336    }
337
338    /**
339     * If a cookie already exists and the server asks to set it again with a
340     * null value, the cookie must be deleted.
341     */
342    private function removeCookieIfEmpty(SetCookie $cookie): void
343    {
344        $cookieValue = $cookie->getValue();
345        if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
346            $this->removeCookie($cookie);
347        }
348    }
349
350    private function removeCookie(SetCookie $cookie): void
351    {
352        $this->cookies = \array_filter(
353            $this->cookies,
354            static function (SetCookie $stored) use ($cookie): bool {
355                return !($stored->getName() === $cookie->getName()
356                    && $stored->getPath() === $cookie->getPath()
357                    && self::cookieDomainsEqual($stored->getDomain(), $cookie->getDomain())
358                    && $stored->getHostOnly() === $cookie->getHostOnly());
359            }
360        );
361    }
362
363    private static function cookieDomainsEqual(?string $first, ?string $second): bool
364    {
365        if ($first === null || $second === null) {
366            return $first === $second;
367        }
368
369        if (isset($first[0]) && $first[0] === '.') {
370            $first = \substr($first, 1);
371        }
372        if (isset($second[0]) && $second[0] === '.') {
373            $second = \substr($second, 1);
374        }
375
376        return Psr7\Utils::caselessEquals($first, $second);
377    }
378}