Coverage Report

Created: 2026-07-16 06:10

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