Coverage Report

Created: 2026-10-31 06:46

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