1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
26 RECEIVING COOKIE INFORMATION
27 ============================
29 struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
30 const char *file, struct CookieInfo *inc, bool newsession);
32 Inits a cookie struct to store data in a local file. This is always
33 called before any cookies are set.
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);
39 The 'lineptr' parameter is a full "Set-cookie:" line as
40 received from a server.
42 The function need to replace previously stored lines that this new
45 It may remove lines that are expired.
47 It should return an indication of success/error.
50 SENDING COOKIE INFORMATION
51 ==========================
53 struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie,
54 char *host, char *path, bool secure);
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
61 It shall only return cookies that haven't expired.
64 Example set of cookies:
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
78 Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
79 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
83 #include "curl_setup.h"
85 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
97 #include "strtoofft.h"
99 #include "curl_memrchr.h"
100 #include "inet_pton.h"
102 /* The last 3 #include files should be in this order */
103 #include "curl_printf.h"
104 #include "curl_memory.h"
105 #include "memdebug.h"
107 static void freecookie(struct Cookie *co)
120 static bool tailmatch(const char *cooke_domain, const char *hostname)
122 size_t cookie_domain_len = strlen(cooke_domain);
123 size_t hostname_len = strlen(hostname);
125 if(hostname_len < cookie_domain_len)
128 if(!strcasecompare(cooke_domain, hostname+hostname_len-cookie_domain_len))
131 /* A lead char of cookie_domain is not '.'.
132 RFC6265 4.1.2.3. The Domain Attribute says:
133 For example, if the value of the Domain attribute is
134 "example.com", the user agent will include the cookie in the Cookie
135 header when making HTTP requests to example.com, www.example.com, and
136 www.corp.example.com.
138 if(hostname_len == cookie_domain_len)
140 if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
146 * matching cookie path and url path
147 * RFC6265 5.1.4 Paths and Path-Match
149 static bool pathmatch(const char *cookie_path, const char *request_uri)
151 size_t cookie_path_len;
153 char *uri_path = NULL;
157 /* cookie_path must not have last '/' separator. ex: /sample */
158 cookie_path_len = strlen(cookie_path);
159 if(1 == cookie_path_len) {
160 /* cookie_path must be '/' */
164 uri_path = strdup(request_uri);
167 pos = strchr(uri_path, '?');
171 /* #-fragments are already cut off! */
172 if(0 == strlen(uri_path) || uri_path[0] != '/') {
174 uri_path = strdup("/");
179 /* here, RFC6265 5.1.4 says
180 4. Output the characters of the uri-path from the first character up
181 to, but not including, the right-most %x2F ("/").
182 but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
184 Ignore this algorithm because /hoge is uri path for this case
188 uri_path_len = strlen(uri_path);
190 if(uri_path_len < cookie_path_len) {
195 /* not using checkprefix() because matching should be case-sensitive */
196 if(strncmp(cookie_path, uri_path, cookie_path_len)) {
201 /* The cookie-path and the uri-path are identical. */
202 if(cookie_path_len == uri_path_len) {
207 /* here, cookie_path_len < url_path_len */
208 if(uri_path[cookie_path_len] == '/') {
221 * cookie path sanitize
223 static char *sanitize_cookie_path(const char *cookie_path)
226 char *new_path = strdup(cookie_path);
230 /* some stupid site sends path attribute with '"'. */
231 len = strlen(new_path);
232 if(new_path[0] == '\"') {
233 memmove((void *)new_path, (const void *)(new_path + 1), len);
236 if(len && (new_path[len - 1] == '\"')) {
237 new_path[len - 1] = 0x0;
241 /* RFC6265 5.2.4 The Path Attribute */
242 if(new_path[0] != '/') {
243 /* Let cookie-path be the default-path. */
245 new_path = strdup("/");
249 /* convert /hoge/ to /hoge */
250 if(len && new_path[len - 1] == '/') {
251 new_path[len - 1] = 0x0;
258 * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
260 * NOTE: OOM or cookie parsing failures are ignored.
262 void Curl_cookie_loadfiles(struct Curl_easy *data)
264 struct curl_slist *list = data->change.cookielist;
266 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
268 struct CookieInfo *newcookies = Curl_cookie_init(data,
271 data->set.cookiesession);
273 /* Failure may be due to OOM or a bad cookie; both are ignored
274 * but only the first should be
276 infof(data, "ignoring failed cookie_init for %s\n", list->data);
278 data->cookies = newcookies;
281 curl_slist_free_all(data->change.cookielist); /* clean up list */
282 data->change.cookielist = NULL; /* don't do this again! */
283 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
288 * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
289 * that will be freed before the allocated string is stored there.
291 * It is meant to easily replace strdup()
293 static void strstore(char **str, const char *newstr)
296 *str = strdup(newstr);
300 * remove_expired() removes expired cookies.
302 static void remove_expired(struct CookieInfo *cookies)
304 struct Cookie *co, *nx, *pv;
305 curl_off_t now = (curl_off_t)time(NULL);
307 co = cookies->cookies;
311 if(co->expires && co->expires < now) {
312 if(co == cookies->cookies) {
313 cookies->cookies = co->next;
318 cookies->numcookies--;
329 * Return true if the given string is an IP(v4|v6) address.
331 static bool isip(const char *domain)
335 struct in6_addr addr6;
338 if(Curl_inet_pton(AF_INET, domain, &addr)
340 || Curl_inet_pton(AF_INET6, domain, &addr6)
343 /* domain name given as IP address */
350 /****************************************************************************
354 * Add a single cookie line to the cookie keeping object.
356 * Be aware that sometimes we get an IP-only host name, and that might also be
357 * a numerical IPv6 address.
359 * Returns NULL on out of memory or invalid cookie. This is suboptimal,
360 * as they should be treated separately.
361 ***************************************************************************/
364 Curl_cookie_add(struct Curl_easy *data,
365 /* The 'data' pointer here may be NULL at times, and thus
366 must only be used very carefully for things that can deal
367 with data being NULL. Such as infof() and similar */
369 struct CookieInfo *c,
370 bool httpheader, /* TRUE if HTTP header-style line */
371 char *lineptr, /* first character of the line */
372 const char *domain, /* default domain */
373 const char *path) /* full path used when this cookie is set,
374 used to get default path for the cookie
377 struct Cookie *clist;
380 struct Cookie *lastc=NULL;
381 time_t now = time(NULL);
382 bool replace_old = FALSE;
383 bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
386 const psl_ctx_t *psl;
389 #ifdef CURL_DISABLE_VERBOSE_STRINGS
393 /* First, alloc and init a new struct for it */
394 co = calloc(1, sizeof(struct Cookie));
396 return NULL; /* bail out if we're this low on memory */
399 /* This line was read off a HTTP-header */
404 what = malloc(MAX_COOKIE_LINE);
410 semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
412 while(*lineptr && ISBLANK(*lineptr))
417 /* we have a <what>=<this> pair or a stand-alone word here */
418 name[0]=what[0]=0; /* init the buffers */
419 if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
420 MAX_COOKIE_LINE_TXT "[^;\r\n]",
422 /* Use strstore() below to properly deal with received cookie
423 headers that have the same string property set more than once,
424 and then we use the last one. */
428 size_t len=strlen(what);
429 size_t nlen = strlen(name);
430 const char *endofn = &ptr[ nlen ];
432 /* name ends with a '=' ? */
433 sep = (*endofn == '=')?TRUE:FALSE;
436 endofn--; /* move to the last character */
437 if(ISBLANK(*endofn)) {
438 /* skip trailing spaces in name */
439 while(*endofn && ISBLANK(*endofn) && nlen) {
443 name[nlen]=0; /* new end of name */
447 /* Strip off trailing whitespace from the 'what' */
448 while(len && ISBLANK(what[len-1])) {
453 /* Skip leading whitespace from the 'what' */
455 while(*whatptr && ISBLANK(*whatptr))
458 if(!co->name && sep) {
459 /* The very first name/value pair is the actual cookie name */
460 co->name = strdup(name);
461 co->value = strdup(whatptr);
462 if(!co->name || !co->value) {
468 /* this was a "<name>=" with no content, and we must allow
469 'secure' and 'httponly' specified this weirdly */
471 if(strcasecompare("secure", name))
473 else if(strcasecompare("httponly", name))
476 /* there was a '=' so we're not done parsing this field */
481 else if(strcasecompare("path", name)) {
482 strstore(&co->path, whatptr);
484 badcookie = TRUE; /* out of memory bad */
487 co->spath = sanitize_cookie_path(co->path);
489 badcookie = TRUE; /* out of memory bad */
493 else if(strcasecompare("domain", name)) {
496 /* Now, we make sure that our host is within the given domain,
497 or the given domain is not valid and thus cannot be set. */
499 if('.' == whatptr[0])
500 whatptr++; /* ignore preceding dot */
504 * Without PSL we don't know when the incoming cookie is set on a
505 * TLD or otherwise "protected" suffix. To reduce risk, we require a
506 * dot OR the exact host name being "localhost".
510 /* check for more dots */
511 dotp = strchr(whatptr, '.');
512 if(!dotp && !strcasecompare("localhost", whatptr))
517 is_ip = isip(domain ? domain : whatptr);
520 || (is_ip && !strcmp(whatptr, domain))
521 || (!is_ip && tailmatch(whatptr, domain))) {
522 strstore(&co->domain, whatptr);
528 co->tailmatch=TRUE; /* we always do that if the domain name was
532 /* we did not get a tailmatch and then the attempted set domain
533 is not a domain to which the current host belongs. Mark as
536 infof(data, "skipped cookie with bad tailmatch domain: %s\n",
540 else if(strcasecompare("version", name)) {
541 strstore(&co->version, whatptr);
547 else if(strcasecompare("max-age", name)) {
548 /* Defined in RFC2109:
550 Optional. The Max-Age attribute defines the lifetime of the
551 cookie, in seconds. The delta-seconds value is a decimal non-
552 negative integer. After delta-seconds seconds elapse, the
553 client should discard the cookie. A value of zero means the
554 cookie should be discarded immediately.
557 strstore(&co->maxage, whatptr);
563 else if(strcasecompare("expires", name)) {
564 strstore(&co->expirestr, whatptr);
571 else this is the second (or more) name we don't know
575 /* this is an "illegal" <what>=<this> pair */
578 if(!semiptr || !*semiptr) {
579 /* we already know there are no more cookies */
585 while(*ptr && ISBLANK(*ptr))
587 semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
590 /* There are no more semicolons, but there's a final name=value pair
592 semiptr=strchr(ptr, '\0');
597 curlx_strtoofft((*co->maxage=='\"')?
598 &co->maxage[1]:&co->maxage[0], NULL, 10);
599 if(CURL_OFF_T_MAX - now < co->expires)
601 co->expires = CURL_OFF_T_MAX;
605 else if(co->expirestr) {
606 /* Note that if the date couldn't get parsed for whatever reason,
607 the cookie will be treated as a session cookie */
608 co->expires = curl_getdate(co->expirestr, NULL);
610 /* Session cookies have expires set to 0 so if we get that back
611 from the date parser let's add a second to make it a
612 non-session cookie */
615 else if(co->expires < 0)
619 if(!badcookie && !co->domain) {
621 /* no domain was given in the header line, set the default */
622 co->domain=strdup(domain);
628 if(!badcookie && !co->path && path) {
629 /* No path was given in the header line, set the default.
630 Note that the passed-in path to this function MAY have a '?' and
631 following part that MUST not be stored as part of the path. */
632 char *queryp = strchr(path, '?');
634 /* queryp is where the interesting part of the path ends, so now we
635 want to the find the last */
638 endslash = strrchr(path, '/');
640 endslash = memrchr(path, '/', (size_t)(queryp - path));
642 size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
643 co->path=malloc(pathlen+1); /* one extra for the zero byte */
645 memcpy(co->path, path, pathlen);
646 co->path[pathlen]=0; /* zero terminate */
647 co->spath = sanitize_cookie_path(co->path);
649 badcookie = TRUE; /* out of memory bad */
658 if(badcookie || !co->name) {
659 /* we didn't get a cookie name or a bad one,
660 this is an illegal line, bail out */
667 /* This line is NOT a HTTP header style line, we do offer support for
668 reading the odd netscape cookies-file format here */
674 /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
675 marked with httpOnly after the domain name are not accessible
676 from javascripts, but since curl does not operate at javascript
677 level, we include them anyway. In Firefox's cookie files, these
678 lines are preceded with #HttpOnly_ and then everything is
679 as usual, so we skip 10 characters of the line..
681 if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
686 if(lineptr[0]=='#') {
687 /* don't even try the comments */
691 /* strip off the possible end-of-line characters */
692 ptr=strchr(lineptr, '\r');
694 *ptr=0; /* clear it */
695 ptr=strchr(lineptr, '\n');
697 *ptr=0; /* clear it */
699 firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
701 /* Now loop through the fields and init the struct we already have
703 for(ptr=firstptr, fields=0; ptr && !badcookie;
704 ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
707 if(ptr[0]=='.') /* skip preceding dots */
709 co->domain = strdup(ptr);
714 /* This field got its explanation on the 23rd of May 2001 by
717 flag: A TRUE/FALSE value indicating if all machines within a given
718 domain can access the variable. This value is set automatically by
719 the browser, depending on the value you set for the domain.
721 As far as I can see, it is set to true when the cookie says
722 .domain.com and to false when the domain is complete www.domain.com
724 co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
727 /* It turns out, that sometimes the file format allows the path
728 field to remain not filled in, we try to detect this and work
729 around it! Andrés GarcÃa made us aware of this... */
730 if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
731 /* only if the path doesn't look like a boolean option! */
732 co->path = strdup(ptr);
736 co->spath = sanitize_cookie_path(co->path);
738 badcookie = TRUE; /* out of memory bad */
743 /* this doesn't look like a path, make one up! */
744 co->path = strdup("/");
747 co->spath = strdup("/");
750 fields++; /* add a field and fall down to secure */
753 co->secure = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
756 co->expires = curlx_strtoofft(ptr, NULL, 10);
759 co->name = strdup(ptr);
764 co->value = strdup(ptr);
771 /* we got a cookie with blank contents, fix it */
772 co->value = strdup("");
779 if(!badcookie && (7 != fields))
780 /* we did not find the sufficient number of fields */
790 if(!c->running && /* read from a file */
791 c->newsession && /* clean session cookies */
792 !co->expires) { /* this is a session cookie since it doesn't expire! */
797 co->livecookie = c->running;
799 /* now, we have parsed the incoming line, we must now check if this
800 superceeds an already existing cookie, which it may if the previous have
801 the same domain and path as this */
803 /* at first, remove expired cookies */
807 /* Check if the domain is a Public Suffix and if yes, ignore the cookie.
808 This needs a libpsl compiled with builtin data. */
809 if(domain && co->domain && !isip(co->domain)) {
811 if(psl && !psl_is_cookie_domain_acceptable(psl, domain, co->domain)) {
813 "cookie '%s' dropped, domain '%s' must not set cookies for '%s'\n",
814 co->name, domain, co->domain);
824 if(strcasecompare(clist->name, co->name)) {
825 /* the names are identical */
827 if(clist->domain && co->domain) {
828 if(strcasecompare(clist->domain, co->domain) &&
829 (clist->tailmatch == co->tailmatch))
830 /* The domains are identical */
833 else if(!clist->domain && !co->domain)
837 /* the domains were identical */
839 if(clist->spath && co->spath) {
840 if(strcasecompare(clist->spath, co->spath)) {
846 else if(!clist->spath && !co->spath)
853 if(replace_old && !co->livecookie && clist->livecookie) {
854 /* Both cookies matched fine, except that the already present
855 cookie is "live", which means it was set from a header, while
856 the new one isn't "live" and thus only read from a file. We let
857 live cookies stay alive */
859 /* Free the newcomer and get out of here! */
865 co->next = clist->next; /* get the next-pointer first */
867 /* then free all the old pointers */
873 free(clist->expirestr);
874 free(clist->version);
877 *clist = *co; /* then store all the new data */
879 free(co); /* free the newly alloced memory */
880 co = clist; /* point to the previous struct instead */
882 /* We have replaced a cookie, now skip the rest of the list but
883 make sure the 'lastc' pointer is properly set */
896 /* Only show this when NOT reading the cookies from a file */
897 infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
898 "expire %" CURL_FORMAT_CURL_OFF_T "\n",
899 replace_old?"Replaced":"Added", co->name, co->value,
900 co->domain, co->path, co->expires);
903 /* then make the last item point on this new one */
908 c->numcookies++; /* one more cookie in the jar */
915 * get_line() makes sure to only return complete whole lines that fit in 'len'
916 * bytes and end with a newline.
918 static char *get_line(char *buf, int len, FILE *input)
920 bool partial = FALSE;
922 char *b = fgets(buf, len, input);
924 size_t rlen = strlen(b);
925 if(rlen && (b[rlen-1] == '\n')) {
933 /* read a partial, discard the next piece that ends with newline */
943 /*****************************************************************************
947 * Inits a cookie struct to read data from a local file. This is always
948 * called before any cookies are set. File may be NULL.
950 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
952 * Returns NULL on out of memory. Invalid cookies are ignored.
953 ****************************************************************************/
954 struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
956 struct CookieInfo *inc,
959 struct CookieInfo *c;
965 /* we didn't get a struct, create one */
966 c = calloc(1, sizeof(struct CookieInfo));
968 return NULL; /* failed to get memory */
969 c->filename = strdup(file?file:"none"); /* copy the name just in case */
971 goto fail; /* failed to get memory */
974 /* we got an already existing one, use that */
977 c->running = FALSE; /* this is not running, this is init */
979 if(file && !strcmp(file, "-")) {
983 else if(file && !*file) {
984 /* points to a "" string */
988 fp = file?fopen(file, FOPEN_READTEXT):NULL;
990 c->newsession = newsession; /* new session? */
996 line = malloc(MAX_COOKIE_LINE);
999 while(get_line(line, MAX_COOKIE_LINE, fp)) {
1000 if(checkprefix("Set-Cookie:", line)) {
1001 /* This is a cookie line, get it! */
1009 while(*lineptr && ISBLANK(*lineptr))
1012 Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
1014 free(line); /* free the line buffer */
1020 c->running = TRUE; /* now, we're running */
1027 /* Only clean up if we allocated it here, as the original could still be in
1028 * use by a share handle */
1029 Curl_cookie_cleanup(c);
1032 return NULL; /* out of memory */
1035 /* sort this so that the longest path gets before the shorter path */
1036 static int cookie_sort(const void *p1, const void *p2)
1038 struct Cookie *c1 = *(struct Cookie **)p1;
1039 struct Cookie *c2 = *(struct Cookie **)p2;
1042 /* 1 - compare cookie path lengths */
1043 l1 = c1->path ? strlen(c1->path) : 0;
1044 l2 = c2->path ? strlen(c2->path) : 0;
1047 return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
1049 /* 2 - compare cookie domain lengths */
1050 l1 = c1->domain ? strlen(c1->domain) : 0;
1051 l2 = c2->domain ? strlen(c2->domain) : 0;
1054 return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
1056 /* 3 - compare cookie names */
1057 if(c1->name && c2->name)
1058 return strcmp(c1->name, c2->name);
1060 /* sorry, can't be more deterministic */
1064 #define CLONE(field) \
1067 d->field = strdup(src->field); \
1073 static struct Cookie *dup_cookie(struct Cookie *src)
1075 struct Cookie *d = calloc(sizeof(struct Cookie), 1);
1085 d->expires = src->expires;
1086 d->tailmatch = src->tailmatch;
1087 d->secure = src->secure;
1088 d->livecookie = src->livecookie;
1089 d->httponly = src->httponly;
1098 /*****************************************************************************
1100 * Curl_cookie_getlist()
1102 * For a given host and path, return a linked list of cookies that the
1103 * client should send to the server if used now. The secure boolean informs
1104 * the cookie if a secure connection is achieved or not.
1106 * It shall only return cookies that haven't expired.
1108 ****************************************************************************/
1110 struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
1111 const char *host, const char *path,
1114 struct Cookie *newco;
1116 time_t now = time(NULL);
1117 struct Cookie *mainco=NULL;
1121 if(!c || !c->cookies)
1122 return NULL; /* no cookie struct or no cookies in the struct */
1124 /* at first, remove expired cookies */
1127 /* check if host is an IP(v4|v6) address */
1133 /* only process this cookie if it is not expired or had no expire
1134 date AND that if the cookie requires we're secure we must only
1135 continue if we are! */
1136 if((!co->expires || (co->expires > now)) &&
1137 (co->secure?secure:TRUE)) {
1139 /* now check if the domain is correct */
1141 (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
1142 ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
1143 /* the right part of the host matches the domain stuff in the
1146 /* now check the left part of the path with the cookies path
1148 if(!co->spath || pathmatch(co->spath, path) ) {
1150 /* and now, we know this is a match and we should create an
1151 entry for the return-linked-list */
1153 newco = dup_cookie(co);
1155 /* then modify our next */
1156 newco->next = mainco;
1158 /* point the main to us */
1165 /* failure, clear up the allocated chain and return NULL */
1166 Curl_cookie_freelist(mainco);
1176 /* Now we need to make sure that if there is a name appearing more than
1177 once, the longest specified path version comes first. To make this
1178 the swiftest way, we just sort them all based on path length. */
1179 struct Cookie **array;
1182 /* alloc an array and store all cookie pointers */
1183 array = malloc(sizeof(struct Cookie *) * matches);
1189 for(i=0; co; co = co->next)
1192 /* now sort the cookie pointers in path length order */
1193 qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
1195 /* remake the linked list order according to the new order */
1197 mainco = array[0]; /* start here */
1198 for(i=0; i<matches-1; i++)
1199 array[i]->next = array[i+1];
1200 array[matches-1]->next = NULL; /* terminate the list */
1202 free(array); /* remove the temporary data again */
1205 return mainco; /* return the new list */
1208 /*****************************************************************************
1210 * Curl_cookie_clearall()
1212 * Clear all existing cookies and reset the counter.
1214 ****************************************************************************/
1215 void Curl_cookie_clearall(struct CookieInfo *cookies)
1218 Curl_cookie_freelist(cookies->cookies);
1219 cookies->cookies = NULL;
1220 cookies->numcookies = 0;
1224 /*****************************************************************************
1226 * Curl_cookie_freelist()
1228 * Free a list of cookies previously returned by Curl_cookie_getlist();
1230 ****************************************************************************/
1232 void Curl_cookie_freelist(struct Cookie *co)
1234 struct Cookie *next;
1243 /*****************************************************************************
1245 * Curl_cookie_clearsess()
1247 * Free all session cookies in the cookies list.
1249 ****************************************************************************/
1250 void Curl_cookie_clearsess(struct CookieInfo *cookies)
1252 struct Cookie *first, *curr, *next, *prev = NULL;
1254 if(!cookies || !cookies->cookies)
1257 first = curr = prev = cookies->cookies;
1259 for(; curr; curr = next) {
1261 if(!curr->expires) {
1271 cookies->numcookies--;
1277 cookies->cookies = first;
1281 /*****************************************************************************
1283 * Curl_cookie_cleanup()
1285 * Free a "cookie object" previous created with Curl_cookie_init().
1287 ****************************************************************************/
1288 void Curl_cookie_cleanup(struct CookieInfo *c)
1292 Curl_cookie_freelist(c->cookies);
1293 free(c); /* free the base struct as well */
1297 /* get_netscape_format()
1299 * Formats a string for Netscape output file, w/o a newline at the end.
1301 * Function returns a char * to a formatted line. Has to be free()d
1303 static char *get_netscape_format(const struct Cookie *co)
1306 "%s" /* httponly preamble */
1307 "%s%s\t" /* domain */
1308 "%s\t" /* tailmatch */
1311 "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
1314 co->httponly?"#HttpOnly_":"",
1315 /* Make sure all domains are prefixed with a dot if they allow
1316 tailmatching. This is Mozilla-style. */
1317 (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
1318 co->domain?co->domain:"unknown",
1319 co->tailmatch?"TRUE":"FALSE",
1320 co->path?co->path:"/",
1321 co->secure?"TRUE":"FALSE",
1324 co->value?co->value:"");
1330 * Writes all internally known cookies to the specified file. Specify
1331 * "-" as file name to write to stdout.
1333 * The function returns non-zero on write failure.
1335 static int cookie_output(struct CookieInfo *c, const char *dumphere)
1339 bool use_stdout=FALSE;
1342 if((NULL == c) || (0 == c->numcookies))
1343 /* If there are no known cookies, we don't write or even create any
1347 /* at first, remove expired cookies */
1350 if(!strcmp("-", dumphere)) {
1356 out = fopen(dumphere, FOPEN_WRITETEXT);
1358 return 1; /* failure */
1361 fputs("# Netscape HTTP Cookie File\n"
1362 "# https://curl.haxx.se/docs/http-cookies.html\n"
1363 "# This file was generated by libcurl! Edit at your own risk.\n\n",
1366 for(co = c->cookies; co; co = co->next) {
1369 format_ptr = get_netscape_format(co);
1370 if(format_ptr == NULL) {
1371 fprintf(out, "#\n# Fatal libcurl error\n");
1376 fprintf(out, "%s\n", format_ptr);
1386 struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
1388 struct curl_slist *list = NULL;
1389 struct curl_slist *beg;
1393 if((data->cookies == NULL) ||
1394 (data->cookies->numcookies == 0))
1397 for(c = data->cookies->cookies; c; c = c->next) {
1400 line = get_netscape_format(c);
1402 curl_slist_free_all(list);
1405 beg = Curl_slist_append_nodup(list, line);
1408 curl_slist_free_all(list);
1417 void Curl_flush_cookies(struct Curl_easy *data, int cleanup)
1419 if(data->set.str[STRING_COOKIEJAR]) {
1420 if(data->change.cookielist) {
1421 /* If there is a list of cookie files to read, do it first so that
1422 we have all the told files read before we write the new jar.
1423 Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
1424 Curl_cookie_loadfiles(data);
1427 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1429 /* if we have a destination file for all the cookies to get dumped to */
1430 if(cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
1431 infof(data, "WARNING: failed to save cookies in %s\n",
1432 data->set.str[STRING_COOKIEJAR]);
1435 if(cleanup && data->change.cookielist) {
1436 /* since nothing is written, we can just free the list of cookie file
1438 curl_slist_free_all(data->change.cookielist); /* clean up list */
1439 data->change.cookielist = NULL;
1441 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1444 if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
1445 Curl_cookie_cleanup(data->cookies);
1447 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1450 #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */