Coverage Report

Created: 2026-09-04 07:16

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
460
#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
11.5k
{
54
11.5k
  if(co->expires && (TIME_T_MAX - COOKIES_MAXAGE - 30) > now) {
55
230
    timediff_t cap = now + COOKIES_MAXAGE;
56
230
    if(co->expires > cap) {
57
58
      cap += 30;
58
58
      co->expires = (cap / 60) * 60;
59
58
    }
60
230
  }
61
11.5k
}
62
63
static void freecookie(struct Cookie *co, bool maintoo)
64
8.39k
{
65
8.39k
  curlx_free(co->domain);
66
8.39k
  curlx_free(co->path);
67
8.39k
  curlx_free(co->name);
68
8.39k
  curlx_free(co->value);
69
8.39k
  if(maintoo)
70
1.37k
    curlx_free(co);
71
8.39k
}
72
73
static bool cookie_tailmatch(const char *cookie_domain,
74
                             const size_t cookie_domain_len,
75
                             const char *hostname)
76
0
{
77
0
  size_t hostname_len = strlen(hostname);
78
79
0
  if(hostname_len < cookie_domain_len)
80
0
    return FALSE;
81
82
0
  if(!curl_strnequal(cookie_domain,
83
0
                     hostname + hostname_len - cookie_domain_len,
84
0
                     cookie_domain_len))
85
0
    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
0
  if(hostname_len == cookie_domain_len)
96
0
    return TRUE;
97
0
  if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
98
0
    return TRUE;
99
0
  return FALSE;
100
0
}
101
102
/*
103
 * matching cookie path and URL path
104
 * RFC6265 5.1.4 Paths and Path-Match
105
 */
106
static bool pathmatch(const char *cookie_path, const char *uri_path)
107
0
{
108
0
  size_t cookie_path_len;
109
0
  size_t uri_path_len;
110
0
  bool ret = FALSE;
111
112
  /* cookie_path must not have last '/' separator. ex: /sample */
113
0
  cookie_path_len = strlen(cookie_path);
114
0
  if(cookie_path_len == 1) {
115
    /* cookie_path must be '/' */
116
0
    return TRUE;
117
0
  }
118
119
  /* #-fragments are already cut off! */
120
0
  if(strlen(uri_path) == 0 || uri_path[0] != '/')
121
0
    uri_path = "/";
122
123
  /*
124
   * here, RFC6265 5.1.4 says
125
   *  4. Output the characters of the uri-path from the first character up
126
   *     to, but not including, the right-most %x2F ("/").
127
   *  but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
128
   *  without redirect.
129
   *  Ignore this algorithm because /hoge is uri path for this case
130
   *  (uri path is not /).
131
   */
132
133
0
  uri_path_len = strlen(uri_path);
134
135
0
  if(uri_path_len < cookie_path_len)
136
0
    goto pathmatched;
137
138
  /* not using checkprefix() because matching should be case-sensitive */
139
0
  if(strncmp(cookie_path, uri_path, cookie_path_len))
140
0
    goto pathmatched;
141
142
  /* The cookie-path and the uri-path are identical. */
143
0
  if(cookie_path_len == uri_path_len) {
144
0
    ret = TRUE;
145
0
    goto pathmatched;
146
0
  }
147
148
  /* here, cookie_path_len < uri_path_len */
149
0
  if(uri_path[cookie_path_len] == '/') {
150
0
    ret = TRUE;
151
0
    goto pathmatched;
152
0
  }
153
154
0
pathmatched:
155
0
  return ret;
156
0
}
157
158
/*
159
 * Return the top-level domain, for optimal hashing.
160
 */
161
static const char *get_top_domain(const char * const domain, size_t *outlen)
162
762
{
163
762
  size_t len = 0;
164
762
  const char *first = NULL, *last;
165
166
762
  if(domain) {
167
762
    len = strlen(domain);
168
762
    last = memrchr(domain, '.', len);
169
762
    if(last) {
170
76
      first = memrchr(domain, '.', (last - domain));
171
76
      if(first)
172
34
        len -= (++first - domain);
173
76
    }
174
762
  }
175
176
762
  if(outlen)
177
762
    *outlen = len;
178
179
762
  return first ? first : domain;
180
762
}
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
762
{
192
762
  const char *end = domain + len;
193
762
  size_t h = 5381;
194
195
2.21k
  while(domain < end) {
196
1.45k
    size_t j = (size_t)Curl_raw_toupper(*domain++);
197
1.45k
    h += h << 5;
198
1.45k
    h ^= j;
199
1.45k
  }
200
201
762
  return (h % COOKIE_HASH_SIZE);
202
762
}
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
2.74k
{
213
2.74k
  const char *top;
214
2.74k
  size_t len;
215
216
2.74k
  if(!domain || Curl_host_is_ipnum(domain))
217
1.98k
    return 0;
218
219
762
  top = get_top_domain(domain, &len);
220
762
  return cookie_hash_domain(top, len);
221
2.74k
}
222
223
/*
224
 * cookie path sanitize
225
 */
226
static char *sanitize_cookie_path(const char *cookie_path, size_t len)
227
111
{
228
  /* some sites send path attribute within '"'. */
229
111
  if(len && (cookie_path[0] == '\"')) {
230
23
    cookie_path++;
231
23
    len--;
232
233
23
    if(len && (cookie_path[len - 1] == '\"'))
234
2
      len--;
235
23
  }
236
237
  /* RFC6265 5.2.4 The Path Attribute */
238
111
  if(!len || (cookie_path[0] != '/'))
239
    /* Let cookie-path be the default-path. */
240
88
    return curlx_strdup("/");
241
242
  /* remove trailing slash when path is non-empty */
243
  /* convert /hoge/ to /hoge */
244
23
  if(len > 1 && cookie_path[len - 1] == '/')
245
3
    len--;
246
247
23
  return curlx_memdup0(cookie_path, len);
248
111
}
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
1.98k
{
257
1.98k
  DEBUGASSERT(str);
258
1.98k
  *str = curlx_memdup0(newstr, len);
259
1.98k
  if(!*str)
260
0
    return CURLE_OUT_OF_MEMORY;
261
1.98k
  return CURLE_OK;
262
1.98k
}
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
14.6k
{
275
14.6k
  struct Cookie *co;
276
14.6k
  curl_off_t now = (curl_off_t)time(NULL);
277
14.6k
  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
14.6k
  if(now < ci->next_expiration &&
288
14.5k
     ci->next_expiration != CURL_OFF_T_MAX)
289
212
    return;
290
14.4k
  else
291
14.4k
    ci->next_expiration = CURL_OFF_T_MAX;
292
293
923k
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
294
908k
    struct Curl_llist_node *n;
295
908k
    struct Curl_llist_node *e = NULL;
296
297
908k
    for(n = Curl_llist_head(&ci->cookielist[i]); n; n = e) {
298
311
      co = Curl_node_elem(n);
299
311
      e = Curl_node_next(n);
300
311
      if(co->expires) {
301
119
        if(co->expires < now) {
302
117
          Curl_node_remove(n);
303
117
          freecookie(co, TRUE);
304
117
          ci->numcookies--;
305
117
        }
306
2
        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
0
          ci->next_expiration = co->expires;
312
119
      }
313
311
    }
314
908k
  }
315
14.4k
}
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
0
{
321
0
  if((len == 9) && curl_strnequal(domain, "localhost", 9))
322
0
    return FALSE;
323
0
  else {
324
    /* there must be a dot present, but that dot must not be a trailing dot */
325
0
    const char *dot = memchr(domain, '.', len);
326
0
    if(dot) {
327
0
      size_t i = dot - domain;
328
0
      if((len - i) > 1)
329
        /* the dot is not the last byte */
330
0
        return FALSE;
331
0
    }
332
0
  }
333
0
  return TRUE;
334
0
}
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
39.2k
{
347
39.2k
  const unsigned char *p = (const unsigned char *)ptr;
348
  /* Reject all bytes \x01 - \x1f + \x7f */
349
586k
  while(len && *p) {
350
546k
    if((*p < 0x20) || (*p == 0x7f))
351
71
      return TRUE;
352
546k
    p++;
353
546k
    len--;
354
546k
  }
355
39.1k
  return FALSE;
356
39.2k
}
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
11.6k
#define MAX_DATE_LENGTH 80
362
363
1.03k
#define COOKIE_NAME   0
364
1.03k
#define COOKIE_VALUE  1
365
0
#define COOKIE_DOMAIN 2
366
372
#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
994
{
373
994
  CURLcode result;
374
994
  result = strstore(&co->name, curlx_str(&cp[COOKIE_NAME]),
375
994
                    curlx_strlen(&cp[COOKIE_NAME]));
376
994
  if(!result)
377
994
    result = strstore(&co->value, curlx_str(&cp[COOKIE_VALUE]),
378
994
                      curlx_strlen(&cp[COOKIE_VALUE]));
379
994
  if(!result) {
380
994
    size_t plen = 0;
381
994
    if(curlx_strlen(&cp[COOKIE_PATH])) {
382
23
      path = curlx_str(&cp[COOKIE_PATH]);
383
23
      plen = curlx_strlen(&cp[COOKIE_PATH]);
384
23
    }
385
971
    else if(path) {
386
      /* No path was given in the header line, set the default */
387
0
      const char *endslash = strrchr(path, '/');
388
0
      if(endslash)
389
0
        plen = endslash - path + 1; /* include end slash */
390
0
      else
391
0
        plen = strlen(path);
392
0
    }
393
394
994
    if(path) {
395
23
      co->path = sanitize_cookie_path(path, plen);
396
23
      if(!co->path)
397
0
        result = CURLE_OUT_OF_MEMORY;
398
23
    }
399
994
  }
400
994
  if(!result) {
401
994
    if(curlx_strlen(&cp[COOKIE_DOMAIN]))
402
0
      result = strstore(&co->domain, curlx_str(&cp[COOKIE_DOMAIN]),
403
0
                        curlx_strlen(&cp[COOKIE_DOMAIN]));
404
994
    else if(domain) {
405
      /* no domain was given in the header line, set the default */
406
0
      co->domain = curlx_strdup(domain);
407
0
      if(!co->domain)
408
0
        result = CURLE_OUT_OF_MEMORY;
409
0
    }
410
994
  }
411
994
  return result;
412
994
}
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
1.06k
{
424
  /* The first name/value pair is the actual cookie name */
425
1.06k
  if(!sep || !curlx_strlen(name)) {
426
27
    infof(data, "invalid cookie, dropped");
427
27
    return FALSE;
428
27
  }
429
430
  /*
431
   * Check for too long individual name or contents. Chrome and Firefox
432
   * support 4095 or 4096 bytes combo
433
   */
434
1.03k
  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
1.03k
  if(!strncmp("__Secure-", curlx_str(name), 9))
442
4
    co->prefix_secure = TRUE;
443
1.03k
  else if(!strncmp("__Host-", curlx_str(name), 7))
444
5
    co->prefix_host = TRUE;
445
446
1.03k
  cookie[COOKIE_NAME] = *name;
447
1.03k
  cookie[COOKIE_VALUE] = *val;
448
1.03k
  return TRUE;
449
1.03k
}
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
4.54k
{
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
4.54k
  if(curlx_str_casecompare(name, "secure")) {
461
206
    if(secure || !ci->running)
462
206
      co->secure = TRUE;
463
0
    else {
464
0
      infof(data, "skipped cookie because not 'secure'");
465
0
      return FALSE;
466
0
    }
467
206
  }
468
4.34k
  else if(curlx_str_casecompare(name, "httponly"))
469
197
    co->httponly = TRUE;
470
471
4.54k
  return TRUE;
472
4.54k
}
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
0
{
479
0
  bool is_ip;
480
0
  const char *domain = *domainp;
481
0
  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
0
  if('.' == *v)
488
0
    curlx_str_nudge(val, 1);
489
490
0
#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
0
  if(bad_domain(curlx_str(val), curlx_strlen(val))) {
497
0
    *domainp = ":";
498
0
    domain = ":";
499
0
  }
500
0
#endif
501
502
0
  is_ip = Curl_host_is_ipnum(domain ? domain : curlx_str(val));
503
504
0
  if(!domain ||
505
0
     (is_ip &&
506
0
      !strncmp(curlx_str(val), domain, curlx_strlen(val)) &&
507
0
      (curlx_strlen(val) == strlen(domain))) ||
508
0
     (!is_ip && cookie_tailmatch(curlx_str(val),
509
0
                                  curlx_strlen(val), domain))) {
510
0
    *cookie_domain = *val;
511
0
    if(!is_ip)
512
0
      co->tailmatch = TRUE; /* we always do that if the domain name was
513
                               given */
514
0
  }
515
0
  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
0
    infof(data, "skipped cookie with bad tailmatch domain: %s",
521
0
          curlx_str(val));
522
0
    return FALSE;
523
0
  }
524
0
  return TRUE;
525
0
}
526
527
static void parse_maxage(struct Cookie *co, struct Curl_str *val,
528
                         time_t *nowp)
529
0
{
530
0
  int rc;
531
0
  const char *maxage = curlx_str(val);
532
0
  if(*maxage == '\"')
533
0
    maxage++;
534
0
  rc = curlx_str_number(&maxage, &co->expires, CURL_OFF_T_MAX);
535
0
  if(!*nowp)
536
0
    *nowp = time(NULL);
537
0
  switch(rc) {
538
0
  case STRE_OVERFLOW:
539
    /* overflow, used max value */
540
0
    co->expires = CURL_OFF_T_MAX;
541
0
    break;
542
0
  default:
543
    /* negative or otherwise bad, expire */
544
0
    co->expires = 1;
545
0
    break;
546
0
  case STRE_OK:
547
0
    if(!co->expires)
548
0
      co->expires = 1; /* expire now */
549
0
    else if(CURL_OFF_T_MAX - *nowp < co->expires)
550
      /* would overflow */
551
0
      co->expires = CURL_OFF_T_MAX;
552
0
    else
553
0
      co->expires += *nowp;
554
0
    break;
555
0
  }
556
0
  cap_expires(*nowp, co);
557
0
}
558
559
static void parse_expires(struct Cookie *co, struct Curl_str *val,
560
                          time_t *nowp)
561
11.9k
{
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
11.9k
  if(!co->expires && (curlx_strlen(val) < MAX_DATE_LENGTH)) {
569
11.5k
    char dbuf[MAX_DATE_LENGTH + 1];
570
11.5k
    time_t date = 0;
571
11.5k
    memcpy(dbuf, curlx_str(val), curlx_strlen(val));
572
11.5k
    dbuf[curlx_strlen(val)] = 0;
573
11.5k
    if(!Curl_getdate_capped(dbuf, &date)) {
574
230
      if(!date)
575
1
        date++;
576
230
      co->expires = (curl_off_t)date;
577
230
    }
578
11.3k
    else
579
11.3k
      co->expires = 0;
580
11.5k
    if(!*nowp)
581
853
      *nowp = time(NULL);
582
11.5k
    cap_expires(*nowp, co);
583
11.5k
  }
584
11.9k
}
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
1.08k
{
598
  /* This line was read off an HTTP-header */
599
1.08k
  time_t now = 0;
600
1.08k
  size_t linelength = strlen(ptr);
601
1.08k
  CURLcode result = CURLE_OK;
602
1.08k
  struct Curl_str cookie[COOKIE_PIECES];
603
1.08k
  *okay = FALSE;
604
1.08k
  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
1.08k
  memset(cookie, 0, sizeof(cookie));
610
23.0k
  do {
611
23.0k
    struct Curl_str name;
612
613
    /* we have a <name>=<value> pair or a stand-alone word here */
614
23.0k
    if(!curlx_str_cspn(&ptr, &name, ";\r\n=")) {
615
21.5k
      struct Curl_str val;
616
21.5k
      bool sep = FALSE;
617
21.5k
      curlx_str_trimblanks(&name);
618
619
21.5k
      if(invalid_octets(curlx_str(&name), curlx_strlen(&name))) {
620
31
        infof(data, "invalid octets in name, cookie dropped");
621
31
        return CURLE_OK;
622
31
      }
623
624
21.4k
      if(!curlx_str_single(&ptr, '=')) {
625
16.9k
        sep = TRUE; /* a '=' was used */
626
16.9k
        if(!curlx_str_cspn(&ptr, &val, ";\r\n"))
627
14.8k
          curlx_str_trimblanks(&val);
628
629
16.9k
        if(invalid_octets(curlx_str(&val), curlx_strlen(&val))) {
630
20
          infof(data, "invalid octets in value, cookie dropped");
631
20
          return CURLE_OK;
632
20
        }
633
16.9k
      }
634
4.57k
      else
635
4.57k
        curlx_str_init(&val);
636
637
21.4k
      if(!curlx_strlen(&cookie[COOKIE_NAME])) {
638
1.06k
        if(!parse_first_pair(data, co, cookie, &name, &val, sep))
639
28
          return CURLE_OK;
640
1.06k
      }
641
20.3k
      else if(!sep) {
642
4.54k
        if(!parse_flag(data, co, ci, &name, secure_origin))
643
0
          return CURLE_OK;
644
4.54k
      }
645
15.8k
      else if(curlx_str_casecompare(&name, "path"))
646
372
        cookie[COOKIE_PATH] = val;
647
15.4k
      else if(curlx_str_casecompare(&name, "domain") && curlx_strlen(&val)) {
648
0
        if(!parse_domain(data, co, &cookie[COOKIE_DOMAIN], &val, &domain))
649
0
          return CURLE_OK;
650
0
      }
651
15.4k
      else if(curlx_str_casecompare(&name, "max-age") && curlx_strlen(&val))
652
0
        parse_maxage(co, &val, &now);
653
15.4k
      else if(curlx_str_casecompare(&name, "expires") && curlx_strlen(&val))
654
11.9k
        parse_expires(co, &val, &now);
655
21.4k
    }
656
23.0k
  } while(!curlx_str_single(&ptr, ';'));
657
658
1.00k
  if(curlx_strlen(&cookie[COOKIE_NAME])) {
659
    /* the header was fine, now store the data */
660
994
    result = storecookie(co, &cookie[0], path, domain);
661
994
    if(!result)
662
994
      *okay = TRUE;
663
994
  }
664
1.00k
  return result;
665
1.08k
}
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
7.30k
{
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
7.30k
  const char *ptr, *next;
678
7.30k
  int fields;
679
7.30k
  size_t len;
680
7.30k
  *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
7.30k
  if(!strncmp(lineptr, "#HttpOnly_", 10)) {
689
1
    lineptr += 10;
690
1
    co->httponly = TRUE;
691
1
  }
692
693
7.30k
  if(lineptr[0] == '#')
694
    /* do not even try the comments */
695
75
    return CURLE_OK;
696
697
  /*
698
   * Now loop through the fields and init the struct we already have
699
   * allocated
700
   */
701
7.22k
  fields = 0;
702
16.7k
  for(next = lineptr; next; fields++) {
703
9.50k
    ptr = next;
704
9.50k
    len = strcspn(ptr, "\t\r\n");
705
9.50k
    next = (ptr[len] == '\t' ? &ptr[len + 1] : NULL);
706
9.50k
    switch(fields) {
707
7.22k
    case 0:
708
7.22k
      if(ptr[0] == '.') { /* skip preceding dots */
709
2
        ptr++;
710
2
        len--;
711
2
      }
712
7.22k
      co->domain = curlx_memdup0(ptr, len);
713
7.22k
      if(!co->domain)
714
0
        return CURLE_OUT_OF_MEMORY;
715
7.22k
      break;
716
7.22k
    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
549
      co->tailmatch = !!curl_strnequal(ptr, "TRUE", len);
723
549
      break;
724
546
    case 2:
725
      /* The file format allows the path field to remain not filled in */
726
546
      if(strncmp("TRUE", ptr, len) && strncmp("FALSE", ptr, len)) {
727
        /* only if the path does not look like a boolean option! */
728
88
        co->path = sanitize_cookie_path(ptr, len);
729
88
        if(!co->path)
730
0
          return CURLE_OUT_OF_MEMORY;
731
88
        break;
732
88
      }
733
458
      else {
734
        /* this does not look like a path, make one up! */
735
458
        co->path = curlx_strdup("/");
736
458
        if(!co->path)
737
0
          return CURLE_OUT_OF_MEMORY;
738
458
      }
739
458
      fields++; /* add a field and fall down to secure */
740
458
      FALLTHROUGH();
741
476
    case 3:
742
476
      co->secure = FALSE;
743
476
      if(curl_strnequal(ptr, "TRUE", len)) {
744
463
        if(secure_origin || ci->running)
745
463
          co->secure = TRUE;
746
0
        else
747
0
          return CURLE_OK;
748
463
      }
749
476
      break;
750
476
    case 4:
751
465
      if(curlx_str_number(&ptr, &co->expires, CURL_OFF_T_MAX))
752
34
        return CURLE_OK;
753
431
      break;
754
431
    case 5:
755
424
      co->name = curlx_memdup0(ptr, len);
756
424
      if(!co->name)
757
0
        return CURLE_OUT_OF_MEMORY;
758
424
      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
424
        if(!strncmp("__Secure-", co->name, 9))
763
2
          co->prefix_secure = TRUE;
764
422
        else if(!strncmp("__Host-", co->name, 7))
765
4
          co->prefix_host = TRUE;
766
424
      }
767
424
      break;
768
424
    case 6:
769
38
      co->value = curlx_memdup0(ptr, len);
770
38
      if(!co->value)
771
0
        return CURLE_OUT_OF_MEMORY;
772
38
      break;
773
9.50k
    }
774
9.50k
  }
775
7.19k
  if(fields == 6) {
776
    /* we got a cookie with blank contents, fix it */
777
386
    co->value = curlx_strdup("");
778
386
    if(!co->value)
779
0
      return CURLE_OUT_OF_MEMORY;
780
386
    else
781
386
      fields++;
782
386
  }
783
784
7.19k
  if(fields != 7)
785
    /* we did not find the sufficient number of fields */
786
6.78k
    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
412
  if(invalid_octets(co->name, strlen(co->name)) ||
793
397
     invalid_octets(co->value, strlen(co->value)))
794
20
    return CURLE_OK;
795
796
392
  *okay = TRUE;
797
392
  return CURLE_OK;
798
412
}
799
800
static bool is_public_suffix(struct Curl_easy *data,
801
                             struct Cookie *co,
802
                             const char *domain)
803
0
{
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
0
  (void)data;
872
0
  (void)co;
873
0
  (void)domain;
874
0
  DEBUGF(infof(data, "NO PSL to check set-cookie '%s' for domain=%s in %s",
875
0
               co->name, co->domain, domain ? domain : "[file]"));
876
0
#endif
877
0
  return FALSE;
878
0
}
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
1.37k
{
887
1.37k
  bool replace_old = FALSE;
888
1.37k
  struct Curl_llist_node *replace_n = NULL;
889
1.37k
  struct Curl_llist_node *n;
890
1.37k
  size_t myhash = cookiehash(co->domain);
891
1.37k
  for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
892
0
    struct Cookie *clist = Curl_node_elem(n);
893
0
    if(!strcmp(clist->name, co->name)) {
894
      /* the names are identical */
895
0
      bool matching_domains = FALSE;
896
897
0
      if(clist->domain && co->domain) {
898
0
        if(cookie_tailmatch(clist->domain, strlen(clist->domain),
899
0
                            co->domain) ||
900
0
           cookie_tailmatch(co->domain, strlen(co->domain), clist->domain))
901
          /* The existing one is a tail of the new or vice versa */
902
0
          matching_domains = TRUE;
903
0
      }
904
0
      else if(!clist->domain && !co->domain)
905
0
        matching_domains = TRUE;
906
907
0
      if(matching_domains && /* the domains were identical */
908
0
         clist->path && co->path && /* both have paths */
909
0
         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
0
    }
935
936
0
    if(!replace_n && !strcmp(clist->name, co->name)) {
937
      /* the names are identical */
938
939
0
      if(clist->domain && co->domain) {
940
0
        if(curl_strequal(clist->domain, co->domain) &&
941
0
           (clist->tailmatch == co->tailmatch))
942
          /* The domains are identical */
943
0
          replace_old = TRUE;
944
0
      }
945
0
      else if(!clist->domain && !co->domain)
946
0
        replace_old = TRUE;
947
948
0
      if(replace_old) {
949
        /* the domains were identical */
950
951
0
        if(clist->path && co->path &&
952
0
           strcmp(clist->path, co->path))
953
0
          replace_old = FALSE;
954
0
        else if(!clist->path != !co->path)
955
0
          replace_old = FALSE;
956
0
      }
957
958
0
      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
0
      if(replace_old)
968
0
        replace_n = n;
969
0
    }
970
0
  }
971
1.37k
  if(replace_n) {
972
0
    struct Cookie *repl = Curl_node_elem(replace_n);
973
974
    /* when replacing, creationtime is kept from old */
975
0
    co->creationtime = repl->creationtime;
976
977
    /* unlink the old */
978
0
    Curl_node_remove(replace_n);
979
980
    /* free the old cookie */
981
0
    freecookie(repl, TRUE);
982
0
  }
983
1.37k
  *replacep = replace_old;
984
1.37k
  return TRUE;
985
1.37k
}
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
8.39k
{
1005
8.39k
  struct Cookie comem;
1006
8.39k
  struct Cookie *co;
1007
8.39k
  size_t myhash;
1008
8.39k
  CURLcode result;
1009
8.39k
  bool replaces = FALSE;
1010
8.39k
  bool okay;
1011
1012
8.39k
  DEBUGASSERT(data);
1013
8.39k
  DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */
1014
8.39k
  if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT)
1015
0
    return CURLE_OK; /* silently ignore */
1016
1017
8.39k
  co = &comem;
1018
8.39k
  memset(co, 0, sizeof(comem));
1019
1020
8.39k
  if(flags & COOKIE_HTTPHEADER)
1021
1.08k
    result = parse_cookie_header(data, co, ci, &okay,
1022
1.08k
                                 lineptr, domain, path, flags & COOKIE_SECURE);
1023
7.30k
  else
1024
7.30k
    result = parse_netscape(co, ci, &okay, lineptr, flags & COOKIE_SECURE);
1025
1026
8.39k
  if(result || !okay)
1027
7.00k
    goto fail;
1028
1029
1.38k
  if(co->prefix_secure && !co->secure)
1030
    /* The __Secure- prefix only requires that the cookie be set secure */
1031
5
    goto fail;
1032
1033
1.38k
  if(!(flags & COOKIE_NOPSL) && is_public_suffix(data, co, domain))
1034
0
    goto fail;
1035
1036
1.38k
  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
9
    if(co->secure && co->path && !strcmp(co->path, "/") && !co->tailmatch)
1042
1
      ;
1043
8
    else
1044
8
      goto fail;
1045
9
  }
1046
1047
1.37k
  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
1.37k
  co->livecookie = ci->running;
1053
1.37k
  co->creationtime = ++ci->lastct;
1054
1055
1.37k
  if(!(flags & COOKIE_NOEXPIRE))
1056
1.37k
    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
1.37k
  if(!replace_existing(data, co, ci, flags & COOKIE_SECURE, &replaces))
1064
0
    goto fail;
1065
1066
  /* clone the stack struct into heap */
1067
1.37k
  co = curlx_memdup(&comem, sizeof(comem));
1068
1.37k
  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
1.37k
  myhash = cookiehash(co->domain);
1076
1.37k
  Curl_llist_append(&ci->cookielist[myhash], co, &co->node);
1077
1078
1.37k
  if(ci->running)
1079
    /* Only show this when NOT reading the cookies from a file */
1080
0
    infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
1081
1.37k
          "expire %" FMT_OFF_T,
1082
1.37k
          replaces ? "Replaced" : "Added", co->name, co->value,
1083
1.37k
          co->domain, co->path, co->expires);
1084
1085
1.37k
  if(!replaces)
1086
1.37k
    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
1.37k
  if(co->expires && (co->expires < ci->next_expiration))
1093
546
    ci->next_expiration = co->expires;
1094
1095
1.37k
  if(flags & COOKIE_HTTPHEADER)
1096
985
    data->req.setcookies++;
1097
1098
1.37k
  return result;
1099
7.01k
fail:
1100
7.01k
  freecookie(co, FALSE);
1101
7.01k
  return result;
1102
1.37k
}
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
9.98k
{
1120
9.98k
  int i;
1121
9.98k
  struct CookieInfo *ci = curlx_calloc(1, sizeof(struct CookieInfo));
1122
9.98k
  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
638k
  for(i = 0; i < COOKIE_HASH_SIZE; i++)
1128
628k
    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
9.98k
  ci->next_expiration = CURL_OFF_T_MAX;
1134
1135
9.98k
  return ci;
1136
9.98k
}
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
6.63k
{
1150
6.63k
  FILE *handle = NULL;
1151
6.63k
  CURLcode result = CURLE_OK;
1152
6.63k
  FILE *fp = NULL;
1153
6.63k
  DEBUGASSERT(ci);
1154
6.63k
  DEBUGASSERT(data);
1155
6.63k
  DEBUGASSERT(file);
1156
1157
6.63k
  ci->newsession = !!(flags & COOKIE_NOSESSION); /* new session? */
1158
6.63k
  ci->running = FALSE; /* this is not running, this is init */
1159
1160
6.63k
  if(file && *file) {
1161
6.63k
    if(!strcmp(file, "-"))
1162
0
      fp = stdin;
1163
6.63k
    else {
1164
6.63k
      fp = curlx_fopen(file, "rb");
1165
6.63k
      if(!fp)
1166
0
        infof(data, "WARNING: failed to open cookie file \"%s\"", file);
1167
6.63k
      else {
1168
6.63k
        curlx_struct_stat stat;
1169
6.63k
        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
6.63k
        else
1176
6.63k
          handle = fp;
1177
6.63k
      }
1178
6.63k
    }
1179
6.63k
  }
1180
1181
6.63k
  if(fp) {
1182
6.63k
    struct dynbuf buf;
1183
6.63k
    bool eof = FALSE;
1184
6.63k
    curlx_dyn_init(&buf, MAX_COOKIE_LINE);
1185
6.63k
    do {
1186
6.63k
      result = Curl_get_line(&buf, fp, &eof);
1187
6.63k
      if(!result) {
1188
6.63k
        const char *lineptr = curlx_dyn_ptr(&buf);
1189
6.63k
        bool headerline = FALSE;
1190
6.63k
        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
6.63k
        result = Curl_cookie_add(data, ci, lineptr, NULL, NULL,
1198
6.63k
                                 (headerline ? COOKIE_HTTPHEADER : 0) |
1199
6.63k
                                 COOKIE_NOEXPIRE | COOKIE_SECURE |
1200
6.63k
                                 (flags & COOKIE_NOPSL));
1201
        /* File reading cookie failures are not propagated back to the
1202
           caller because there is no way to do that */
1203
6.63k
      }
1204
6.63k
    } while(!result && !eof);
1205
6.63k
    curlx_dyn_free(&buf); /* free the line buffer */
1206
1207
    /*
1208
     * Remove expired cookies from the hash. We must make sure to run this
1209
     * after reading the file, and not on every cookie.
1210
     */
1211
6.63k
    remove_expired(ci);
1212
1213
6.63k
    if(handle)
1214
6.63k
      curlx_fclose(handle);
1215
6.63k
  }
1216
6.63k
  data->state.cookie_engine = TRUE;
1217
6.63k
  ci->running = TRUE; /* now, we are running */
1218
1219
6.63k
  return result;
1220
6.63k
}
1221
1222
/*
1223
 * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
1224
 */
1225
CURLcode Curl_cookie_loadfiles(struct Curl_easy *data,
1226
                               int flags)
1227
6.63k
{
1228
6.63k
  CURLcode result = CURLE_OK;
1229
6.63k
  struct curl_slist *list = data->state.cookielist;
1230
6.63k
  if(list) {
1231
6.63k
    Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1232
6.63k
    if(!data->cookies)
1233
0
      data->cookies = Curl_cookie_init();
1234
6.63k
    if(!data->cookies)
1235
0
      result = CURLE_OUT_OF_MEMORY;
1236
6.63k
    else {
1237
6.63k
      data->state.cookie_engine = TRUE;
1238
13.2k
      while(list) {
1239
6.63k
        result = cookie_load(data, list->data, data->cookies, flags);
1240
6.63k
        if(result)
1241
0
          break;
1242
6.63k
        list = list->next;
1243
6.63k
      }
1244
6.63k
    }
1245
6.63k
    Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1246
6.63k
  }
1247
6.63k
  return result;
1248
6.63k
}
1249
1250
/*
1251
 * cookie_sort
1252
 *
1253
 * Helper function to sort cookies such that the longest path gets before the
1254
 * shorter path. Path, domain and name lengths are considered in that order,
1255
 * with the creationtime as the tiebreaker. The creationtime is guaranteed to
1256
 * be unique per cookie, so we know we will get an ordering at that point.
1257
 */
1258
static int cookie_sort(const void *p1, const void *p2)
1259
0
{
1260
0
  const struct Cookie *c1 = *(const struct Cookie * const *)p1;
1261
0
  const struct Cookie *c2 = *(const struct Cookie * const *)p2;
1262
0
  size_t l1, l2;
1263
1264
  /* 1 - compare cookie path lengths */
1265
0
  l1 = c1->path ? strlen(c1->path) : 0;
1266
0
  l2 = c2->path ? strlen(c2->path) : 0;
1267
1268
0
  if(l1 != l2)
1269
0
    return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */
1270
1271
  /* 2 - compare cookie domain lengths */
1272
0
  l1 = c1->domain ? strlen(c1->domain) : 0;
1273
0
  l2 = c2->domain ? strlen(c2->domain) : 0;
1274
1275
0
  if(l1 != l2)
1276
0
    return (l2 > l1) ? 1 : -1; /* avoid size_t <=> int conversions */
1277
1278
  /* 3 - compare cookie name lengths */
1279
0
  l1 = c1->name ? strlen(c1->name) : 0;
1280
0
  l2 = c2->name ? strlen(c2->name) : 0;
1281
1282
0
  if(l1 != l2)
1283
0
    return (l2 > l1) ? 1 : -1;
1284
1285
  /* 4 - compare cookie creation time */
1286
0
  return (c2->creationtime > c1->creationtime) ? 1 : -1;
1287
0
}
1288
1289
/*
1290
 * cookie_sort_ct
1291
 *
1292
 * Helper function to sort cookies according to creation time.
1293
 */
1294
static int cookie_sort_ct(const void *p1, const void *p2)
1295
0
{
1296
0
  const struct Cookie *c1 = *(const struct Cookie * const *)p1;
1297
0
  const struct Cookie *c2 = *(const struct Cookie * const *)p2;
1298
1299
0
  return (c2->creationtime > c1->creationtime) ? 1 : -1;
1300
0
}
1301
1302
bool Curl_secure_context(struct Curl_easy *data, const char *host)
1303
0
{
1304
0
  return Curl_xfer_is_secure(data) ||
1305
0
    curl_strequal("localhost", host) ||
1306
0
    !strcmp(host, "127.0.0.1") ||
1307
0
    !strcmp(host, "::1");
1308
0
}
1309
1310
/*
1311
 * Curl_cookie_getlist
1312
 *
1313
 * For a given host and path, return a linked list of cookies that the client
1314
 * should send to the server if used now.
1315
 *
1316
 * It shall only return cookies that have not expired.
1317
 *
1318
 * 'okay' is TRUE when there is a list returned.
1319
 */
1320
CURLcode Curl_cookie_getlist(struct Curl_easy *data,
1321
                             bool *okay,
1322
                             const char *host,
1323
                             struct Curl_llist *list)
1324
0
{
1325
0
  size_t matches = 0;
1326
0
  const bool is_ip = Curl_host_is_ipnum(host);
1327
0
  const size_t myhash = cookiehash(host);
1328
0
  struct Curl_llist_node *n;
1329
0
  const bool secure = Curl_secure_context(data, host);
1330
0
  struct CookieInfo *ci = data->cookies;
1331
0
  const char *path = data->state.up.path;
1332
0
  CURLcode result = CURLE_OK;
1333
0
  *okay = FALSE;
1334
1335
0
  Curl_llist_init(list, NULL);
1336
1337
0
  if(!ci || !Curl_llist_count(&ci->cookielist[myhash]))
1338
0
    return CURLE_OK; /* no cookie struct or no cookies in the struct */
1339
1340
  /* at first, remove expired cookies */
1341
0
  remove_expired(ci);
1342
1343
0
  for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
1344
0
    struct Cookie *co = Curl_node_elem(n);
1345
1346
    /* if the cookie requires we are secure we must only continue if we are! */
1347
0
    if(co->secure ? secure : TRUE) {
1348
1349
      /* now check if the domain is correct */
1350
0
      if(!co->domain ||
1351
0
         (co->tailmatch && !is_ip &&
1352
0
          cookie_tailmatch(co->domain, strlen(co->domain), host)) ||
1353
0
         ((!co->tailmatch || is_ip) && curl_strequal(host, co->domain))) {
1354
        /*
1355
         * the right part of the host matches the domain stuff in the
1356
         * cookie data
1357
         */
1358
1359
        /*
1360
         * now check the left part of the path with the cookies path
1361
         * requirement
1362
         */
1363
0
        if(!co->path || pathmatch(co->path, path)) {
1364
1365
          /*
1366
           * This is a match and we add it to the return-linked-list
1367
           */
1368
0
          Curl_llist_append(list, co, &co->getnode);
1369
0
          matches++;
1370
0
          if(matches >= MAX_COOKIE_SEND_AMOUNT) {
1371
0
            infof(data, "Included max number of cookies (%zu) in request!",
1372
0
                  matches);
1373
0
            break;
1374
0
          }
1375
0
        }
1376
0
      }
1377
0
    }
1378
0
  }
1379
1380
0
  if(matches) {
1381
    /*
1382
     * Now we need to make sure that if there is a name appearing more than
1383
     * once, the longest specified path version comes first. To make this the
1384
     * swiftest way, we sort them all based on path length.
1385
     */
1386
0
    struct Cookie **array;
1387
0
    size_t i;
1388
1389
    /* alloc an array and store all cookie pointers */
1390
0
    array = curlx_malloc(sizeof(struct Cookie *) * matches);
1391
0
    if(!array) {
1392
0
      result = CURLE_OUT_OF_MEMORY;
1393
0
      goto fail;
1394
0
    }
1395
1396
0
    n = Curl_llist_head(list);
1397
1398
0
    for(i = 0; n; n = Curl_node_next(n))
1399
0
      array[i++] = Curl_node_elem(n);
1400
1401
    /* now sort the cookie pointers in path length order */
1402
0
    qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
1403
1404
    /* remake the linked list order according to the new order */
1405
0
    Curl_llist_destroy(list, NULL);
1406
1407
0
    for(i = 0; i < matches; i++)
1408
0
      Curl_llist_append(list, array[i], &array[i]->getnode);
1409
1410
0
    curlx_free(array); /* remove the temporary data again */
1411
0
  }
1412
1413
0
  *okay = TRUE;
1414
0
  return CURLE_OK; /* success */
1415
1416
0
fail:
1417
  /* failure, clear up the allocated chain and return NULL */
1418
0
  Curl_llist_destroy(list, NULL);
1419
0
  return result; /* error */
1420
0
}
1421
1422
/*
1423
 * Curl_cookie_clearall
1424
 *
1425
 * Clear all existing cookies and reset the counter.
1426
 */
1427
void Curl_cookie_clearall(struct CookieInfo *ci)
1428
9.98k
{
1429
9.98k
  if(ci) {
1430
9.98k
    unsigned int i;
1431
638k
    for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1432
628k
      struct Curl_llist_node *n;
1433
630k
      for(n = Curl_llist_head(&ci->cookielist[i]); n;) {
1434
1.25k
        struct Cookie *c = Curl_node_elem(n);
1435
1.25k
        struct Curl_llist_node *e = Curl_node_next(n);
1436
1.25k
        Curl_node_remove(n);
1437
1.25k
        freecookie(c, TRUE);
1438
1.25k
        n = e;
1439
1.25k
      }
1440
628k
    }
1441
9.98k
    ci->numcookies = 0;
1442
9.98k
  }
1443
9.98k
}
1444
1445
/*
1446
 * Curl_cookie_clearsess
1447
 *
1448
 * Free all session cookies in the cookies list.
1449
 */
1450
void Curl_cookie_clearsess(struct CookieInfo *ci)
1451
1
{
1452
1
  unsigned int i;
1453
1454
1
  if(!ci)
1455
1
    return;
1456
1457
0
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1458
0
    struct Curl_llist_node *n = Curl_llist_head(&ci->cookielist[i]);
1459
0
    struct Curl_llist_node *e = NULL;
1460
1461
0
    for(; n; n = e) {
1462
0
      struct Cookie *curr = Curl_node_elem(n);
1463
0
      e = Curl_node_next(n); /* in case the node is removed, get it early */
1464
0
      if(!curr->expires) {
1465
0
        Curl_node_remove(n);
1466
0
        freecookie(curr, TRUE);
1467
0
        ci->numcookies--;
1468
0
      }
1469
0
    }
1470
0
  }
1471
0
}
1472
1473
/*
1474
 * Curl_cookie_cleanup()
1475
 *
1476
 * Free a "cookie object" previous created with Curl_cookie_init().
1477
 */
1478
void Curl_cookie_cleanup(struct CookieInfo *ci)
1479
9.98k
{
1480
9.98k
  if(ci) {
1481
9.98k
    Curl_cookie_clearall(ci);
1482
9.98k
    curlx_free(ci); /* free the base struct as well */
1483
9.98k
  }
1484
9.98k
}
1485
1486
/*
1487
 * get_netscape_format()
1488
 *
1489
 * Formats a string for Netscape output file, w/o a newline at the end.
1490
 * Function returns a char * to a formatted line. The caller is responsible
1491
 * for freeing the returned pointer.
1492
 */
1493
static char *get_netscape_format(const struct Cookie *co)
1494
124
{
1495
124
  return curl_maprintf(
1496
124
    "%s"               /* httponly preamble */
1497
124
    "%s%s\t"           /* domain */
1498
124
    "%s\t"             /* tailmatch */
1499
124
    "%s\t"             /* path */
1500
124
    "%s\t"             /* secure */
1501
124
    "%" FMT_OFF_T "\t" /* expires */
1502
124
    "%s\t"             /* name */
1503
124
    "%s",              /* value */
1504
124
    co->httponly ? "#HttpOnly_" : "",
1505
    /*
1506
     * Make sure all domains are prefixed with a dot if they allow
1507
     * tailmatching. This is Mozilla-style.
1508
     */
1509
124
    (co->tailmatch && co->domain && co->domain[0] != '.') ? "." : "",
1510
124
    co->domain ? co->domain : "unknown",
1511
124
    co->tailmatch ? "TRUE" : "FALSE",
1512
124
    co->path ? co->path : "/",
1513
124
    co->secure ? "TRUE" : "FALSE",
1514
124
    co->expires,
1515
124
    co->name,
1516
124
    co->value ? co->value : "");
1517
124
}
1518
1519
/*
1520
 * cookie_output()
1521
 *
1522
 * Writes all internally known cookies to the specified file. Specify
1523
 * "-" as filename to write to stdout.
1524
 *
1525
 * The function returns non-zero on write failure.
1526
 */
1527
static CURLcode cookie_output(struct Curl_easy *data,
1528
                              struct CookieInfo *ci,
1529
                              const char *filename)
1530
6.63k
{
1531
6.63k
  FILE *out = NULL;
1532
6.63k
  bool use_stdout = FALSE;
1533
6.63k
  char *tempstore = NULL;
1534
6.63k
  CURLcode result = CURLE_OK;
1535
1536
6.63k
  if(!ci)
1537
    /* no cookie engine alive */
1538
0
    return CURLE_OK;
1539
1540
  /* at first, remove expired cookies */
1541
6.63k
  remove_expired(ci);
1542
1543
6.63k
  if(!strcmp("-", filename)) {
1544
    /* use stdout */
1545
0
    out = stdout;
1546
0
    use_stdout = TRUE;
1547
0
  }
1548
6.63k
  else {
1549
6.63k
    result = Curl_fopen(data, filename, &out, &tempstore);
1550
6.63k
    if(result)
1551
0
      goto error;
1552
6.63k
  }
1553
1554
6.63k
  fputs("# Netscape HTTP Cookie File\n"
1555
6.63k
        "# https://curl.se/docs/http-cookies.html\n"
1556
6.63k
        "# This file was generated by libcurl! Edit at your own risk.\n\n",
1557
6.63k
        out);
1558
1559
6.63k
  if(ci->numcookies) {
1560
203
    unsigned int i;
1561
203
    size_t nvalid = 0;
1562
203
    struct Cookie **array;
1563
203
    struct Curl_llist_node *n;
1564
1565
203
    array = curlx_calloc(1, sizeof(struct Cookie *) * ci->numcookies);
1566
203
    if(!array) {
1567
0
      result = CURLE_OUT_OF_MEMORY;
1568
0
      goto error;
1569
0
    }
1570
1571
    /* only sort the cookies with a domain property */
1572
12.9k
    for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1573
12.9k
      for(n = Curl_llist_head(&ci->cookielist[i]); n; n = Curl_node_next(n)) {
1574
203
        struct Cookie *co = Curl_node_elem(n);
1575
203
        if(!co->domain)
1576
79
          continue;
1577
124
        array[nvalid++] = co;
1578
124
      }
1579
12.7k
    }
1580
1581
203
    qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
1582
1583
327
    for(i = 0; i < nvalid; i++) {
1584
124
      char *format_ptr = get_netscape_format(array[i]);
1585
124
      if(!format_ptr) {
1586
0
        curlx_free(array);
1587
0
        result = CURLE_OUT_OF_MEMORY;
1588
0
        goto error;
1589
0
      }
1590
124
      curl_mfprintf(out, "%s\n", format_ptr);
1591
124
      curlx_free(format_ptr);
1592
124
    }
1593
1594
203
    curlx_free(array);
1595
203
  }
1596
1597
6.63k
  if(!use_stdout) {
1598
6.63k
    curlx_fclose(out);
1599
6.63k
    out = NULL;
1600
6.63k
    if(tempstore && curlx_rename(tempstore, filename)) {
1601
0
      result = CURLE_WRITE_ERROR;
1602
0
      goto error;
1603
0
    }
1604
6.63k
  }
1605
1606
  /*
1607
   * If we reach here we have successfully written a cookie file so there is
1608
   * no need to inspect the error, any error case should have jumped into the
1609
   * error block below.
1610
   */
1611
6.63k
  curlx_free(tempstore);
1612
6.63k
  return CURLE_OK;
1613
1614
0
error:
1615
0
  if(out && !use_stdout)
1616
0
    curlx_fclose(out);
1617
0
  if(tempstore) {
1618
0
    unlink(tempstore);
1619
0
    curlx_free(tempstore);
1620
0
  }
1621
0
  return result;
1622
6.63k
}
1623
1624
static struct curl_slist *cookie_list(const struct Curl_easy *data)
1625
0
{
1626
0
  struct curl_slist *list = NULL;
1627
0
  struct curl_slist *beg;
1628
0
  unsigned int i;
1629
0
  struct Curl_llist_node *n;
1630
1631
0
  if(!data->cookies || (data->cookies->numcookies == 0))
1632
0
    return NULL;
1633
1634
  /* at first, remove expired cookies */
1635
0
  remove_expired(data->cookies);
1636
1637
0
  for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1638
0
    for(n = Curl_llist_head(&data->cookies->cookielist[i]); n;
1639
0
        n = Curl_node_next(n)) {
1640
0
      struct Cookie *c = Curl_node_elem(n);
1641
0
      char *line;
1642
0
      if(!c->domain)
1643
0
        continue;
1644
0
      line = get_netscape_format(c);
1645
0
      if(!line) {
1646
0
        curl_slist_free_all(list);
1647
0
        return NULL;
1648
0
      }
1649
0
      beg = Curl_slist_append_nodup(list, line);
1650
0
      if(!beg) {
1651
0
        curlx_free(line);
1652
0
        curl_slist_free_all(list);
1653
0
        return NULL;
1654
0
      }
1655
0
      list = beg;
1656
0
    }
1657
0
  }
1658
1659
0
  return list;
1660
0
}
1661
1662
struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
1663
0
{
1664
0
  struct curl_slist *list;
1665
0
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1666
0
  list = cookie_list(data);
1667
0
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1668
0
  return list;
1669
0
}
1670
1671
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
1672
21.4k
{
1673
21.4k
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1674
  /* only save the cookie file if a transfer was started (cookies->running is
1675
     set), as otherwise the cookies were not completely initialized and there
1676
     might be cookie files that were not loaded so saving the file is the
1677
     wrong thing. */
1678
21.4k
  if(data->cookies) {
1679
9.98k
    const char *cookiejar = CURL_EASY_STR(data, STRING_COOKIEJAR);
1680
9.98k
    if(cookiejar && data->cookies->running) {
1681
      /* if we have a destination file for all the cookies to get dumped to */
1682
6.63k
      CURLcode result = cookie_output(data, data->cookies, cookiejar);
1683
6.63k
      if(result)
1684
0
        infof(data, "WARNING: failed to save cookies in %s: %s",
1685
6.63k
              cookiejar, curl_easy_strerror(result));
1686
6.63k
    }
1687
1688
9.98k
    if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
1689
9.98k
      Curl_cookie_cleanup(data->cookies);
1690
9.98k
      data->cookies = NULL;
1691
9.98k
    }
1692
9.98k
  }
1693
21.4k
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1694
21.4k
}
1695
1696
void Curl_cookie_run(struct Curl_easy *data)
1697
6.63k
{
1698
6.63k
  Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1699
6.63k
  if(data->cookies)
1700
6.63k
    data->cookies->running = TRUE;
1701
6.63k
  Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1702
6.63k
}
1703
1704
#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */