Coverage Report

Created: 2026-12-01 06:27

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