Coverage Report

Created: 2026-10-15 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/cookie.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
27
28
#include "urldata.h"
29
#include "cookie.h"
30
#include "psl.h"
31
#include "curl_trc.h"
32
#include "transfer.h"
33
#include "slist.h"
34
#include "curl_share.h"
35
#include "strcase.h"
36
#include "curl_fopen.h"
37
#include "curl_get_line.h"
38
#include "curl_memrchr.h"
39
#include "parsedate.h"
40
#include "curlx/strdup.h"
41
#include "llist.h"
42
#include "curlx/strparse.h"
43
44
/* number of seconds in 400 days */
45
9.02k
#define COOKIES_MAXAGE (400 * 24 * 3600)
46
47
/* Make sure cookies never expire further away in time than 400 days into the
48
   future. (from RFC6265bis draft-19)
49
50
   For the sake of easier testing, align the capped time to an even 60 second
51
   boundary. */
52
static void cap_expires(time_t now, struct Cookie *co)
53
27.9k
{
54
27.9k
  if(co->expires && (TIME_T_MAX - COOKIES_MAXAGE - 30) > now) {
55
4.51k
    timediff_t cap = now + COOKIES_MAXAGE;
56
4.51k
    if(co->expires > cap) {
57
911
      cap += 30;
58
911
      co->expires = (cap / 60) * 60;
59
911
    }
60
4.51k
  }
61
27.9k
}
62
63
static void freecookie(struct Cookie *co, bool maintoo)
64
38.0k
{
65
38.0k
  curlx_free(co->domain);
66
38.0k
  curlx_free(co->path);
67
38.0k
  curlx_free(co->name);
68
38.0k
  curlx_free(co->value);
69
38.0k
  if(maintoo)
70
13.5k
    curlx_free(co);
71
38.0k
}
72
73
static bool cookie_tailmatch(const char *cookie_domain,
74
                             const size_t cookie_domain_len,
75
                             const char *hostname)
76
20.4k
{
77
20.4k
  size_t hostname_len = strlen(hostname);
78
79
20.4k
  if(hostname_len < cookie_domain_len)
80
1.29k
    return FALSE;
81
82
19.1k
  if(!curl_strnequal(cookie_domain,
83
19.1k
                     hostname + hostname_len - cookie_domain_len,
84
19.1k
                     cookie_domain_len))
85
542
    return FALSE;
86
87
  /*
88
   * A lead char of cookie_domain is not '.'.
89
   * RFC6265 4.1.2.3. The Domain Attribute says:
90
   * For example, if the value of the Domain attribute is
91
   * "example.com", the user agent will include the cookie in the Cookie
92
   * header when making HTTP requests to example.com, www.example.com, and
93
   * www.corp.example.com.
94
   */
95
18.6k
  if(hostname_len == cookie_domain_len)
96
17.0k
    return TRUE;
97
1.58k
  if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
98
1.02k
    return TRUE;
99
560
  return FALSE;
100
1.58k
}
101
102
/*
103
 * matching cookie path and URL path
104
 * RFC6265 5.1.4 Paths and Path-Match
105
 */
106
static bool pathmatch(const char *cookie_path, const char *uri_path)
107
0
{
108
0
  size_t cookie_path_len;
109
0
  size_t uri_path_len;
110
0
  bool ret = FALSE;
111
112
  /* cookie_path must not have last '/' separator. ex: /sample */
113
0
  cookie_path_len = strlen(cookie_path);
114
0
  if(cookie_path_len == 1) {
115
    /* cookie_path must be '/' */
116
0
    return TRUE;
117
0
  }
118
119
  /* #-fragments are already cut off! */
120
0
  if(strlen(uri_path) == 0 || uri_path[0] != '/')
121
0
    uri_path = "/";
122
123
  /*
124
   * here, RFC6265 5.1.4 says
125
   *  4. Output the characters of the uri-path from the first character up
126
   *     to, but not including, the right-most %x2F ("/").
127
   *  but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
128
   *  without redirect.
129
   *  Ignore this algorithm because /hoge is uri path for this case
130
   *  (uri path is not /).
131
   */
132
133
0
  uri_path_len = strlen(uri_path);
134
135
0
  if(uri_path_len < cookie_path_len)
136
0
    goto pathmatched;
137
138
  /* not using checkprefix() because matching should be case-sensitive */
139
0
  if(strncmp(cookie_path, uri_path, cookie_path_len))
140
0
    goto pathmatched;
141
142
  /* The cookie-path and the uri-path are identical. */
143
0
  if(cookie_path_len == uri_path_len) {
144
0
    ret = TRUE;
145
0
    goto pathmatched;
146
0
  }
147
148
  /* here, cookie_path_len < uri_path_len */
149
0
  if(uri_path[cookie_path_len] == '/') {
150
0
    ret = TRUE;
151
0
    goto pathmatched;
152
0
  }
153
154
0
pathmatched:
155
0
  return ret;
156
0
}
157
158
/*
159
 * Return the top-level domain, for optimal hashing.
160
 */
161
static const char *get_top_domain(const char * const domain, size_t *outlen)
162
14.0k
{
163
14.0k
  size_t len = 0;
164
14.0k
  const char *first = NULL, *last;
165
166
14.0k
  if(domain) {
167
14.0k
    len = strlen(domain);
168
14.0k
    last = memrchr(domain, '.', len);
169
14.0k
    if(last) {
170
4.73k
      first = memrchr(domain, '.', (last - domain));
171
4.73k
      if(first)
172
3.85k
        len -= (++first - domain);
173
4.73k
    }
174
14.0k
  }
175
176
14.0k
  if(outlen)
177
14.0k
    *outlen = len;
178
179
14.0k
  return first ? first : domain;
180
14.0k
}
181
182
/* Avoid C1001, an "internal error" with MSVC14 */
183
#if defined(_MSC_VER) && (_MSC_VER == 1900)
184
#pragma optimize("", off)
185
#endif
186
187
/*
188
 * A case-insensitive hash for the cookie domains.
189
 */
190
static size_t cookie_hash_domain(const char *domain, const size_t len)
191
14.0k
{
192
14.0k
  const char *end = domain + len;
193
14.0k
  size_t h = 5381;
194
195
46.4k
  while(domain < end) {
196
32.4k
    size_t j = (size_t)Curl_raw_toupper(*domain++);
197
32.4k
    h += h << 5;
198
32.4k
    h ^= j;
199
32.4k
  }
200
201
14.0k
  return (h % COOKIE_HASH_SIZE);
202
14.0k
}
203
204
#if defined(_MSC_VER) && (_MSC_VER == 1900)
205
#pragma optimize("", on)
206
#endif
207
208
/*
209
 * Hash this domain.
210
 */
211
static size_t cookiehash(const char * const domain)
212
27.1k
{
213
27.1k
  const char *top;
214
27.1k
  size_t len;
215
216
27.1k
  if(!domain || Curl_host_is_ipnum(domain))
217
13.1k
    return 0;
218
219
14.0k
  top = get_top_domain(domain, &len);
220
14.0k
  return cookie_hash_domain(top, len);
221
27.1k
}
222
223
/*
224
 * cookie path sanitize
225
 */
226
static char *sanitize_cookie_path(const char *cookie_path, size_t len)
227
12.0k
{
228
  /* some sites send path attribute within '"'. */
229
12.0k
  if(len && (cookie_path[0] == '\"')) {
230
238
    cookie_path++;
231
238
    len--;
232
233
238
    if(len && (cookie_path[len - 1] == '\"'))
234
67
      len--;
235
238
  }
236
237
  /* RFC6265 5.2.4 The Path Attribute */
238
12.0k
  if(!len || (cookie_path[0] != '/'))
239
    /* Let cookie-path be the default-path. */
240
282
    return curlx_strdup("/");
241
242
  /* remove trailing slash when path is non-empty */
243
  /* convert /hoge/ to /hoge */
244
11.8k
  if(len > 1 && cookie_path[len - 1] == '/')
245
1.99k
    len--;
246
247
11.8k
  return curlx_memdup0(cookie_path, len);
248
12.0k
}
249
250
/*
251
 * strstore
252
 *
253
 * A thin wrapper around curlx_memdup0().
254
 */
255
static CURLcode strstore(char **str, const char *newstr, size_t len)
256
28.0k
{
257
28.0k
  DEBUGASSERT(str);
258
28.0k
  *str = curlx_memdup0(newstr, len);
259
28.0k
  if(!*str)
260
0
    return CURLE_OUT_OF_MEMORY;
261
28.0k
  return CURLE_OK;
262
28.0k
}
263
264
/*
265
 * remove_expired
266
 *
267
 * Remove expired cookies from the hash by inspecting the expires timestamp on
268
 * each cookie in the hash, freeing and deleting any where the timestamp is in
269
 * the past. If the cookiejar has recorded the next timestamp at which one or
270
 * more cookies expire, then processing will exit early in case this timestamp
271
 * is in the future.
272
 */
273
static void remove_expired(struct CookieInfo *ci)
274
49.5k
{
275
49.5k
  struct Cookie *co;
276
49.5k
  curl_off_t now = (curl_off_t)time(NULL);
277
49.5k
  unsigned int i;
278
279
  /*
280
   * If the earliest expiration timestamp in the jar is in the future we can
281
   * skip scanning the whole jar and instead exit early as there will not be
282
   * any cookies to evict. If we need to evict, reset the next_expiration
283
   * counter in order to track the next one. In case the recorded first
284
   * expiration is the max offset, then perform the safe fallback of checking
285
   * all cookies.
286
   */
287
49.5k
  if(now < ci->next_expiration &&
288
48.7k
     ci->next_expiration != CURL_OFF_T_MAX)
289
2.48k
    return;
290
47.0k
  else
291
47.0k
    ci->next_expiration = CURL_OFF_T_MAX;
292
293
3.01M
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
294
2.96M
    struct Curl_llist_node *n;
295
2.96M
    struct Curl_llist_node *e = NULL;
296
297
3.01M
    for(n = Curl_llist_head(&ci->cookielist[i]); n; n = e) {
298
48.7k
      co = Curl_node_elem(n);
299
48.7k
      e = Curl_node_next(n);
300
48.7k
      if(co->expires) {
301
3.35k
        if(co->expires < now) {
302
845
          Curl_node_remove(n);
303
845
          freecookie(co, TRUE);
304
845
          ci->numcookies--;
305
845
        }
306
2.51k
        else if(co->expires < ci->next_expiration)
307
          /*
308
           * If this cookie has an expiration timestamp earlier than what we
309
           * have seen so far then record it for the next round of expirations.
310
           */
311
779
          ci->next_expiration = co->expires;
312
3.35k
      }
313
48.7k
    }
314
2.96M
  }
315
47.0k
}
316
317
#ifndef USE_LIBPSL
318
/* Make sure domain contains a dot or is localhost. */
319
static bool bad_domain(const char *domain, size_t len)
320
2.29k
{
321
2.29k
  if((len == 9) && curl_strnequal(domain, "localhost", 9))
322
66
    return FALSE;
323
2.22k
  else {
324
    /* there must be a dot present, but that dot must not be a trailing dot */
325
2.22k
    const char *dot = memchr(domain, '.', len);
326
2.22k
    if(dot) {
327
1.66k
      size_t i = dot - domain;
328
1.66k
      if((len - i) > 1)
329
        /* the dot is not the last byte */
330
1.59k
        return FALSE;
331
1.66k
    }
332
2.22k
  }
333
627
  return TRUE;
334
2.29k
}
335
#endif
336
337
/* RFC 6265 section 4.1.1 says a server should accept this range:
338
339
   cookie-octet    = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
340
341
   Yet, Firefox and Chrome as of June 2022 accept space, comma and
342
   double-quotes fine. The prime reason for filtering out control bytes is that
343
   some HTTP servers return 400 for requests that contain such.
344
 */
345
static bool invalid_octets(const char *ptr, size_t len)
346
143k
{
347
143k
  const unsigned char *p = (const unsigned char *)ptr;
348
  /* Reject all bytes \x01 - \x1f + \x7f */
349
1.31M
  while(len && *p) {
350
1.17M
    if((*p < 0x20) || (*p == 0x7f))
351
3.08k
      return TRUE;
352
1.17M
    p++;
353
1.17M
    len--;
354
1.17M
  }
355
139k
  return FALSE;
356
143k
}
357
358
/* The maximum length we accept a date string for the 'expire' keyword. The
359
   standard date formats are within the 30 bytes range. This adds an extra
360
   margin to make sure it realistically works with what is used out there. */
361
24.8k
#define MAX_DATE_LENGTH 80
362
363
15.6k
#define COOKIE_NAME   0
364
15.6k
#define COOKIE_VALUE  1
365
2.29k
#define COOKIE_DOMAIN 2
366
1.67k
#define COOKIE_PATH   3
367
368
#define COOKIE_PIECES 4 /* the list above */
369
370
static CURLcode storecookie(struct Cookie *co, const struct Curl_str *cp,
371
                            const char *path, const char *domain)
372
13.7k
{
373
13.7k
  CURLcode result;
374
13.7k
  result = strstore(&co->name, curlx_str(&cp[COOKIE_NAME]),
375
13.7k
                    curlx_strlen(&cp[COOKIE_NAME]));
376
13.7k
  if(!result)
377
13.7k
    result = strstore(&co->value, curlx_str(&cp[COOKIE_VALUE]),
378
13.7k
                      curlx_strlen(&cp[COOKIE_VALUE]));
379
13.7k
  if(!result) {
380
13.7k
    size_t plen = 0;
381
13.7k
    if(curlx_strlen(&cp[COOKIE_PATH])) {
382
1.28k
      path = curlx_str(&cp[COOKIE_PATH]);
383
1.28k
      plen = curlx_strlen(&cp[COOKIE_PATH]);
384
1.28k
    }
385
12.4k
    else if(path) {
386
      /* No path was given in the header line, set the default */
387
10.7k
      const char *endslash = strrchr(path, '/');
388
10.7k
      if(endslash)
389
10.7k
        plen = endslash - path + 1; /* include end slash */
390
0
      else
391
0
        plen = strlen(path);
392
10.7k
    }
393
394
13.7k
    if(path) {
395
12.0k
      co->path = sanitize_cookie_path(path, plen);
396
12.0k
      if(!co->path)
397
0
        result = CURLE_OUT_OF_MEMORY;
398
12.0k
    }
399
13.7k
  }
400
13.7k
  if(!result) {
401
13.7k
    if(curlx_strlen(&cp[COOKIE_DOMAIN]))
402
517
      result = strstore(&co->domain, curlx_str(&cp[COOKIE_DOMAIN]),
403
517
                        curlx_strlen(&cp[COOKIE_DOMAIN]));
404
13.2k
    else if(domain) {
405
      /* no domain was given in the header line, set the default */
406
11.6k
      co->domain = curlx_strdup(domain);
407
11.6k
      if(!co->domain)
408
0
        result = CURLE_OUT_OF_MEMORY;
409
11.6k
    }
410
13.7k
  }
411
13.7k
  return result;
412
13.7k
}
413
414
/*
415
 * Parse the first name/value pair of the cookie header, which is the actual
416
 * cookie name and value.
417
 */
418
static bool parse_first_pair(struct Curl_easy *data, struct Cookie *co,
419
                             struct Curl_str *cookie,
420
                             struct Curl_str *name,
421
                             struct Curl_str *val,
422
                             bool sep)
423
17.0k
{
424
  /* The first name/value pair is the actual cookie name */
425
17.0k
  if(!sep || !curlx_strlen(name)) {
426
1.33k
    infof(data, "invalid cookie, dropped");
427
1.33k
    return FALSE;
428
1.33k
  }
429
430
  /*
431
   * Check for too long individual name or contents. Chrome and Firefox
432
   * support 4095 or 4096 bytes combo
433
   */
434
15.6k
  if((curlx_strlen(name) + curlx_strlen(val)) > MAX_NAME) {
435
10
    infof(data, "oversized cookie dropped, name/val %zu + %zu bytes",
436
10
          curlx_strlen(name), curlx_strlen(val));
437
10
    return FALSE;
438
10
  }
439
440
  /* Check if we have a reserved prefix set. */
441
15.6k
  if(!strncmp("__Secure-", curlx_str(name), 9))
442
625
    co->prefix_secure = TRUE;
443
15.0k
  else if(!strncmp("__Host-", curlx_str(name), 7))
444
409
    co->prefix_host = TRUE;
445
446
15.6k
  cookie[COOKIE_NAME] = *name;
447
15.6k
  cookie[COOKIE_VALUE] = *val;
448
15.6k
  return TRUE;
449
15.6k
}
450
451
static bool parse_domain(struct Curl_easy *data, struct Cookie *co,
452
                         struct Curl_str *cookie_domain,
453
                         struct Curl_str *val,
454
                         const char **domainp)
455
2.29k
{
456
2.29k
  bool is_ip;
457
2.29k
  const char *domain = *domainp;
458
2.29k
  const char *v = curlx_str(val);
459
  /*
460
   * Now, we make sure that our host is within the given domain, or
461
   * the given domain is not valid and thus cannot be set.
462
   */
463
464
2.29k
  if('.' == *v)
465
927
    curlx_str_nudge(val, 1);
466
467
2.29k
#ifndef USE_LIBPSL
468
  /*
469
   * Without PSL we do not know when the incoming cookie is set on a
470
   * TLD or otherwise "protected" suffix. To reduce risk, we require a
471
   * dot OR the exact hostname being "localhost".
472
   */
473
2.29k
  if(bad_domain(curlx_str(val), curlx_strlen(val))) {
474
627
    *domainp = ":";
475
627
    domain = ":";
476
627
  }
477
2.29k
#endif
478
479
2.29k
  is_ip = Curl_host_is_ipnum(domain ? domain : curlx_str(val));
480
481
2.29k
  if(!domain ||
482
1.53k
     (is_ip &&
483
305
      !strncmp(curlx_str(val), domain, curlx_strlen(val)) &&
484
166
      (curlx_strlen(val) == strlen(domain))) ||
485
1.44k
     (!is_ip && cookie_tailmatch(curlx_str(val),
486
1.52k
                                  curlx_strlen(val), domain))) {
487
1.52k
    *cookie_domain = *val;
488
1.52k
    if(!is_ip)
489
1.43k
      co->tailmatch = TRUE; /* we always do that if the domain name was
490
                               given */
491
1.52k
  }
492
763
  else {
493
    /*
494
     * We did not get a tailmatch and then the attempted set domain is
495
     * not a domain to which the current host belongs. Mark as bad.
496
     */
497
763
    infof(data, "skipped cookie with bad tailmatch domain: %s",
498
763
          curlx_str(val));
499
763
    return FALSE;
500
763
  }
501
1.52k
  return TRUE;
502
2.29k
}
503
504
static void parse_maxage(struct Cookie *co, struct Curl_str *val,
505
                         time_t *nowp)
506
3.08k
{
507
3.08k
  int rc;
508
3.08k
  const char *maxage = curlx_str(val);
509
3.08k
  if(*maxage == '\"')
510
339
    maxage++;
511
3.08k
  rc = curlx_str_number(&maxage, &co->expires, CURL_OFF_T_MAX);
512
3.08k
  if(!*nowp)
513
851
    *nowp = time(NULL);
514
3.08k
  switch(rc) {
515
85
  case STRE_OVERFLOW:
516
    /* overflow, used max value */
517
85
    co->expires = CURL_OFF_T_MAX;
518
85
    break;
519
792
  default:
520
    /* negative or otherwise bad, expire */
521
792
    co->expires = 1;
522
792
    break;
523
2.20k
  case STRE_OK:
524
2.20k
    if(!co->expires)
525
521
      co->expires = 1; /* expire now */
526
1.68k
    else if(CURL_OFF_T_MAX - *nowp < co->expires)
527
      /* would overflow */
528
78
      co->expires = CURL_OFF_T_MAX;
529
1.61k
    else
530
1.61k
      co->expires += *nowp;
531
2.20k
    break;
532
3.08k
  }
533
3.08k
  cap_expires(*nowp, co);
534
3.08k
}
535
536
static void parse_expires(struct Cookie *co, struct Curl_str *val,
537
                          time_t *nowp)
538
25.3k
{
539
  /*
540
   * Let max-age have priority.
541
   *
542
   * If the date cannot get parsed for whatever reason, the cookie
543
   * will be treated as a session cookie
544
   */
545
25.3k
  if(!co->expires && (curlx_strlen(val) < MAX_DATE_LENGTH)) {
546
24.8k
    char dbuf[MAX_DATE_LENGTH + 1];
547
24.8k
    time_t date = 0;
548
24.8k
    memcpy(dbuf, curlx_str(val), curlx_strlen(val));
549
24.8k
    dbuf[curlx_strlen(val)] = 0;
550
24.8k
    if(!Curl_getdate_capped(dbuf, &date)) {
551
1.42k
      if(!date)
552
1
        date++;
553
1.42k
      co->expires = (curl_off_t)date;
554
1.42k
    }
555
23.3k
    else
556
23.3k
      co->expires = 0;
557
24.8k
    if(!*nowp)
558
2.95k
      *nowp = time(NULL);
559
24.8k
    cap_expires(*nowp, co);
560
24.8k
  }
561
25.3k
}
562
563
/* this function returns errors on OOM etc, not for cookie format problems */
564
static CURLcode
565
parse_cookie_header(struct Curl_easy *data,
566
                    struct Cookie *co,
567
                    bool *okay, /* if the cookie was fine */
568
                    const char *ptr, /* the header */
569
                    const char *domain, /* default domain */
570
                    /* full path used when this cookie is set */
571
                    const char *path,
572
                    bool secure_origin)
573
19.3k
{
574
  /* This line was read off an HTTP-header */
575
19.3k
  time_t now = 0;
576
19.3k
  size_t linelength = strlen(ptr);
577
19.3k
  CURLcode result = CURLE_OK;
578
19.3k
  struct Curl_str cookie[COOKIE_PIECES];
579
19.3k
  *okay = FALSE;
580
19.3k
  if(linelength > MAX_COOKIE_LINE)
581
    /* discard overly long lines at once */
582
105
    return CURLE_OK;
583
584
  /* memset instead of initializer because gcc 4.8.1 is silly */
585
19.2k
  memset(cookie, 0, sizeof(cookie));
586
81.4k
  do {
587
81.4k
    struct Curl_str name;
588
589
    /* we have a <name>=<value> pair or a stand-alone word here */
590
81.4k
    int rc = curlx_str_cspn(&ptr, &name, ";\r\n=");
591
81.4k
    if(!rc || (rc == STRE_SHORT)) {
592
81.4k
      struct Curl_str val;
593
81.4k
      bool sep = FALSE;
594
81.4k
      curlx_str_trimblanks(&name);
595
596
81.4k
      if(invalid_octets(curlx_str(&name), curlx_strlen(&name))) {
597
2.08k
        infof(data, "invalid octets in name, cookie dropped");
598
2.08k
        return CURLE_OK;
599
2.08k
      }
600
601
79.3k
      if(!curlx_str_single(&ptr, '=')) {
602
60.6k
        sep = TRUE; /* a '=' was used */
603
60.6k
        if(!curlx_str_cspn(&ptr, &val, ";\r\n"))
604
45.3k
          curlx_str_trimblanks(&val);
605
606
60.6k
        if(invalid_octets(curlx_str(&val), curlx_strlen(&val))) {
607
979
          infof(data, "invalid octets in value, cookie dropped");
608
979
          return CURLE_OK;
609
979
        }
610
60.6k
      }
611
18.7k
      else
612
18.7k
        curlx_str_init(&val);
613
614
78.3k
      if(!curlx_strlen(&cookie[COOKIE_NAME])) {
615
17.0k
        if(!parse_first_pair(data, co, cookie, &name, &val, sep))
616
1.34k
          return CURLE_OK;
617
17.0k
      }
618
619
      /* whether there's separator or not */
620
61.3k
      else if(curlx_str_casecompare(&name, "secure")) {
621
721
        if(secure_origin)
622
436
          co->secure = TRUE;
623
285
        else {
624
285
          infof(data, "skipped cookie because not 'secure'");
625
285
          return CURLE_OK;
626
285
        }
627
721
      }
628
60.6k
      else if(curlx_str_casecompare(&name, "httponly"))
629
195
        co->httponly = TRUE;
630
60.4k
      else if(sep) {
631
        /* only if a separating equals sign is present */
632
43.8k
        if(curlx_str_casecompare(&name, "path"))
633
1.67k
          cookie[COOKIE_PATH] = val;
634
42.1k
        else if(curlx_str_casecompare(&name, "domain")) {
635
2.50k
          if(curlx_strlen(&val) &&
636
2.29k
             !parse_domain(data, co, &cookie[COOKIE_DOMAIN], &val, &domain))
637
763
            return CURLE_OK;
638
2.50k
        }
639
39.6k
        else if(curlx_str_casecompare(&name, "max-age") && curlx_strlen(&val))
640
3.08k
          parse_maxage(co, &val, &now);
641
36.6k
        else if(curlx_str_casecompare(&name, "expires") && curlx_strlen(&val))
642
25.3k
          parse_expires(co, &val, &now);
643
43.8k
      }
644
78.3k
    }
645
81.4k
  } while(!curlx_str_single(&ptr, ';'));
646
647
13.7k
  if(curlx_strlen(&cookie[COOKIE_NAME])) {
648
    /* the header was fine, now store the data */
649
13.7k
    result = storecookie(co, &cookie[0], path, domain);
650
13.7k
    if(!result)
651
13.7k
      *okay = TRUE;
652
13.7k
  }
653
13.7k
  return result;
654
19.2k
}
655
656
static CURLcode parse_netscape(struct Cookie *co,
657
                               const struct CookieInfo *ci,
658
                               bool *okay,
659
                               const char *lineptr,
660
                               bool secure_origin)
