Debian Codegraph @

deps/curl/lib/cookie.c

raw
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, 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.haxx.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 ***************************************************************************/
22
23 /***
24
25
26 RECEIVING COOKIE INFORMATION
27 ============================
28
29 struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
30 const char *file, struct CookieInfo *inc, bool newsession);
31
32 Inits a cookie struct to store data in a local file. This is always
33 called before any cookies are set.
34
35 struct Cookie *Curl_cookie_add(struct Curl_easy *data,
36 struct CookieInfo *c, bool httpheader, char *lineptr,
37 const char *domain, const char *path);
38
39 The 'lineptr' parameter is a full "Set-cookie:" line as
40 received from a server.
41
42 The function need to replace previously stored lines that this new
43 line supersedes.
44
45 It may remove lines that are expired.
46
47 It should return an indication of success/error.
48
49
50 SENDING COOKIE INFORMATION
51 ==========================
52
53 struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie,
54 char *host, char *path, bool secure);
55
56 For a given host and path, return a linked list of cookies that
57 the client should send to the server if used now. The secure
58 boolean informs the cookie if a secure connection is achieved or
59 not.
60
61 It shall only return cookies that haven't expired.
62
63
64 Example set of cookies:
65
66 Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
67 Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
68 domain=.fidelity.com; path=/ftgw; secure
69 Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
70 domain=.fidelity.com; path=/; secure
71 Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
72 domain=.fidelity.com; path=/; secure
73 Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
74 domain=.fidelity.com; path=/; secure
75 Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
76 domain=.fidelity.com; path=/; secure
77 Set-cookie:
78 Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
79 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
80 ****/
81
82
83 #include "curl_setup.h"
84
85 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
86
87 #include "urldata.h"
88 #include "cookie.h"
89 #include "psl.h"
90 #include "strtok.h"
91 #include "sendf.h"
92 #include "slist.h"
93 #include "share.h"
94 #include "strtoofft.h"
95 #include "strcase.h"
96 #include "curl_get_line.h"
97 #include "curl_memrchr.h"
98 #include "inet_pton.h"
99 #include "parsedate.h"
100 #include "rand.h"
101 #include "rename.h"
102
103 /* The last 3 #include files should be in this order */
104 #include "curl_printf.h"
105 #include "curl_memory.h"
106 #include "memdebug.h"
107
108 static void freecookie(struct Cookie *co)
109 {
110 free(co->expirestr);
111 free(co->domain);
112 free(co->path);
113 free(co->spath);
114 free(co->name);
115 free(co->value);
116 free(co->maxage);
117 free(co->version);
118 free(co);
119 }
120
121 static bool tailmatch(const char *cooke_domain, const char *hostname)
122 {
123 size_t cookie_domain_len = strlen(cooke_domain);
124 size_t hostname_len = strlen(hostname);
125
126 if(hostname_len < cookie_domain_len)
127 return FALSE;
128
129 if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len))
130 return FALSE;
131
132 /* A lead char of cookie_domain is not '.'.
133 RFC6265 4.1.2.3. The Domain Attribute says:
134 For example, if the value of the Domain attribute is
135 "example.com", the user agent will include the cookie in the Cookie
136 header when making HTTP requests to example.com, www.example.com, and
137 www.corp.example.com.
138 */
139 if(hostname_len == cookie_domain_len)
140 return TRUE;
141 if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
142 return TRUE;
143 return FALSE;
144 }
145
146 /*
147 * Return true if the given string is an IP(v4|v6) address.
148 */
149 static bool isip(const char *domain)
150 {
151 struct in_addr addr;
152 #ifdef ENABLE_IPV6
153 struct in6_addr addr6;
154 #endif
155
156 if(Curl_inet_pton(AF_INET, domain, &addr)
157 #ifdef ENABLE_IPV6
158 || Curl_inet_pton(AF_INET6, domain, &addr6)
159 #endif
160 ) {
161 /* domain name given as IP address */
162 return TRUE;
163 }
164
165 return FALSE;
166 }
167
168 /*
169 * matching cookie path and url path
170 * RFC6265 5.1.4 Paths and Path-Match
171 */
172 static bool pathmatch(const char *cookie_path, const char *request_uri)
173 {
174 size_t cookie_path_len;
175 size_t uri_path_len;
176 char *uri_path = NULL;
177 char *pos;
178 bool ret = FALSE;
179
180 /* cookie_path must not have last '/' separator. ex: /sample */
181 cookie_path_len = strlen(cookie_path);
182 if(1 == cookie_path_len) {
183 /* cookie_path must be '/' */
184 return TRUE;
185 }
186
187 uri_path = strdup(request_uri);
188 if(!uri_path)
189 return FALSE;
190 pos = strchr(uri_path, '?');
191 if(pos)
192 *pos = 0x0;
193
194 /* #-fragments are already cut off! */
195 if(0 == strlen(uri_path) || uri_path[0] != '/') {
196 free(uri_path);
197 uri_path = strdup("/");
198 if(!uri_path)
199 return FALSE;
200 }
201
202 /* here, RFC6265 5.1.4 says
203 4. Output the characters of the uri-path from the first character up
204 to, but not including, the right-most %x2F ("/").
205 but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
206 without redirect.
207 Ignore this algorithm because /hoge is uri path for this case
208 (uri path is not /).
209 */
210
211 uri_path_len = strlen(uri_path);
212
213 if(uri_path_len < cookie_path_len) {
214 ret = FALSE;
215 goto pathmatched;
216 }
217
218 /* not using checkprefix() because matching should be case-sensitive */
219 if(strncmp(cookie_path, uri_path, cookie_path_len)) {
220 ret = FALSE;
221 goto pathmatched;
222 }
223
224 /* The cookie-path and the uri-path are identical. */
225 if(cookie_path_len == uri_path_len) {
226 ret = TRUE;
227 goto pathmatched;
228 }
229
230 /* here, cookie_path_len < uri_path_len */
231 if(uri_path[cookie_path_len] == '/') {
232 ret = TRUE;
233 goto pathmatched;
234 }
235
236 ret = FALSE;
237
238 pathmatched:
239 free(uri_path);
240 return ret;
241 }
242
243 /*
244 * Return the top-level domain, for optimal hashing.
245 */
246 static const char *get_top_domain(const char * const domain, size_t *outlen)
247 {
248 size_t len;
249 const char *first = NULL, *last;
250
251 if(!domain)
252 return NULL;
253
254 len = strlen(domain);
255 last = memrchr(domain, '.', len);
256 if(last) {
257 first = memrchr(domain, '.', (last - domain));
258 if(first)
259 len -= (++first - domain);
260 }
261
262 if(outlen)
263 *outlen = len;
264
265 return first? first: domain;
266 }
267
268 /*
269 * A case-insensitive hash for the cookie domains.
270 */
271 static size_t cookie_hash_domain(const char *domain, const size_t len)
272 {
273 const char *end = domain + len;
274 size_t h = 5381;
275
276 while(domain < end) {
277 h += h << 5;
278 h ^= Curl_raw_toupper(*domain++);
279 }
280
281 return (h % COOKIE_HASH_SIZE);
282 }
283
284 /*
285 * Hash this domain.
286 */
287 static size_t cookiehash(const char * const domain)
288 {
289 const char *top;
290 size_t len;
291
292 if(!domain || isip(domain))
293 return 0;
294
295 top = get_top_domain(domain, &len);
296 return cookie_hash_domain(top, len);
297 }
298
299 /*
300 * cookie path sanitize
301 */
302 static char *sanitize_cookie_path(const char *cookie_path)
303 {
304 size_t len;
305 char *new_path = strdup(cookie_path);
306 if(!new_path)
307 return NULL;
308
309 /* some stupid site sends path attribute with '"'. */
310 len = strlen(new_path);
311 if(new_path[0] == '\"') {
312 memmove((void *)new_path, (const void *)(new_path + 1), len);
313 len--;
314 }
315 if(len && (new_path[len - 1] == '\"')) {
316 new_path[len - 1] = 0x0;
317 len--;
318 }
319
320 /* RFC6265 5.2.4 The Path Attribute */
321 if(new_path[0] != '/') {
322 /* Let cookie-path be the default-path. */
323 free(new_path);
324 new_path = strdup("/");
325 return new_path;
326 }
327
328 /* convert /hoge/ to /hoge */
329 if(len && new_path[len - 1] == '/') {
330 new_path[len - 1] = 0x0;
331 }
332
333 return new_path;
334 }
335
336 /*
337 * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
338 *
339 * NOTE: OOM or cookie parsing failures are ignored.
340 */
341 void Curl_cookie_loadfiles(struct Curl_easy *data)
342 {
343 struct curl_slist *list = data->change.cookielist;
344 if(list) {
345 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
346 while(list) {
347 struct CookieInfo *newcookies = Curl_cookie_init(data,
348 list->data,
349 data->cookies,
350 data->set.cookiesession);
351 if(!newcookies)
352 /* Failure may be due to OOM or a bad cookie; both are ignored
353 * but only the first should be
354 */
355 infof(data, "ignoring failed cookie_init for %s\n", list->data);
356 else
357 data->cookies = newcookies;
358 list = list->next;
359 }
360 curl_slist_free_all(data->change.cookielist); /* clean up list */
361 data->change.cookielist = NULL; /* don't do this again! */
362 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
363 }
364 }
365
366 /*
367 * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
368 * that will be freed before the allocated string is stored there.
369 *
370 * It is meant to easily replace strdup()
371 */
372 static void strstore(char **str, const char *newstr)
373 {
374 free(*str);
375 *str = strdup(newstr);
376 }
377
378 /*
379 * remove_expired() removes expired cookies.
380 */
381 static void remove_expired(struct CookieInfo *cookies)
382 {
383 struct Cookie *co, *nx;
384 curl_off_t now = (curl_off_t)time(NULL);
385 unsigned int i;
386
387 for(i = 0; i < COOKIE_HASH_SIZE; i++) {
388 struct Cookie *pv = NULL;
389 co = cookies->cookies[i];
390 while(co) {
391 nx = co->next;
392 if(co->expires && co->expires < now) {
393 if(!pv) {
394 cookies->cookies[i] = co->next;
395 }
396 else {
397 pv->next = co->next;
398 }
399 cookies->numcookies--;
400 freecookie(co);
401 }
402 else {
403 pv = co;
404 }
405 co = nx;
406 }
407 }
408 }
409
410 /* Make sure domain contains a dot or is localhost. */
411 static bool bad_domain(const char *domain)
412 {
413 return !strchr(domain, '.') && !strcasecompare(domain, "localhost");
414 }
415
416 /****************************************************************************
417 *
418 * Curl_cookie_add()
419 *
420 * Add a single cookie line to the cookie keeping object.
421 *
422 * Be aware that sometimes we get an IP-only host name, and that might also be
423 * a numerical IPv6 address.
424 *
425 * Returns NULL on out of memory or invalid cookie. This is suboptimal,
426 * as they should be treated separately.
427 ***************************************************************************/
428
429 struct Cookie *
430 Curl_cookie_add(struct Curl_easy *data,
431 /* The 'data' pointer here may be NULL at times, and thus
432 must only be used very carefully for things that can deal
433 with data being NULL. Such as infof() and similar */
434
435 struct CookieInfo *c,
436 bool httpheader, /* TRUE if HTTP header-style line */
437 bool noexpire, /* if TRUE, skip remove_expired() */
438 char *lineptr, /* first character of the line */
439 const char *domain, /* default domain */
440 const char *path, /* full path used when this cookie is set,
441 used to get default path for the cookie
442 unless set */
443 bool secure) /* TRUE if connection is over secure origin */
444 {
445 struct Cookie *clist;
446 struct Cookie *co;
447 struct Cookie *lastc = NULL;
448 time_t now = time(NULL);
449 bool replace_old = FALSE;
450 bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
451 size_t myhash;
452
453 #ifdef CURL_DISABLE_VERBOSE_STRINGS
454 (void)data;
455 #endif
456
457 /* First, alloc and init a new struct for it */
458 co = calloc(1, sizeof(struct Cookie));
459 if(!co)
460 return NULL; /* bail out if we're this low on memory */
461
462 if(httpheader) {
463 /* This line was read off a HTTP-header */
464 char name[MAX_NAME];
465 char what[MAX_NAME];
466 const char *ptr;
467 const char *semiptr;
468
469 size_t linelength = strlen(lineptr);
470 if(linelength > MAX_COOKIE_LINE) {
471 /* discard overly long lines at once */
472 free(co);
473 return NULL;
474 }
475
476 semiptr = strchr(lineptr, ';'); /* first, find a semicolon */
477
478 while(*lineptr && ISBLANK(*lineptr))
479 lineptr++;
480
481 ptr = lineptr;
482 do {
483 /* we have a <what>=<this> pair or a stand-alone word here */
484 name[0] = what[0] = 0; /* init the buffers */
485 if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
486 MAX_NAME_TXT "[^;\r\n]",
487 name, what)) {
488 /* Use strstore() below to properly deal with received cookie
489 headers that have the same string property set more than once,
490 and then we use the last one. */
491 const char *whatptr;
492 bool done = FALSE;
493 bool sep;
494 size_t len = strlen(what);
495 size_t nlen = strlen(name);
496 const char *endofn = &ptr[ nlen ];
497
498 if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
499 ((nlen + len) > MAX_NAME)) {
500 /* too long individual name or contents, or too long combination of
501 name + contents. Chrome and Firefox support 4095 or 4096 bytes
502 combo. */
503 freecookie(co);
504 infof(data, "oversized cookie dropped, name/val %zu + %zu bytes\n",
505 nlen, len);
506 return NULL;
507 }
508
509 /* name ends with a '=' ? */
510 sep = (*endofn == '=')?TRUE:FALSE;
511
512 if(nlen) {
513 endofn--; /* move to the last character */
514 if(ISBLANK(*endofn)) {
515 /* skip trailing spaces in name */
516 while(*endofn && ISBLANK(*endofn) && nlen) {
517 endofn--;
518 nlen--;
519 }
520 name[nlen] = 0; /* new end of name */
521 }
522 }
523
524 /* Strip off trailing whitespace from the 'what' */
525 while(len && ISBLANK(what[len-1])) {
526 what[len-1] = 0;
527 len--;
528 }
529
530 /* Skip leading whitespace from the 'what' */
531 whatptr = what;
532 while(*whatptr && ISBLANK(*whatptr))
533 whatptr++;
534
535 /*
536 * Check if we have a reserved prefix set before anything else, as we
537 * otherwise have to test for the prefix in both the cookie name and
538 * "the rest". Prefixes must start with '__' and end with a '-', so
539 * only test for names where that can possibly be true.
540 */
541 if(nlen > 3 && name[0] == '_' && name[1] == '_') {
542 if(!strncmp("__Secure-", name, 9))
543 co->prefix |= COOKIE_PREFIX__SECURE;
544 else if(!strncmp("__Host-", name, 7))
545 co->prefix |= COOKIE_PREFIX__HOST;
546 }
547
548 if(!co->name) {
549 /* The very first name/value pair is the actual cookie name */
550 if(!sep) {
551 /* Bad name/value pair. */
552 badcookie = TRUE;
553 break;
554 }
555 co->name = strdup(name);
556 co->value = strdup(whatptr);
557 done = TRUE;
558 if(!co->name || !co->value) {
559 badcookie = TRUE;
560 break;
561 }
562 }
563 else if(!len) {
564 /* this was a "<name>=" with no content, and we must allow
565 'secure' and 'httponly' specified this weirdly */
566 done = TRUE;
567 /*
568 * secure cookies are only allowed to be set when the connection is
569 * using a secure protocol, or when the cookie is being set by
570 * reading from file
571 */
572 if(strcasecompare("secure", name)) {
573 if(secure || !c->running) {
574 co->secure = TRUE;
575 }
576 else {
577 badcookie = TRUE;
578 break;
579 }
580 }
581 else if(strcasecompare("httponly", name))
582 co->httponly = TRUE;
583 else if(sep)
584 /* there was a '=' so we're not done parsing this field */
585 done = FALSE;
586 }
587 if(done)
588 ;
589 else if(strcasecompare("path", name)) {
590 strstore(&co->path, whatptr);
591 if(!co->path) {
592 badcookie = TRUE; /* out of memory bad */
593 break;
594 }
595 free(co->spath); /* if this is set again */
596 co->spath = sanitize_cookie_path(co->path);
597 if(!co->spath) {
598 badcookie = TRUE; /* out of memory bad */
599 break;
600 }
601 }
602 else if(strcasecompare("domain", name)) {
603 bool is_ip;
604
605 /* Now, we make sure that our host is within the given domain,
606 or the given domain is not valid and thus cannot be set. */
607
608 if('.' == whatptr[0])
609 whatptr++; /* ignore preceding dot */
610
611 #ifndef USE_LIBPSL
612 /*
613 * Without PSL we don't know when the incoming cookie is set on a
614 * TLD or otherwise "protected" suffix. To reduce risk, we require a
615 * dot OR the exact host name being "localhost".
616 */
617 if(bad_domain(whatptr))
618 domain = ":";
619 #endif
620
621 is_ip = isip(domain ? domain : whatptr);
622
623 if(!domain
624 || (is_ip && !strcmp(whatptr, domain))
625 || (!is_ip && tailmatch(whatptr, domain))) {
626 strstore(&co->domain, whatptr);
627 if(!co->domain) {
628 badcookie = TRUE;
629 break;
630 }
631 if(!is_ip)
632 co->tailmatch = TRUE; /* we always do that if the domain name was
633 given */
634 }
635 else {
636 /* we did not get a tailmatch and then the attempted set domain
637 is not a domain to which the current host belongs. Mark as
638 bad. */
639 badcookie = TRUE;
640 infof(data, "skipped cookie with bad tailmatch domain: %s\n",
641 whatptr);
642 }
643 }
644 else if(strcasecompare("version", name)) {
645 strstore(&co->version, whatptr);
646 if(!co->version) {
647 badcookie = TRUE;
648 break;
649 }
650 }
651 else if(strcasecompare("max-age", name)) {
652 /* Defined in RFC2109:
653
654 Optional. The Max-Age attribute defines the lifetime of the
655 cookie, in seconds. The delta-seconds value is a decimal non-
656 negative integer. After delta-seconds seconds elapse, the
657 client should discard the cookie. A value of zero means the
658 cookie should be discarded immediately.
659
660 */
661 strstore(&co->maxage, whatptr);
662 if(!co->maxage) {
663 badcookie = TRUE;
664 break;
665 }
666 }
667 else if(strcasecompare("expires", name)) {
668 strstore(&co->expirestr, whatptr);
669 if(!co->expirestr) {
670 badcookie = TRUE;
671 break;
672 }
673 }
674 /*
675 else this is the second (or more) name we don't know
676 about! */
677 }
678 else {
679 /* this is an "illegal" <what>=<this> pair */
680 }
681
682 if(!semiptr || !*semiptr) {
683 /* we already know there are no more cookies */
684 semiptr = NULL;
685 continue;
686 }
687
688 ptr = semiptr + 1;
689 while(*ptr && ISBLANK(*ptr))
690 ptr++;
691 semiptr = strchr(ptr, ';'); /* now, find the next semicolon */
692
693 if(!semiptr && *ptr)
694 /* There are no more semicolons, but there's a final name=value pair
695 coming up */
696 semiptr = strchr(ptr, '\0');
697 } while(semiptr);
698
699 if(co->maxage) {
700 CURLofft offt;
701 offt = curlx_strtoofft((*co->maxage == '\"')?
702 &co->maxage[1]:&co->maxage[0], NULL, 10,
703 &co->expires);
704 if(offt == CURL_OFFT_FLOW)
705 /* overflow, used max value */
706 co->expires = CURL_OFF_T_MAX;
707 else if(!offt) {
708 if(!co->expires)
709 /* already expired */
710 co->expires = 1;
711 else if(CURL_OFF_T_MAX - now < co->expires)
712 /* would overflow */
713 co->expires = CURL_OFF_T_MAX;
714 else
715 co->expires += now;
716 }
717 }
718 else if(co->expirestr) {
719 /* Note that if the date couldn't get parsed for whatever reason,
720 the cookie will be treated as a session cookie */
721 co->expires = Curl_getdate_capped(co->expirestr);
722
723 /* Session cookies have expires set to 0 so if we get that back
724 from the date parser let's add a second to make it a
725 non-session cookie */
726 if(co->expires == 0)
727 co->expires = 1;
728 else if(co->expires < 0)
729 co->expires = 0;
730 }
731
732 if(!badcookie && !co->domain) {
733 if(domain) {
734 /* no domain was given in the header line, set the default */
735 co->domain = strdup(domain);
736 if(!co->domain)
737 badcookie = TRUE;
738 }
739 }
740
741 if(!badcookie && !co->path && path) {
742 /* No path was given in the header line, set the default.
743 Note that the passed-in path to this function MAY have a '?' and
744 following part that MUST not be stored as part of the path. */
745 char *queryp = strchr(path, '?');
746
747 /* queryp is where the interesting part of the path ends, so now we
748 want to the find the last */
749 char *endslash;
750 if(!queryp)
751 endslash = strrchr(path, '/');
752 else
753 endslash = memrchr(path, '/', (queryp - path));
754 if(endslash) {
755 size_t pathlen = (endslash-path + 1); /* include end slash */
756 co->path = malloc(pathlen + 1); /* one extra for the zero byte */
757 if(co->path) {
758 memcpy(co->path, path, pathlen);
759 co->path[pathlen] = 0; /* zero terminate */
760 co->spath = sanitize_cookie_path(co->path);
761 if(!co->spath)
762 badcookie = TRUE; /* out of memory bad */
763 }
764 else
765 badcookie = TRUE;
766 }
767 }
768
769 if(badcookie || !co->name) {
770 /* we didn't get a cookie name or a bad one,
771 this is an illegal line, bail out */
772 freecookie(co);
773 return NULL;
774 }
775
776 }
777 else {
778 /* This line is NOT a HTTP header style line, we do offer support for
779 reading the odd netscape cookies-file format here */
780 char *ptr;
781 char *firstptr;
782 char *tok_buf = NULL;
783 int fields;
784
785 /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
786 marked with httpOnly after the domain name are not accessible
787 from javascripts, but since curl does not operate at javascript
788 level, we include them anyway. In Firefox's cookie files, these
789 lines are preceded with #HttpOnly_ and then everything is
790 as usual, so we skip 10 characters of the line..
791 */
792 if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
793 lineptr += 10;
794 co->httponly = TRUE;
795 }
796
797 if(lineptr[0]=='#') {
798 /* don't even try the comments */
799 free(co);
800 return NULL;
801 }
802 /* strip off the possible end-of-line characters */
803 ptr = strchr(lineptr, '\r');
804 if(ptr)
805 *ptr = 0; /* clear it */
806 ptr = strchr(lineptr, '\n');
807 if(ptr)
808 *ptr = 0; /* clear it */
809
810 firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
811
812 /* Now loop through the fields and init the struct we already have
813 allocated */
814 for(ptr = firstptr, fields = 0; ptr && !badcookie;
815 ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
816 switch(fields) {
817 case 0:
818 if(ptr[0]=='.') /* skip preceding dots */
819 ptr++;
820 co->domain = strdup(ptr);
821 if(!co->domain)
822 badcookie = TRUE;
823 break;
824 case 1:
825 /* flag: A TRUE/FALSE value indicating if all machines within a given
826 domain can access the variable. Set TRUE when the cookie says
827 .domain.com and to false when the domain is complete www.domain.com
828 */
829 co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
830 break;
831 case 2:
832 /* The file format allows the path field to remain not filled in */
833 if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
834 /* only if the path doesn't look like a boolean option! */
835 co->path = strdup(ptr);
836 if(!co->path)
837 badcookie = TRUE;
838 else {
839 co->spath = sanitize_cookie_path(co->path);
840 if(!co->spath) {
841 badcookie = TRUE; /* out of memory bad */
842 }
843 }
844 break;
845 }
846 /* this doesn't look like a path, make one up! */
847 co->path = strdup("/");
848 if(!co->path)
849 badcookie = TRUE;
850 co->spath = strdup("/");
851 if(!co->spath)
852 badcookie = TRUE;
853 fields++; /* add a field and fall down to secure */
854 /* FALLTHROUGH */
855 case 3:
856 co->secure = FALSE;
857 if(strcasecompare(ptr, "TRUE")) {
858 if(secure || c->running)
859 co->secure = TRUE;
860 else
861 badcookie = TRUE;
862 }
863 break;
864 case 4:
865 if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
866 badcookie = TRUE;
867 break;
868 case 5:
869 co->name = strdup(ptr);
870 if(!co->name)
871 badcookie = TRUE;
872 else {
873 /* For Netscape file format cookies we check prefix on the name */
874 if(strncasecompare("__Secure-", co->name, 9))
875 co->prefix |= COOKIE_PREFIX__SECURE;
876 else if(strncasecompare("__Host-", co->name, 7))
877 co->prefix |= COOKIE_PREFIX__HOST;
878 }
879 break;
880 case 6:
881 co->value = strdup(ptr);
882 if(!co->value)
883 badcookie = TRUE;
884 break;
885 }
886 }
887 if(6 == fields) {
888 /* we got a cookie with blank contents, fix it */
889 co->value = strdup("");
890 if(!co->value)
891 badcookie = TRUE;
892 else
893 fields++;
894 }
895
896 if(!badcookie && (7 != fields))
897 /* we did not find the sufficient number of fields */
898 badcookie = TRUE;
899
900 if(badcookie) {
901 freecookie(co);
902 return NULL;
903 }
904
905 }
906
907 if(co->prefix & COOKIE_PREFIX__SECURE) {
908 /* The __Secure- prefix only requires that the cookie be set secure */
909 if(!co->secure) {
910 freecookie(co);
911 return NULL;
912 }
913 }
914 if(co->prefix & COOKIE_PREFIX__HOST) {
915 /*
916 * The __Host- prefix requires the cookie to be secure, have a "/" path
917 * and not have a domain set.
918 */
919 if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
920 ;
921 else {
922 freecookie(co);
923 return NULL;
924 }
925 }
926
927 if(!c->running && /* read from a file */
928 c->newsession && /* clean session cookies */
929 !co->expires) { /* this is a session cookie since it doesn't expire! */
930 freecookie(co);
931 return NULL;
932 }
933
934 co->livecookie = c->running;
935 co->creationtime = ++c->lastct;
936
937 /* now, we have parsed the incoming line, we must now check if this
938 supersedes an already existing cookie, which it may if the previous have
939 the same domain and path as this */
940
941 /* at first, remove expired cookies */
942 if(!noexpire)
943 remove_expired(c);
944
945 #ifdef USE_LIBPSL
946 /* Check if the domain is a Public Suffix and if yes, ignore the cookie. */
947 if(domain && co->domain && !isip(co->domain)) {
948 const psl_ctx_t *psl = Curl_psl_use(data);
949 int acceptable;
950
951 if(psl) {
952 acceptable = psl_is_cookie_domain_acceptable(psl, domain, co->domain);
953 Curl_psl_release(data);
954 }
955 else
956 acceptable = !bad_domain(domain);
957
958 if(!acceptable) {
959 infof(data, "cookie '%s' dropped, domain '%s' must not "
960 "set cookies for '%s'\n", co->name, domain, co->domain);
961 freecookie(co);
962 return NULL;
963 }
964 }
965 #endif
966
967 myhash = cookiehash(co->domain);
968 clist = c->cookies[myhash];
969 replace_old = FALSE;
970 while(clist) {
971 if(strcasecompare(clist->name, co->name)) {
972 /* the names are identical */
973
974 if(clist->domain && co->domain) {
975 if(strcasecompare(clist->domain, co->domain) &&
976 (clist->tailmatch == co->tailmatch))
977 /* The domains are identical */
978 replace_old = TRUE;
979 }
980 else if(!clist->domain && !co->domain)
981 replace_old = TRUE;
982
983 if(replace_old) {
984 /* the domains were identical */
985
986 if(clist->spath && co->spath) {
987 if(clist->secure && !co->secure && !secure) {
988 size_t cllen;
989 const char *sep;
990
991 /*
992 * A non-secure cookie may not overlay an existing secure cookie.
993 * For an existing cookie "a" with path "/login", refuse a new
994 * cookie "a" with for example path "/login/en", while the path
995 * "/loginhelper" is ok.
996 */
997
998 sep = strchr(clist->spath + 1, '/');
999
1000 if(sep)
1001 cllen = sep - clist->spath;
1002 else
1003 cllen = strlen(clist->spath);
1004
1005 if(strncasecompare(clist->spath, co->spath, cllen)) {
1006 freecookie(co);
1007 return NULL;
1008 }
1009 }
1010 else if(strcasecompare(clist->spath, co->spath))
1011 replace_old = TRUE;
1012 else
1013 replace_old = FALSE;
1014 }
1015 else if(!clist->spath && !co->spath)
1016 replace_old = TRUE;
1017 else
1018 replace_old = FALSE;
1019
1020 }
1021
1022 if(replace_old && !co->livecookie && clist->livecookie) {
1023 /* Both cookies matched fine, except that the already present
1024 cookie is "live", which means it was set from a header, while
1025 the new one isn't "live" and thus only read from a file. We let
1026 live cookies stay alive */
1027
1028 /* Free the newcomer and get out of here! */
1029 freecookie(co);
1030 return NULL;
1031 }
1032
1033 if(replace_old) {
1034 co->next = clist->next; /* get the next-pointer first */
1035
1036 /* when replacing, creationtime is kept from old */
1037 co->creationtime = clist->creationtime;
1038
1039 /* then free all the old pointers */
1040 free(clist->name);
1041 free(clist->value);
1042 free(clist->domain);
1043 free(clist->path);
1044 free(clist->spath);
1045 free(clist->expirestr);
1046 free(clist->version);
1047 free(clist->maxage);
1048
1049 *clist = *co; /* then store all the new data */
1050
1051 free(co); /* free the newly allocated memory */
1052 co = clist; /* point to the previous struct instead */
1053
1054 /* We have replaced a cookie, now skip the rest of the list but
1055 make sure the 'lastc' pointer is properly set */
1056 do {
1057 lastc = clist;
1058 clist = clist->next;
1059 } while(clist);
1060 break;
1061 }
1062 }
1063 lastc = clist;
1064 clist = clist->next;
1065 }
1066
1067 if(c->running)
1068 /* Only show this when NOT reading the cookies from a file */
1069 infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
1070 "expire %" CURL_FORMAT_CURL_OFF_T "\n",
1071 replace_old?"Replaced":"Added", co->name, co->value,
1072 co->domain, co->path, co->expires);
1073
1074 if(!replace_old) {
1075 /* then make the last item point on this new one */
1076 if(lastc)
1077 lastc->next = co;
1078 else
1079 c->cookies[myhash] = co;
1080 c->numcookies++; /* one more cookie in the jar */
1081 }
1082
1083 return co;
1084 }
1085
1086
1087 /*****************************************************************************
1088 *
1089 * Curl_cookie_init()
1090 *
1091 * Inits a cookie struct to read data from a local file. This is always
1092 * called before any cookies are set. File may be NULL.
1093 *
1094 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
1095 *
1096 * Note that 'data' might be called as NULL pointer.
1097 *
1098 * Returns NULL on out of memory. Invalid cookies are ignored.
1099 ****************************************************************************/
1100 struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
1101 const char *file,
1102 struct CookieInfo *inc,
1103 bool newsession)
1104 {
1105 struct CookieInfo *c;
1106 FILE *fp = NULL;
1107 bool fromfile = TRUE;
1108 char *line = NULL;
1109
1110 if(NULL == inc) {
1111 /* we didn't get a struct, create one */
1112 c = calloc(1, sizeof(struct CookieInfo));
1113 if(!c)
1114 return NULL; /* failed to get memory */
1115 c->filename = strdup(file?file:"none"); /* copy the name just in case */
1116 if(!c->filename)
1117 goto fail; /* failed to get memory */
1118 }
1119 else {
1120 /* we got an already existing one, use that */
1121 c = inc;
1122 }
1123 c->running = FALSE; /* this is not running, this is init */
1124
1125 if(file && !strcmp(file, "-")) {
1126 fp = stdin;
1127 fromfile = FALSE;
1128 }
1129 else if(file && !*file) {
1130 /* points to a "" string */
1131 fp = NULL;
1132 }
1133 else
1134 fp = file?fopen(file, FOPEN_READTEXT):NULL;
1135
1136 c->newsession = newsession; /* new session? */
1137
1138 if(fp) {
1139 char *lineptr;
1140 bool headerline;
1141
1142 line = malloc(MAX_COOKIE_LINE);
1143 if(!line)
1144 goto fail;
1145 while(Curl_get_line(line, MAX_COOKIE_LINE, fp)) {
1146 if(checkprefix("Set-Cookie:", line)) {
1147 /* This is a cookie line, get it! */
1148 lineptr = &line[11];
1149 headerline = TRUE;
1150 }
1151 else {
1152 lineptr = line;
1153 headerline = FALSE;
1154 }
1155 while(*lineptr && ISBLANK(*lineptr))
1156 lineptr++;
1157
1158 Curl_cookie_add(data, c, headerline, TRUE, lineptr, NULL, NULL, TRUE);
1159 }
1160 free(line); /* free the line buffer */
1161 remove_expired(c); /* run this once, not on every cookie */
1162
1163 if(fromfile)
1164 fclose(fp);
1165 }
1166
1167 c->running = TRUE; /* now, we're running */
1168 if(data)
1169 data->state.cookie_engine = TRUE;
1170
1171 return c;
1172
1173 fail:
1174 free(line);
1175 if(!inc)
1176 /* Only clean up if we allocated it here, as the original could still be in
1177 * use by a share handle */
1178 Curl_cookie_cleanup(c);
1179 if(fromfile && fp)
1180 fclose(fp);
1181 return NULL; /* out of memory */
1182 }
1183
1184 /* sort this so that the longest path gets before the shorter path */
1185 static int cookie_sort(const void *p1, const void *p2)
1186 {
1187 struct Cookie *c1 = *(struct Cookie **)p1;
1188 struct Cookie *c2 = *(struct Cookie **)p2;
1189 size_t l1, l2;
1190
1191 /* 1 - compare cookie path lengths */
1192 l1 = c1->path ? strlen(c1->path) : 0;
1193 l2 = c2->path ? strlen(c2->path) : 0;
1194
1195 if(l1 != l2)
1196 return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
1197
1198 /* 2 - compare cookie domain lengths */
1199 l1 = c1->domain ? strlen(c1->domain) : 0;
1200 l2 = c2->domain ? strlen(c2->domain) : 0;
1201
1202 if(l1 != l2)
1203 return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
1204
1205 /* 3 - compare cookie name lengths */
1206 l1 = c1->name ? strlen(c1->name) : 0;
1207 l2 = c2->name ? strlen(c2->name) : 0;
1208
1209 if(l1 != l2)
1210 return (l2 > l1) ? 1 : -1;
1211
1212 /* 4 - compare cookie creation time */
1213 return (c2->creationtime > c1->creationtime) ? 1 : -1;
1214 }
1215
1216 /* sort cookies only according to creation time */
1217 static int cookie_sort_ct(const void *p1, const void *p2)
1218 {
1219 struct Cookie *c1 = *(struct Cookie **)p1;
1220 struct Cookie *c2 = *(struct Cookie **)p2;
1221
1222 return (c2->creationtime > c1->creationtime) ? 1 : -1;
1223 }
1224
1225 #define CLONE(field) \
1226 do { \
1227 if(src->field) { \
1228 d->field = strdup(src->field); \
1229 if(!d->field) \
1230 goto fail; \
1231 } \
1232 } while(0)
1233
1234 static struct Cookie *dup_cookie(struct Cookie *src)
1235 {
1236 struct Cookie *d = calloc(sizeof(struct Cookie), 1);
1237 if(d) {
1238 CLONE(expirestr);
1239 CLONE(domain);
1240 CLONE(path);
1241 CLONE(spath);
1242 CLONE(name);
1243 CLONE(value);
1244 CLONE(maxage);
1245 CLONE(version);
1246 d->expires = src->expires;
1247 d->tailmatch = src->tailmatch;
1248 d->secure = src->secure;
1249 d->livecookie = src->livecookie;
1250 d->httponly = src->httponly;
1251 d->creationtime = src->creationtime;
1252 }
1253 return d;
1254
1255 fail:
1256 freecookie(d);
1257 return NULL;
1258 }
1259
1260 /*****************************************************************************
1261 *
1262 * Curl_cookie_getlist()
1263 *
1264 * For a given host and path, return a linked list of cookies that the
1265 * client should send to the server if used now. The secure boolean informs
1266 * the cookie if a secure connection is achieved or not.
1267 *
1268 * It shall only return cookies that haven't expired.
1269 *
1270 ****************************************************************************/
1271
1272 struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
1273 const char *host, const char *path,
1274 bool secure)
1275 {
1276 struct Cookie *newco;
1277 struct Cookie *co;
1278 struct Cookie *mainco = NULL;
1279 size_t matches = 0;
1280 bool is_ip;
1281 const size_t myhash = cookiehash(host);
1282
1283 if(!c || !c->cookies[myhash])
1284 return NULL; /* no cookie struct or no cookies in the struct */
1285
1286 /* at first, remove expired cookies */
1287 remove_expired(c);
1288
1289 /* check if host is an IP(v4|v6) address */
1290 is_ip = isip(host);
1291
1292 co = c->cookies[myhash];
1293
1294 while(co) {
1295 /* if the cookie requires we're secure we must only continue if we are! */
1296 if(co->secure?secure:TRUE) {
1297
1298 /* now check if the domain is correct */
1299 if(!co->domain ||
1300 (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
1301 ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
1302 /* the right part of the host matches the domain stuff in the
1303 cookie data */
1304
1305 /* now check the left part of the path with the cookies path
1306 requirement */
1307 if(!co->spath || pathmatch(co->spath, path) ) {
1308
1309 /* and now, we know this is a match and we should create an
1310 entry for the return-linked-list */
1311
1312 newco = dup_cookie(co);
1313 if(newco) {
1314 /* then modify our next */
1315 newco->next = mainco;
1316
1317 /* point the main to us */
1318 mainco = newco;
1319
1320 matches++;
1321 }
1322 else
1323 goto fail;
1324 }
1325 }
1326 }
1327 co = co->next;
1328 }
1329
1330 if(matches) {
1331 /* Now we need to make sure that if there is a name appearing more than
1332 once, the longest specified path version comes first. To make this
1333 the swiftest way, we just sort them all based on path length. */
1334 struct Cookie **array;
1335 size_t i;
1336
1337 /* alloc an array and store all cookie pointers */
1338 array = malloc(sizeof(struct Cookie *) * matches);
1339 if(!array)
1340 goto fail;
1341
1342 co = mainco;
1343
1344 for(i = 0; co; co = co->next)
1345 array[i++] = co;
1346
1347 /* now sort the cookie pointers in path length order */
1348 qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
1349
1350 /* remake the linked list order according to the new order */
1351
1352 mainco = array[0]; /* start here */
1353 for(i = 0; i<matches-1; i++)
1354 array[i]->next = array[i + 1];
1355 array[matches-1]->next = NULL; /* terminate the list */
1356
1357 free(array); /* remove the temporary data again */
1358 }
1359
1360 return mainco; /* return the new list */
1361
1362 fail:
1363 /* failure, clear up the allocated chain and return NULL */
1364 Curl_cookie_freelist(mainco);
1365 return NULL;
1366 }
1367
1368 /*****************************************************************************
1369 *
1370 * Curl_cookie_clearall()
1371 *
1372 * Clear all existing cookies and reset the counter.
1373 *
1374 ****************************************************************************/
1375 void Curl_cookie_clearall(struct CookieInfo *cookies)
1376 {
1377 if(cookies) {
1378 unsigned int i;
1379 for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1380 Curl_cookie_freelist(cookies->cookies[i]);
1381 cookies->cookies[i] = NULL;
1382 }
1383 cookies->numcookies = 0;
1384 }
1385 }
1386
1387 /*****************************************************************************
1388 *
1389 * Curl_cookie_freelist()
1390 *
1391 * Free a list of cookies previously returned by Curl_cookie_getlist();
1392 *
1393 ****************************************************************************/
1394
1395 void Curl_cookie_freelist(struct Cookie *co)
1396 {
1397 struct Cookie *next;
1398 while(co) {
1399 next = co->next;
1400 freecookie(co);
1401 co = next;
1402 }
1403 }
1404
1405
1406 /*****************************************************************************
1407 *
1408 * Curl_cookie_clearsess()
1409 *
1410 * Free all session cookies in the cookies list.
1411 *
1412 ****************************************************************************/
1413 void Curl_cookie_clearsess(struct CookieInfo *cookies)
1414 {
1415 struct Cookie *first, *curr, *next, *prev = NULL;
1416 unsigned int i;
1417
1418 if(!cookies)
1419 return;
1420
1421 for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1422 if(!cookies->cookies[i])
1423 continue;
1424
1425 first = curr = prev = cookies->cookies[i];
1426
1427 for(; curr; curr = next) {
1428 next = curr->next;
1429 if(!curr->expires) {
1430 if(first == curr)
1431 first = next;
1432
1433 if(prev == curr)
1434 prev = next;
1435 else
1436 prev->next = next;
1437
1438 freecookie(curr);
1439 cookies->numcookies--;
1440 }
1441 else
1442 prev = curr;
1443 }
1444
1445 cookies->cookies[i] = first;
1446 }
1447 }
1448
1449
1450 /*****************************************************************************
1451 *
1452 * Curl_cookie_cleanup()
1453 *
1454 * Free a "cookie object" previous created with Curl_cookie_init().
1455 *
1456 ****************************************************************************/
1457 void Curl_cookie_cleanup(struct CookieInfo *c)
1458 {
1459 if(c) {
1460 unsigned int i;
1461 free(c->filename);
1462 for(i = 0; i < COOKIE_HASH_SIZE; i++)
1463 Curl_cookie_freelist(c->cookies[i]);
1464 free(c); /* free the base struct as well */
1465 }
1466 }
1467
1468 /* get_netscape_format()
1469 *
1470 * Formats a string for Netscape output file, w/o a newline at the end.
1471 *
1472 * Function returns a char * to a formatted line. Has to be free()d
1473 */
1474 static char *get_netscape_format(const struct Cookie *co)
1475 {
1476 return aprintf(
1477 "%s" /* httponly preamble */
1478 "%s%s\t" /* domain */
1479 "%s\t" /* tailmatch */
1480 "%s\t" /* path */
1481 "%s\t" /* secure */
1482 "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
1483 "%s\t" /* name */
1484 "%s", /* value */
1485 co->httponly?"#HttpOnly_":"",
1486 /* Make sure all domains are prefixed with a dot if they allow
1487 tailmatching. This is Mozilla-style. */
1488 (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
1489 co->domain?co->domain:"unknown",
1490 co->tailmatch?"TRUE":"FALSE",
1491 co->path?co->path:"/",
1492 co->secure?"TRUE":"FALSE",
1493 co->expires,
1494 co->name,
1495 co->value?co->value:"");
1496 }
1497
1498 /*
1499 * cookie_output()
1500 *
1501 * Writes all internally known cookies to the specified file. Specify
1502 * "-" as file name to write to stdout.
1503 *
1504 * The function returns non-zero on write failure.
1505 */
1506 static int cookie_output(struct Curl_easy *data,
1507 struct CookieInfo *c, const char *filename)
1508 {
1509 struct Cookie *co;
1510 FILE *out = NULL;
1511 bool use_stdout = FALSE;
1512 char *tempstore = NULL;
1513 bool error = false;
1514
1515 if(!c)
1516 /* no cookie engine alive */
1517 return 0;
1518
1519 /* at first, remove expired cookies */
1520 remove_expired(c);
1521
1522 if(!strcmp("-", filename)) {
1523 /* use stdout */
1524 out = stdout;
1525 use_stdout = TRUE;
1526 }
1527 else {
1528 unsigned char randsuffix[9];
1529
1530 if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix)))
1531 return 2;
1532
1533 tempstore = aprintf("%s.%s.tmp", filename, randsuffix);
1534 if(!tempstore)
1535 return 1;
1536
1537 out = fopen(tempstore, FOPEN_WRITETEXT);
1538 if(!out)
1539 goto error;
1540 }
1541
1542 fputs("# Netscape HTTP Cookie File\n"
1543 "# https://curl.haxx.se/docs/http-cookies.html\n"
1544 "# This file was generated by libcurl! Edit at your own risk.\n\n",
1545 out);
1546
1547 if(c->numcookies) {
1548 unsigned int i;
1549 size_t nvalid = 0;
1550 struct Cookie **array;
1551
1552 array = calloc(1, sizeof(struct Cookie *) * c->numcookies);
1553 if(!array) {
1554 goto error;
1555 }
1556
1557 /* only sort the cookies with a domain property */
1558 for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1559 for(co = c->cookies[i]; co; co = co->next) {
1560 if(!co->domain)
1561 continue;
1562 array[nvalid++] = co;
1563 }
1564 }
1565
1566 qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
1567
1568 for(i = 0; i < nvalid; i++) {
1569 char *format_ptr = get_netscape_format(array[i]);
1570 if(format_ptr == NULL) {
1571 fprintf(out, "#\n# Fatal libcurl error\n");
1572 free(array);
1573 goto error;
1574 }
1575 fprintf(out, "%s\n", format_ptr);
1576 free(format_ptr);
1577 }
1578
1579 free(array);
1580 }
1581
1582 if(!use_stdout) {
1583 fclose(out);
1584 out = NULL;
1585 if(Curl_rename(tempstore, filename)) {
1586 unlink(tempstore);
1587 goto error;
1588 }
1589 }
1590
1591 goto cleanup;
1592 error:
1593 error = true;
1594 cleanup:
1595 if(out && !use_stdout)
1596 fclose(out);
1597 free(tempstore);
1598 return error ? 1 : 0;
1599 }
1600
1601 static struct curl_slist *cookie_list(struct Curl_easy *data)
1602 {
1603 struct curl_slist *list = NULL;
1604 struct curl_slist *beg;
1605 struct Cookie *c;
1606 char *line;
1607 unsigned int i;
1608
1609 if((data->cookies == NULL) ||
1610 (data->cookies->numcookies == 0))
1611 return NULL;
1612
1613 for(i = 0; i < COOKIE_HASH_SIZE; i++) {
1614 for(c = data->cookies->cookies[i]; c; c = c->next) {
1615 if(!c->domain)
1616 continue;
1617 line = get_netscape_format(c);
1618 if(!line) {
1619 curl_slist_free_all(list);
1620 return NULL;
1621 }
1622 beg = Curl_slist_append_nodup(list, line);
1623 if(!beg) {
1624 free(line);
1625 curl_slist_free_all(list);
1626 return NULL;
1627 }
1628 list = beg;
1629 }
1630 }
1631
1632 return list;
1633 }
1634
1635 struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
1636 {
1637 struct curl_slist *list;
1638 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1639 list = cookie_list(data);
1640 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1641 return list;
1642 }
1643
1644 void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
1645 {
1646 if(data->set.str[STRING_COOKIEJAR]) {
1647 if(data->change.cookielist) {
1648 /* If there is a list of cookie files to read, do it first so that
1649 we have all the told files read before we write the new jar.
1650 Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
1651 Curl_cookie_loadfiles(data);
1652 }
1653
1654 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1655
1656 /* if we have a destination file for all the cookies to get dumped to */
1657 if(cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]))
1658 infof(data, "WARNING: failed to save cookies in %s\n",
1659 data->set.str[STRING_COOKIEJAR]);
1660 }
1661 else {
1662 if(cleanup && data->change.cookielist) {
1663 /* since nothing is written, we can just free the list of cookie file
1664 names */
1665 curl_slist_free_all(data->change.cookielist); /* clean up list */
1666 data->change.cookielist = NULL;
1667 }
1668 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1669 }
1670
1671 if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
1672 Curl_cookie_cleanup(data->cookies);
1673 data->cookies = NULL;
1674 }
1675 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1676 }
1677
1678 #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */