Coverage Report

Created: 2026-09-14 07:04

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