661
18.7k
{
662
  /*
663
   * This line is NOT an HTTP header style line, we do offer support for
664
   * reading the odd netscape cookies-file format here
665
   */
666
18.7k
  const char *ptr, *next;
667
18.7k
  int fields;
668
18.7k
  size_t len;
669
18.7k
  *okay = FALSE;
670
671
  /*
672
   * In 2008, Internet Explorer introduced HTTP-only cookies to prevent XSS
673
   * attacks. Cookies marked httpOnly are not accessible to JavaScript. In
674
   * Firefox's cookie files, they are prefixed #HttpOnly_ and the rest
675
   * remains as usual, so we skip 10 characters of the line.
676
   */
677
18.7k
  if(!strncmp(lineptr, "#HttpOnly_", 10)) {
678
7
    lineptr += 10;
679
7
    co->httponly = TRUE;
680
7
  }
681
682
18.7k
  if(lineptr[0] == '#')
683
    /* do not even try the comments */
684
54
    return CURLE_OK;
685
686
  /*
687
   * Now loop through the fields and init the struct we already have
688
   * allocated
689
   */
690
18.6k
  fields = 0;
691
40.1k
  for(next = lineptr; next; fields++) {
692
21.5k
    ptr = next;
693
21.5k
    len = strcspn(ptr, "\t\r\n");
694
21.5k
    next = (ptr[len] == '\t' ? &ptr[len + 1] : NULL);
695
21.5k
    switch(fields) {
696
18.6k
    case 0:
697
18.6k
      if(ptr[0] == '.') { /* skip preceding dots */
698
4
        ptr++;
699
4
        len--;
700
4
      }
701
18.6k
      co->domain = curlx_memdup0(ptr, len);
702
18.6k
      if(!co->domain)
703
0
        return CURLE_OUT_OF_MEMORY;
704
18.6k
      break;
705
18.6k
    case 1:
706
      /*
707
       * flag: A TRUE/FALSE value indicating if all machines within a given
708
       * domain can access the variable. Set TRUE when the cookie says
709
       * .example.com and to false when the domain is complete www.example.com
710
       */
711
654
      co->tailmatch = !!curl_strnequal(ptr, "TRUE", len);
712
654
      break;
713
651
    case 2:
714
      /* The file format allows the path field to remain not filled in */
715
651
      if(strncmp("TRUE", ptr, len) && strncmp("FALSE", ptr, len)) {
716
        /* only if the path does not look like a boolean option! */
717
64
        co->path = sanitize_cookie_path(ptr, len);
718
64
        if(!co->path)
719
0
          return CURLE_OUT_OF_MEMORY;
720
64
        break;
721
64
      }
722
587
      else {
723
        /* this does not look like a path, make one up! */
724
587
        co->path = curlx_strdup("/");
725
587
        if(!co->path)
726
0
          return CURLE_OUT_OF_MEMORY;
727
587
      }
728
587
      fields++; /* add a field and fall down to secure */
729
587
      FALLTHROUGH();
730
599
    case 3:
731
599
      co->secure = FALSE;
732
599
      if(curl_strnequal(ptr, "TRUE", len)) {
733
589
        if(secure_origin || ci->running)
734
589
          co->secure = TRUE;
735
0
        else
736
0
          return CURLE_OK;
737
589
      }
738
599
      break;
739
599
    case 4:
740
593
      if(curlx_str_number(&ptr, &co->expires, CURL_OFF_T_MAX))
741
67
        return CURLE_OK;
742
526
      break;
743
526
    case 5:
744
524
      co->name = curlx_memdup0(ptr, len);
745
524
      if(!co->name)
746
0
        return CURLE_OUT_OF_MEMORY;
747
524
      else {
748
        /* For Netscape file format cookies we check prefix on the name.
749
           These prefixes are matched case sensitively, same as on the
750
           header path and as the 6265bis document specifies. */
751
524
        if(!strncmp("__Secure-", co->name, 9))
752
2
          co->prefix_secure = TRUE;
753
522
        else if(!strncmp("__Host-", co->name, 7))
754
4
          co->prefix_host = TRUE;
755
524
      }
756
524
      break;
757
524
    case 6:
758
31
      co->value = curlx_memdup0(ptr, len);
759
31
      if(!co->value)
760
0
        return CURLE_OUT_OF_MEMORY;
761
31
      break;
762
21.5k
    }
763
21.5k
  }
764
18.6k
  if(fields == 6) {
765
    /* we got a cookie with blank contents, fix it */
766
493
    co->value = curlx_strdup("");
767
493
    if(!co->value)
768
0
      return CURLE_OUT_OF_MEMORY;
769
493
    else
770
493
      fields++;
771
493
  }
772
773
18.6k
  if(fields != 7)
774
    /* we did not find the sufficient number of fields */
775
18.1k
    return CURLE_OK;
776
777
  /* Reject control octets in the name or value, matching the filtering done
778
     for cookies set over HTTP. A cookie loaded from a file is later sent in
779
     request headers, so the same bytes that make a server reject a request
780
     must not slip in through the file. */
781
511
  if(invalid_octets(co->name, strlen(co->name)) ||
782
494
     invalid_octets(co->value, strlen(co->value)))
783
20
    return CURLE_OK;
784
785
491
  *okay = TRUE;
786
491
  return CURLE_OK;
787
511
}
788
789
static bool is_public_suffix(struct Curl_easy *data,
790
                             struct Cookie *co,
791
                             const char *domain)
792
11.5k
{
793
#ifdef USE_LIBPSL
794
  /*
795
   * Check if the domain is a Public Suffix and if yes, ignore the cookie.
796
   * 'domain' is NULL when the cookie is loaded from file or
797
   * CURLOPT_COOKIELIST.
798
   */
799
  DEBUGASSERT(data);
800
  DEBUGASSERT(co);
801
  DEBUGF(infof(data, "PSL check set-cookie '%s' for domain=%s in %s",
802
               co->name, co->domain ? co->domain : "[blank]",
803
               domain ? domain : "[file]"));
804
  if(!co->domain || Curl_host_is_ipnum(co->domain))
805
    return FALSE;
806
807
  else {
808
    bool acceptable = FALSE;
809
    char lcase[256];
810
    char lcookie[256];
811
    size_t dlen = domain ? strlen(domain) : 0;
812
    size_t clen = strlen(co->domain);
813
814
    /* trim trailing dots */
815
    if(dlen && (domain[dlen - 1] == '.'))
816
      dlen--;
817
    if(clen && (co->domain[clen - 1] == '.'))
818
      clen--;
819
820
    if((dlen < sizeof(lcase)) && (clen < sizeof(lcookie))) {
821
      const psl_ctx_t *psl = Curl_psl_use(data);
822
      if(psl) {
823
        /* the PSL check requires lowercase domain name and pattern */
824
        Curl_strntolower(lcookie, co->domain, clen);
825
        lcookie[clen] = 0;
826
        if(domain) {
827
          Curl_strntolower(lcase, domain, dlen);
828
          lcase[dlen] = 0;
829
          acceptable = psl_is_cookie_domain_acceptable(psl, lcase, lcookie);
830
831
          /* if the cookie is acceptable, but is set for a PSL domain, then it
832
             cannot be tailmatching */
833
          if(acceptable && co->tailmatch &&
834
             curl_strequal(co->domain, domain) &&
835
             psl_is_public_suffix(psl, lcookie))
836
            co->tailmatch = FALSE;
837
        }
838
        else {
839
          bool suffix = psl_is_public_suffix(psl, lcookie);
840
          acceptable = TRUE;
841
          if(suffix)
842
            /* switch off tailmatching when set for a PSL domain */
843
            co->tailmatch = FALSE;
844
        }
845
        Curl_psl_release(data);
846
      }
847
      else
848
        infof(data, "libpsl problem, rejecting cookie for safety");
849
    }
850
851
    if(!acceptable) {
852
      infof(data, "cookie '%s' dropped, domain '%s' must not "
853
            "set cookies for '%s'", co->name,
854
            domain ? domain : "[file]", co->domain);
855
      return TRUE;
856
    }
857
  }
858
#else
859
11.5k
  (void)data;
860
11.5k
  (void)co;
861
11.5k
  (void)domain;
862
11.5k
  DEBUGF(infof(data, "NO PSL to check set-cookie '%s' for domain=%s in %s",
863
11.5k
               co->name, co->domain, domain ? domain : "[file]"));
864
11.5k
#endif
865
11.5k
  return FALSE;
866
11.5k
}
867
868
/* returns TRUE when replaced */
869
static bool replace_existing(struct Curl_easy *data,
870
                             struct Cookie *co,
871
                             const struct CookieInfo *ci,
872
                             bool secure,
873
                             bool *replacep)
874
13.5k
{
875
13.5k
  bool replace_old = FALSE;
876
13.5k
  struct Curl_llist_node *replace_n = NULL;
877
13.5k
  struct Curl_llist_node *n;
878
13.5k
  size_t myhash = cookiehash(co->domain);
879
83.2k
  for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
880
69.7k
    struct Cookie *clist = Curl_node_elem(n);
881
69.7k
    if(!strcmp(clist->name, co->name)) {
882
      /* the names are identical */
883
18.5k
      bool matching_domains = FALSE;
884
885
18.5k
      if(clist->domain && co->domain) {
886
18.1k
        if(cookie_tailmatch(clist->domain, strlen(clist->domain),
887
18.1k
                            co->domain) ||
888
1.10k
           cookie_tailmatch(co->domain, strlen(co->domain), clist->domain))
889
          /* The existing one is a tail of the new or vice versa */
890
17.4k
          matching_domains = TRUE;
891
18.1k
      }
892
373
      else if(!clist->domain && !co->domain)
893
0
        matching_domains = TRUE;
894
895
18.5k
      if(matching_domains && /* the domains were identical */
896
17.4k
         clist->path && co->path && /* both have paths */
897
17.0k
         clist->secure && !co->secure && !secure) {
898
0
        size_t cllen;
899
0
        const char *sep = NULL;
900
901
        /*
902
         * A non-secure cookie may not overlay an existing secure cookie.
903
         * For an existing cookie "a" with path "/login", refuse a new
904
         * cookie "a" with for example path "/login/en", while the path
905
         * "/loginhelper" is ok.
906
         */
907
908
0
        DEBUGASSERT(clist->path[0]);
909
0
        if(clist->path[0])
910
0
          sep = strchr(clist->path + 1, '/');
911
0
        if(sep)
912
0
          cllen = sep - clist->path;
913
0
        else
914
0
          cllen = strlen(clist->path);
915
916
0
        if(!strncmp(clist->path, co->path, cllen)) {
917
0
          infof(data, "cookie '%s' for domain '%s' dropped, would "
918
0
                "overlay an existing cookie", co->name, co->domain);
919
0
          return FALSE;
920
0
        }
921
0
      }
922
18.5k
    }
923
924
69.7k
    if(!replace_n && !strcmp(clist->name, co->name)) {
925
      /* the names are identical */
926
927
16.3k
      if(clist->domain && co->domain) {
928
15.9k
        if(curl_strequal(clist->domain, co->domain) &&
929
14.4k
           (clist->tailmatch == co->tailmatch))
930
          /* The domains are identical */
931
14.3k
          replace_old = TRUE;
932
15.9k
      }
933
373
      else if(!clist->domain && !co->domain)
934
0
        replace_old = TRUE;
935
936
16.3k
      if(replace_old) {
937
        /* the domains were identical */
938
939
14.3k
        if(clist->path && co->path &&
940
14.3k
           strcmp(clist->path, co->path))
941
6.75k
          replace_old = FALSE;
942
7.57k
        else if(!clist->path != !co->path)
943
34
          replace_old = FALSE;
944
14.3k
      }
945
946
16.3k
      if(replace_old && !co->livecookie && clist->livecookie) {
947
        /*
948
         * Both cookies matched fine, except that the already present cookie
949
         * is "live", which means it was set from a header, while the new one
950
         * was read from a file and thus is not "live". "live" cookies are
951
         * preferred so the new cookie is freed.
952
         */
953
0
        return FALSE;
954
0
      }
955
16.3k
      if(replace_old)
956
7.54k
        replace_n = n;
957
16.3k
    }
958
69.7k
  }
959
13.5k
  if(replace_n) {
960
7.54k
    struct Cookie *repl = Curl_node_elem(replace_n);
961
962
    /* when replacing, creationtime is kept from old */
963
7.54k
    co->creationtime = repl->creationtime;
964
965
    /* unlink the old */
966
7.54k
    Curl_node_remove(replace_n);
967
968
    /* free the old cookie */
969
7.54k
    freecookie(repl, TRUE);
970
7.54k
  }
971
13.5k
  *replacep = replace_old;
972
13.5k
  return TRUE;
973
13.5k
}
974
975
/*
976
 * Curl_cookie_add
977
 *
978
 * Add a single cookie line to the cookie keeping object. Be aware that
979
 * sometimes we get an IP-only hostname, and that might also be a numerical
980
 * IPv6 address.
981
 *
982
 */
983
CURLcode Curl_cookie_add(struct Curl_easy *data,
984
                         struct CookieInfo *ci,
985
                         const char *lineptr, /* first character of the line */
986
                         const char *domain,  /* default domain */
987
                         const char *path,    /* full path used when this
988
                                                 cookie is set, used to get
989
                                                 default path for the cookie
990
                                                 unless set */
991
                         const int flags)
992
38.6k
{
993
38.6k
  struct Cookie comem;
994
38.6k
  struct Cookie *co;
995
38.6k
  size_t myhash;
996
38.6k
  CURLcode result;
997
38.6k
  bool replaces = FALSE;
998
38.6k
  bool okay;
999
1000
38.6k
  DEBUGASSERT(data);
1001
38.6k
  DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */
1002
38.6k
  if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT)
1003
555
    return CURLE_OK; /* silently ignore */
1004
1005
38.0k
  co = &comem;
1006
38.0k
  memset(co, 0, sizeof(comem));
1007
1008
38.0k
  if(flags & COOKIE_HTTPHEADER)
1009
19.3k
    result = parse_cookie_header(data, co, &okay,
1010
19.3k
                                 lineptr, domain, path, flags & COOKIE_SECURE);
1011
18.7k
  else
1012
18.7k
    result = parse_netscape(co, ci, &okay, lineptr, flags & COOKIE_SECURE);
1013
1014
38.0k
  if(result || !okay)
1015
23.8k
    goto fail;
1016
1017
14.2k
  if(co->prefix_secure && !co->secure)
1018
    /* The __Secure- prefix only requires that the cookie be set secure */
1019
466
    goto fail;
1020
1021
13.7k
  if(!(flags & COOKIE_NOPSL) && is_public_suffix(data, co, domain))
1022
0
    goto fail;
1023
1024
13.7k
  if(co->prefix_host) {
1025
    /*
1026
     * The __Host- prefix requires the cookie to be secure, have a "/" path
1027
     * and not have a domain set.
1028
     */
1029
313
    if(co->secure && co->path && !strcmp(co->path, "/") && !co->tailmatch)
1030
78
      ;
1031
235
    else
1032
235
      goto fail;
1033
313
  }
1034
1035
13.5k
  if(!ci->running &&    /* read from a file */
1036
2.23k
     ci->newsession &&  /* clean session cookies */
1037
0
     !co->expires)      /* this is a session cookie */
1038
0
    goto fail;
1039
1040
13.5k
  co->livecookie = ci->running;
1041
13.5k
  co->creationtime = ++ci->lastct;
1042
1043
13.5k
  if(!(flags & COOKIE_NOEXPIRE))
1044
13.5k
    remove_expired(ci);
1045
1046
  /*
1047
   * Now we have parsed the incoming line, we must now check if this supersedes
1048
   * an already existing cookie, which it may if the previous have the same
1049
   * domain and path as this.
1050
   */
1051
13.5k
  if(!replace_existing(data, co, ci, flags & COOKIE_SECURE, &replaces))
1052
0
    goto fail;
1053
1054
  /* clone the stack struct into heap */
1055
13.5k
  co = curlx_memdup(&comem, sizeof(comem));
1056
13.5k
  if(!co) {
1057
0
    co = &comem;
1058
0
    result = CURLE_OUT_OF_MEMORY;
1059
0
    goto fail; /* bail out if we are this low on memory */
1060
0
  }
1061
1062
  /* add this cookie to the list */
1063
13.5k
  myhash = cookiehash(co->domain);
1064
13.5k
  Curl_llist_append(&ci->cookielist[myhash], co, &co->node);
1065
1066
13.5k
  if(ci->running)
1067
    /* Only show this when NOT reading the cookies from a file */
1068
11.3k
    infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
1069
13.5k
          "expire %" FMT_OFF_T,
1070
13.5k
          replaces ? "Replaced" : "Added", co->name, co->value,
1071
13.5k
          co->domain, co->path, co->expires);
1072
1073
13.5k
  if(!replaces)
1074
6.01k
    ci->numcookies++; /* one more cookie in the jar */
1075
1076
  /*
1077
   * Now that we have added a new cookie to the jar, update the expiration
1078
   * tracker in case it is the next one to expire.
1079
   */
1080
13.5k
  if(co->expires && (co->expires < ci->next_expiration))
1081
1.73k
    ci->next_expiration = co->expires;
1082
1083
13.5k
  if(flags & COOKIE_HTTPHEADER)
1084
13.0k
    data->req.setcookies++;
1085
1086
13.5k
  return result;
1087
24.5k
fail:
1088
24.5k
  freecookie(co, FALSE);
1089
24.5k
  return result;
1090
13.5k
}
1091
1092
/*
1093
 * Curl_cookie_init()
1094
 *
1095
 * Inits a cookie struct to read data from a local file. This is always
1096
 * called before any cookies are set. File may be NULL in which case only the
1097
 * struct is initialized. Is file is "-" then STDIN is read.
1098
 *
1099
 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
1100
 *
1101
 * Note that 'data' might be called as NULL pointer. If data is NULL, 'file'
1102
 * will be ignored.
1103
 *
1104
 * Returns NULL on out of memory.
1105
 */
1106
struct CookieInfo *Curl_cookie_init(void)
1107
21.2k
{
1108
21.2k
  int i;
1109
21.2k
  struct CookieInfo *ci = curlx_calloc(1, sizeof(struct CookieInfo));
1110
21.2k
  if(!ci)
1111
0
    return NULL;
1112
1113
  /* This does not use the destructor callback since we want to add
1114
     and remove to lists while keeping the cookie struct intact */
1115
1.35M
  for(i = 0; i < COOKIE_HASH_SIZE; i++)
1116
1.33M
    Curl_llist_init(&ci->cookielist[i], NULL);
1117
  /*
1118
   * Initialize the next_expiration time to signal that we do not have enough
1119
   * information yet.
1120
   */
1121
21.2k
  ci->next_expiration = CURL_OFF_T_MAX;
1122
1123
21.2k
  return ci;
1124
21.2k
}
1125
1126
/*
1127
 * cookie_load()
1128
 *
1129
 * Reads cookies from a local file. This is always called before any cookies
1130
 * are set. If file is "-" then STDIN is read.
1131
 *
1132
 * If 'flags' has the COOKIE_NOSESSION bit set, discard all "session cookies"
1133
 * read from file.
1134
 */
1135
static CURLcode cookie_load(struct Curl_easy *data, const char *file,
1136
                            struct CookieInfo *ci, int flags)
1137
18.0k
{
1138
18.0k
  FILE *handle = NULL;
1139
18.0k
  CURLcode result = CURLE_OK;
1140
18.0k
  FILE *fp = NULL;
1141
18.0k
  DEBUGASSERT(ci);
1142
18.0k
  DEBUGASSERT(data);
1143
18.0k
  DEBUGASSERT(file);
1144
1145
18.0k
  ci->newsession = !!(flags & COOKIE_NOSESSION); /* new session? */
1146
18.0k
  ci->running = FALSE; /* this is not running, this is init */
1147
1148
18.0k
  if(file && *file) {
1149
18.0k
    if(!strcmp(file, "-"))
1150
0
      fp = stdin;
1151
18.0k
    else {
1152
18.0k
      fp = curlx_fopen(file, "rb");
1153
18.0k
      if(!fp)
1154
0
        infof(data, "WARNING: failed to open cookie file \"%s\"", file);
1155
18.0k
      else {
1156
18.0k
        curlx_struct_stat stat;
1157
18.0k
        if((curlx_fstat(fileno(fp), &stat) != -1) && S_ISDIR(stat.st_mode)) {
1158
0
          curlx_fclose(fp);
1159
0
          fp = NULL;
1160
0
          infof(data, "WARNING: cookie filename points to a directory: \"%s\"",
1161
0
                file);
1162
0
        }
1163
18.0k
        else
1164
18.0k
          handle = fp;
1165
18.0k
      }
1166
18.0k
    }
1167
18.0k
  }
1168
1169
18.0k
  if(fp) {
1170
18.0k
    struct dynbuf buf;
1171
18.0k
    bool eof = FALSE;
1172
    /* accept a little longer lines so that a full cookie fits and does not
1173
       abort the file read */
1174
18.0k
    curlx_dyn_init(&buf, MAX_COOKIE_LINE + 48);
1175
18.0k
    do {
1176
18.0k
      result = Curl_get_line(&buf, fp, &eof);
1177
18.0k
      if(!result) {
1178
18.0k
        const char *lineptr = curlx_dyn_ptr(&buf);
1179
18.0k
        bool headerline = FALSE;
1180
18.0k
        if(checkprefix("Set-Cookie:", lineptr)) {
1181
          /* This is a cookie line, get it! */
1182
0
          lineptr += 11;
1183
0
          headerline = TRUE;
1184
0
          curlx_str_passblanks(&lineptr);
1185
0
        }
1186
1187
18.0k
        result = Curl_cookie_add(data, ci, lineptr, NULL, NULL,
1188
18.0k
                                 (headerline ? COOKIE_HTTPHEADER : 0) |
1189
18.0k
                                 COOKIE_NOEXPIRE | COOKIE_SECURE |
1190
18.0k
                                 (flags & COOKIE_NOPSL));
1191
        /* Ignore individual cookie problems unless we ran out of memory */
1192
18.0k
        if(result != CURLE_OUT_OF_MEMORY)
1193
18.0k
          result = CURLE_OK;
1194
18.0k
      }
1195
18.0k
    } while(!result && !eof);
1196
18.0k
    curlx_dyn_free(&buf); /* free the line buffer */
1197
1198
    /*
1199
     * Remove expired cookies from the hash. We must make sure to run this
1200
     * after reading the file, and not on every cookie.
1201
     */
1202
18.0k
    remove_expired(ci);
1203
1204
18.0k
    if(handle)
1205
18.0k
      curlx_fclose(handle);
1206
18.0k
  }
1207
18.0k
  data->state.cookie_engine = TRUE;
1208
18.0k
  ci->running = TRUE; /* now, we are running */
1209
1210
18.0k
  return result;
1211
18.0k
}
1212
1213
/*
1214
 * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
1215
 */
1216
CURLcode Curl_cookie_loadfiles(struct Curl_easy *data,
1217
                               int flags)
1218
18.0k
{
1219
18.0k
  CURLcode result = CURLE_OK;
1220
18.0k
  struct curl_slist *list = data->state.cookielist;
1221
18.0k
  if(list) {
1222
18.0k
    Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1223
18.0k
    if(!data->cookies)
1224
0
      data->cookies = Curl_cookie_init();
1225
18.0k
    if(!data->cookies)
1226
0
      result = CURLE_OUT_OF_MEMORY;
1227
18.0k
    else {
1228
18.0k
      data->state.cookie_engine = TRUE;
1229
36.0k
      while(list) {
1230
18.0k
        result = cookie_load(data, list->data, data->cookies, flags);
1231
18.0k
        if(result)
1232
0
          break;
1233
18.0k
        list = list->next;
1234
18.0k
      }
1235
18.0k
    }
1236
18.0k
    Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1237
18.0k
  }
1238
18.0k
  return result;
1239
18.0k
}
1240
1241
/*
1242
 * cookie_sort
1243
 *
1244
 * Helper function to sort cookies such that the longest path gets before the
1245
 * shorter path. Path, domain and name lengths are considered in that order,
1246
 * with the creationtime as the tiebreaker. The creationtime is guaranteed to
1247
 * be unique per cookie, so we know we will get an ordering at that point.
1248
 */
1249
static int cookie_sort(const void *p1, const void *p2)
1250
0
{
1251
0
  const struct Cookie *c1 = *(const struct Cookie * const *)p1;
1252
0
  const struct Cookie *c2 = *(const struct Cookie * const *)p2;
1253
0
  size_t l1, l2;
1254
1255
  /* 1 - compare cookie path lengths */
1256
0
  l1 = c1->path ? strlen(c1->path) : 0;
1257
0
  l2 = c2->path ? strlen(c2->path) : 0;
1258
1259
0
  if(l1 != l2)
1260
0
    return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */
1261
1262
  /* 2 - compare cookie domain lengths */
1263
0
  l1 = c1->domain ? strlen(c1->domain) : 0;
1264
0
  l2 = c2->domain ? strlen(c2->domain) : 0;
1265
1266
0
  if(l1 != l2)
1267
0
    return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */
1268
1269
  /* 3 - compare cookie name lengths */
1270
0
  l1 = c1->name ? strlen(c1->name) : 0;
1271
0
  l2 = c2->name ? strlen(c2->name) : 0;
1272
1273
0
  if(l1 != l2)
1274
0
    return (l2 > l1) ? 1 : -1;
1275
1276
  /* 4 - compare cookie creation time */
1277
0
  return (c2->creationtime > c1->creationtime) ? 1 : -1;
1278
0
}
1279
1280
/*
1281
 * cookie_sort_ct
1282
 *
1283
 * Helper function to sort cookies according to creation time.
1284
 */
1285
static int cookie_sort_ct(const void *p1, const void *p2)
1286
5.65k
{
1287
5.65k
  const struct Cookie *c1 = *(const struct Cookie * const *)p1;
1288
5.65k
  const struct Cookie *c2 = *(const struct Cookie * const *)p2;
1289
1290
5.65k
  return (c2->creationtime > c1->creationtime) ? 1 : -1;
1291
5.65k
}
1292
1293
bool Curl_secure_context(struct Curl_easy *data, const char *host)
1294
18.0k
{
1295
18.0k
  return Curl_xfer_is_secure(data) ||
1296
18.0k
    curl_strequal("localhost", host) ||
1297
17.8k
    !strcmp(host, "127.0.0.1") ||
1298
17.0k
    !strcmp(host, "::1");
1299
18.0k
}
1300
1301
/*
1302
 * Curl_cookie_getlist
1303
 *
1304
 * For a given host and path, return a linked list of cookies that the client
1305
 * should send to the server if used now.
1306
 *
1307
 * It shall only return cookies that have not expired.
1308
 *
1309
 * 'okay' is TRUE when there is a list returned.
1310
 */
1311
CURLcode Curl_cookie_getlist(struct Curl_easy *data,
1312
                             bool *okay,
1313
                             const char *host,
1314
                             struct Curl_llist *list)
1315
0
{
1316
0
  size_t matches = 0;
1317
0
  const bool is_ip = Curl_host_is_ipnum(host);
1318
0
  const size_t myhash = cookiehash(host);
1319
0
  struct Curl_llist_node *n;
1320
0
  const bool secure = Curl_secure_context(data, host);
1321
0
  struct CookieInfo *ci = data->cookies;
1322
0
  const char *path = data->state.up.path;
1323
0
  CURLcode result = CURLE_OK;
1324
0
  *okay = FALSE;
1325
1326
0
  Curl_llist_init(list, NULL);
1327
1328
0
  if(!ci || !Curl_llist_count(&ci->cookielist[myhash]))
1329
0
    return CURLE_OK; /* no cookie struct or no cookies in the struct */
1330
1331
  /* at first, remove expired cookies */
1332
0
  remove_expired(ci);
1333
1334
0
  for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
1335
0
    struct Cookie *co = Curl_node_elem(n);
1336
1337
    /* if the cookie requires we are secure we must only continue if we are! */
1338
0
    if(co->secure ? secure : TRUE) {
1339
1340
      /* now check if the domain is correct */
1341
0
      if(!co->domain ||
1342
0
         (co->tailmatch && !is_ip &&
1343
0
          cookie_tailmatch(co->domain, strlen(co->domain), host)) ||
1344
0
         ((!co->tailmatch || is_ip) && curl_strequal(host, co->domain))) {
1345
        /*
1346
         * the right part of the host matches the domain stuff in the
1347
         * cookie data
1348
         */
1349
1350
        /*
1351
         * now check the left part of the path with the cookies path
1352
         * requirement
1353
         */
1354
0
        if(!co->path || pathmatch(co->path, path)) {
1355
1356
          /*
1357
           * This is a match and we add it to the return-linked-list
1358
           */
1359
0
          Curl_llist_append(list, co, &co->getnode);
1360
0
          matches++;
1361
0
          if(matches >= MAX_COOKIE_SEND_AMOUNT) {
1362
0
            infof(data, "Included max number of cookies (%zu) in request!",
1363
0
                  matches);
1364
0
            break;
1365
0
          }
1366
0
        }
1367
0
      }
1368
0
    }
1369
0
  }
1370
1371
0
  if(matches) {
1372
    /*
1373
     * Now we need to make sure that if there is a name appearing more than
1374
     * once, the longest specified path version comes first. To make this the
1375
     * swiftest way, we sort them all based on path length.
1376
     */
1377
0
    struct Cookie **array;
1378
0
    size_t i;
1379
1380
    /* alloc an array and store all cookie pointers */
1381
0
    array = curlx_malloc(sizeof(struct Cookie *) * matches);
1382
0
    if(!array) {
1383
0
      result = CURLE_OUT_OF_MEMORY;
1384
0
      goto fail;
1385
0
    }
1386
1387
0
    n = Curl_llist_head(list);
1388
1389
0
    for(i = 0; n; n = Curl_node_next(n))
1390
0
      array[i++] = Curl_node_elem(n);
1391
1392
    /* now sort the cookie pointers in path length order */
1393
0
    qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
1394
1395
    /* remake the linked list order according to the new order */
1396
0
    Curl_llist_destroy(list, NULL);
1397
1398
0
    for(i = 0; i < matches; i++)
1399
0
      Curl_llist_append(list, array[i], &array[i]->getnode);
1400
1401
0
    curlx_free(array); /* remove the temporary data again */
1402
0
  }
1403
1404
0
  *okay = TRUE;
1405
0
  return CURLE_OK; /* success */
1406
1407
0
fail:
1408
  /* failure, clear up the allocated chain and return NULL */
1409
0
  Curl_llist_destroy(list, NULL);
1410
0
  return result; /* error */
1411
0
}
1412
1413
/*
1414
 * Curl_cookie_clearall
1415
 *
1416
 * Clear all existing cookies and reset the counter.
1417
 */
1418
void Curl_cookie_clearall(struct CookieInfo *ci)
1419
21.2k
{
1420
21.2k
  if(ci) {
1421
21.2k
    unsigned int i;
1422
1.35M
    for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1423
1.33M
      struct Curl_llist_node *n;
1424
1.34M
      for(n = Curl_llist_head(&ci->cookielist[i]); n;) {
1425
5.17k
        struct Cookie *c = Curl_node_elem(n);
1426
5.17k
        struct Curl_llist_node *e = Curl_node_next(n);
1427
5.17k
        Curl_node_remove(n);
1428
5.17k
        freecookie(c, TRUE);
1429
5.17k
        n = e;
1430
5.17k
      }
1431
1.33M
    }
1432
21.2k
    ci->numcookies = 0;
1433
21.2k
  }
1434
21.2k
}
1435
1436
/*
1437
 * Curl_cookie_clearsess
1438
 *
1439
 * Free all session cookies in the cookies list.
1440
 */
1441
void Curl_cookie_clearsess(struct CookieInfo *ci)
1442
1
{
1443
1
  unsigned int i;
1444
1445
1
  if(!ci)
1446
1
    return;
1447
1448
0
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1449
0
    struct Curl_llist_node *n = Curl_llist_head(&ci->cookielist[i]);
1450
0
    struct Curl_llist_node *e = NULL;
1451
1452
0
    for(; n; n = e) {
1453
0
      struct Cookie *curr = Curl_node_elem(n);
1454
0
      e = Curl_node_next(n); /* in case the node is removed, get it early */
1455
0
      if(!curr->expires) {
1456
0
        Curl_node_remove(n);
1457
0
        freecookie(curr, TRUE);
1458
0
        ci->numcookies--;
1459
0
      }
1460
0
    }
1461
0
  }
1462
0
}
1463
1464
/*
1465
 * Curl_cookie_cleanup()
1466
 *
1467
 * Free a "cookie object" previous created with Curl_cookie_init().
1468
 */
1469
void Curl_cookie_cleanup(struct CookieInfo *ci)
1470
21.2k
{
1471
21.2k
  if(ci) {
1472
21.2k
    Curl_cookie_clearall(ci);
1473
21.2k
    curlx_free(ci); /* free the base struct as well */
1474
21.2k
  }
1475
21.2k
}
1476
1477
/*
1478
 * get_netscape_format()
1479
 *
1480
 * Formats a string for Netscape output file, w/o a newline at the end.
1481
 * Function returns a char * to a formatted line. The caller is responsible
1482
 * for freeing the returned pointer.
1483
 */
1484
static char *get_netscape_format(const struct Cookie *co)
1485
3.40k
{
1486
3.40k
  return curl_maprintf(
1487
3.40k
    "%s"               /* httponly preamble */
1488
3.40k
    "%s%s\t"           /* domain */
1489
3.40k
    "%s\t"             /* tailmatch */
1490
3.40k
    "%s\t"             /* path */
1491
3.40k
    "%s\t"             /* secure */
1492
3.40k
    "%" FMT_OFF_T "\t" /* expires */
1493
3.40k
    "%s\t"             /* name */
1494
3.40k
    "%s",              /* value */
1495
3.40k
    co->httponly ? "#HttpOnly_" : "",
1496
    /*
1497
     * Make sure all domains are prefixed with a dot if they allow
1498
     * tailmatching. This is Mozilla-style.
1499
     */
1500
3.40k
    (co->tailmatch && co->domain && co->domain[0] != '.') ? "." : "",
1501
3.40k
    co->domain ? co->domain : "unknown",
1502
3.40k
    co->tailmatch ? "TRUE" : "FALSE",
1503
3.40k
    co->path ? co->path : "/",
1504
3.40k
    co->secure ? "TRUE" : "FALSE",
1505
3.40k
    co->expires,
1506
3.40k
    co->name,
1507
3.40k
    co->value ? co->value : "");
1508
3.40k
}
1509
1510
/*
1511
 * cookie_output()
1512
 *
1513
 * Writes all internally known cookies to the specified file. Specify
1514
 * "-" as filename to write to stdout.
1515
 *
1516
 * The function returns non-zero on write failure.
1517
 */
1518
static CURLcode cookie_output(struct Curl_easy *data,
1519
                              struct CookieInfo *ci,
1520
                              const char *filename)
1521
18.0k
{
1522
18.0k
  FILE *out = NULL;
1523
18.0k
  bool use_stdout = FALSE;
1524
18.0k
  char *tempstore = NULL;
1525
18.0k
  CURLcode result = CURLE_OK;
1526
1527
18.0k
  if(!ci)
1528
    /* no cookie engine alive */
1529
0
    return CURLE_OK;
1530
1531
  /* at first, remove expired cookies */
1532
18.0k
  remove_expired(ci);
1533
1534
18.0k
  if(!strcmp("-", filename)) {
1535
    /* use stdout */
1536
0
    out = stdout;
1537
0
    use_stdout = TRUE;
1538
0
  }
1539
18.0k
  else {
1540
18.0k
    result = Curl_fopen(data, filename, &out, &tempstore);
1541
18.0k
    if(result)
1542
0
      goto error;
1543
18.0k
  }
1544
1545
18.0k
  fputs("# Netscape HTTP Cookie File\n"
1546
18.0k
        "# https://curl.se/docs/http-cookies.html\n"
1547
18.0k
        "# This file was generated by libcurl! Edit at your own risk.\n\n",
1548
18.0k
        out);
1549
1550
18.0k
  if(ci->numcookies) {
1551
1.51k
    unsigned int i;
1552
1.51k
    size_t nvalid = 0;
1553
1.51k
    struct Cookie **array;
1554
1.51k
    struct Curl_llist_node *n;
1555
1556
1.51k
    array = curlx_calloc(1, sizeof(struct Cookie *) * ci->numcookies);
1557
1.51k
    if(!array) {
1558
0
      result = CURLE_OUT_OF_MEMORY;
1559
0
      goto error;
1560
0
    }
1561
1562
    /* only sort the cookies with a domain property */
1563
96.8k
    for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1564
99.3k
      for(n = Curl_llist_head(&ci->cookielist[i]); n; n = Curl_node_next(n)) {
1565
3.99k
        struct Cookie *co = Curl_node_elem(n);
1566
3.99k
        if(!co->domain)
1567
590
          continue;
1568
3.40k
        array[nvalid++] = co;
1569
3.40k
      }
1570
95.3k
    }
1571
1572
1.51k
    qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
1573
1574
4.91k
    for(i = 0; i < nvalid; i++) {
1575
3.40k
      char *format_ptr = get_netscape_format(array[i]);
1576
3.40k
      if(!format_ptr) {
1577
0
        curlx_free(array);
1578
0
        result = CURLE_OUT_OF_MEMORY;
1579
0
        goto error;
1580
0
      }
1581
3.40k
      curl_mfprintf(out, "%s\n", format_ptr);
1582
3.40k
      curlx_free(format_ptr);
1583
3.40k
    }
1584
1585
1.51k
    curlx_free(array);
1586
1.51k
  }
1587
1588
18.0k
  if(!use_stdout) {
1589
18.0k
    curlx_fclose(out);
1590
18.0k
    out = NULL;
1591
18.0k
    if(tempstore && curlx_rename(tempstore, filename)) {
1592
0
      result = CURLE_WRITE_ERROR;
1593
0
      goto error;
1594
0
    }
1595
18.0k
  }
1596
1597
  /*
1598
   * If we reach here we have successfully written a cookie file so there is
1599
   * no need to inspect the error, any error case should have jumped into the
1600
   * error block below.
1601
   */
1602
18.0k
  curlx_free(tempstore);
1603
18.0k
  return CURLE_OK;
1604
1605
0
error:
1606
0
  if(out && !use_stdout)
1607
0
    curlx_fclose(out);
1608
0
  if(tempstore) {
1609
0
    unlink(tempstore);
1610
0
    curlx_free(tempstore);
1611
0
  }
1612
0
  return result;
1613
18.0k
}
1614
1615
static struct curl_slist *cookie_list(const struct Curl_easy *data)
1616
0
{
1617
0
  struct curl_slist *list = NULL;
1618
0
  struct curl_slist *beg;
1619
0
  struct curl_slist **tail = &list;
1620
0
  unsigned int i;
1621
0
  struct Curl_llist_node *n;
1622
1623
0
  if(!data->cookies || (data->cookies->numcookies == 0))
1624
0
    return NULL;
1625
1626
  /* at first, remove expired cookies */
1627
0
  remove_expired(data->cookies);
1628
1629
0
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1630
0
    for(n = Curl_llist_head(&data->cookies->cookielist[i]); n;
1631
0
        n = Curl_node_next(n)) {
1632
0
      struct Cookie *c = Curl_node_elem(n);
1633
0
      char *line;
1634
0
      if(!c->domain)
1635
0
        continue;
1636
0
      line = get_netscape_format(c);
1637
0
      if(!line) {
1638
0
        curl_slist_free_all(list);
1639
0
        return NULL;
1640
0
      }
1641
0
      beg = Curl_slist_append_nodup(NULL, line);
1642
0
      if(!beg) {
1643
0
        curlx_free(line);
1644
0
        curl_slist_free_all(list);
1645
0
        return NULL;
1646
0
      }
1647
0
      *tail = beg;
1648
0
      tail = &beg->next;
1649
0
    }
1650
0
  }
1651
1652
0
  return list;
1653
0
}
1654
1655
struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
1656
0
{
1657
0
  struct curl_slist *list;
1658
0
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1659
0
  list = cookie_list(data);
1660
0
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1661
0
  return list;
1662
0
}
1663
1664
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
1665
44.0k
{
1666
44.0k
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1667
  /* only save the cookie file if a transfer was started (cookies->running is
1668
     set), as otherwise the cookies were not completely initialized and there
1669
     might be cookie files that were not loaded so saving the file is the
1670
     wrong thing. */
1671
44.0k
  if(data->cookies) {
1672
21.2k
    const char *cookiejar = CURL_EASY_STR(data, STRING_COOKIEJAR);
1673
21.2k
    if(cookiejar && data->cookies->running) {
1674
      /* if we have a destination file for all the cookies to get dumped to */
1675
18.0k
      CURLcode result = cookie_output(data, data->cookies, cookiejar);
1676
18.0k
      if(result)
1677
0
        infof(data, "WARNING: failed to save cookies in %s: %s",
1678
18.0k
              cookiejar, curl_easy_strerror(result));
1679
18.0k
    }
1680
1681
21.2k
    if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
1682
21.2k
      Curl_cookie_cleanup(data->cookies);
1683
21.2k
      data->cookies = NULL;
1684
21.2k
    }
1685
21.2k
  }
1686
44.0k
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1687
44.0k
}
1688
1689
void Curl_cookie_run(struct Curl_easy *data)
1690
18.0k
{
1691
18.0k
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1692
18.0k
  if(data->cookies)
1693
18.0k
    data->cookies->running = TRUE;
1694
18.0k
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1695
18.0k
}
1696
1697
#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */