1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2009, 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 http://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.
22 ***************************************************************************/
27 RECEIVING COOKIE INFORMATION
28 ============================
30 struct CookieInfo *cookie_init(char *file);
32 Inits a cookie struct to store data in a local file. This is always
33 called before any cookies are set.
35 int cookies_set(struct CookieInfo *cookie, char *cookie_line);
37 The 'cookie_line' parameter is a full "Set-cookie:" line as
38 received from a server.
40 The function need to replace previously stored lines that this new
43 It may remove lines that are expired.
45 It should return an indication of success/error.
48 SENDING COOKIE INFORMATION
49 ==========================
51 struct Cookies *cookie_getlist(struct CookieInfo *cookie,
52 char *host, char *path, bool secure);
54 For a given host and path, return a linked list of cookies that
55 the client should send to the server if used now. The secure
56 boolean informs the cookie if a secure connection is achieved or
59 It shall only return cookies that haven't expired.
62 Example set of cookies:
64 Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
65 Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
66 domain=.fidelity.com; path=/ftgw; secure
67 Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
68 domain=.fidelity.com; path=/; secure
69 Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
70 domain=.fidelity.com; path=/; secure
71 Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
72 domain=.fidelity.com; path=/; secure
73 Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
74 domain=.fidelity.com; path=/; secure
76 Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
77 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
83 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
88 #define _MPRINTF_REPLACE /* without this on windows OS we get undefined reference to snprintf */
89 #include <curl/mprintf.h>
96 #include "curl_memory.h"
98 #include "strtoofft.h"
100 #include "curl_memrchr.h"
102 /* The last #include file should be: */
103 #include "memdebug.h"
106 static void freecookie(struct Cookie *co)
126 static bool tailmatch(const char *little, const char *bigone)
128 size_t littlelen = strlen(little);
129 size_t biglen = strlen(bigone);
131 if(littlelen > biglen)
134 return (bool)Curl_raw_equal(little, bigone+biglen-littlelen);
138 * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
140 void Curl_cookie_loadfiles(struct SessionHandle *data)
142 struct curl_slist *list = data->change.cookielist;
144 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
146 data->cookies = Curl_cookie_init(data,
149 data->set.cookiesession);
152 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
153 curl_slist_free_all(data->change.cookielist); /* clean up list */
154 data->change.cookielist = NULL; /* don't do this again! */
159 * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
160 * that will be freed before the allocated string is stored there.
162 * It is meant to easily replace strdup()
164 static void strstore(char **str, const char *newstr)
168 *str = strdup(newstr);
172 /****************************************************************************
176 * Add a single cookie line to the cookie keeping object.
178 ***************************************************************************/
181 Curl_cookie_add(struct SessionHandle *data,
182 /* The 'data' pointer here may be NULL at times, and thus
183 must only be used very carefully for things that can deal
184 with data being NULL. Such as infof() and similar */
186 struct CookieInfo *c,
187 bool httpheader, /* TRUE if HTTP header-style line */
188 char *lineptr, /* first character of the line */
189 const char *domain, /* default domain */
190 const char *path) /* full path used when this cookie is set,
191 used to get default path for the cookie
194 struct Cookie *clist;
197 struct Cookie *lastc=NULL;
198 time_t now = time(NULL);
199 bool replace_old = FALSE;
200 bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
202 #ifdef CURL_DISABLE_VERBOSE_STRINGS
206 /* First, alloc and init a new struct for it */
207 co = calloc(1, sizeof(struct Cookie));
209 return NULL; /* bail out if we're this low on memory */
212 /* This line was read off a HTTP-header */
218 what = malloc(MAX_COOKIE_LINE);
224 semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
226 while(*lineptr && ISBLANK(*lineptr))
231 /* we have a <what>=<this> pair or a 'secure' word here */
232 sep = strchr(ptr, '=');
233 if(sep && (!semiptr || (semiptr>sep)) ) {
235 * There is a = sign and if there was a semicolon too, which make sure
236 * that the semicolon comes _after_ the equal sign.
239 name[0]=what[0]=0; /* init the buffers */
240 if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;=]=%"
241 MAX_COOKIE_LINE_TXT "[^;\r\n]",
243 /* this is a <name>=<what> pair. We use strstore() below to properly
244 deal with received cookie headers that have the same string
245 property set more than once, and then we use the last one. */
249 /* Strip off trailing whitespace from the 'what' */
250 size_t len=strlen(what);
251 while(len && ISBLANK(what[len-1])) {
256 /* Skip leading whitespace from the 'what' */
258 while(*whatptr && ISBLANK(*whatptr)) {
262 if(Curl_raw_equal("path", name)) {
263 strstore(&co->path, whatptr);
265 badcookie = TRUE; /* out of memory bad */
269 else if(Curl_raw_equal("domain", name)) {
270 /* note that this name may or may not have a preceeding dot, but
271 we don't care about that, we treat the names the same anyway */
273 const char *domptr=whatptr;
276 /* Count the dots, we need to make sure that there are enough
279 if('.' == whatptr[0])
280 /* don't count the initial dot, assume it */
284 domptr = strchr(domptr, '.');
291 /* The original Netscape cookie spec defined that this domain name
292 MUST have three dots (or two if one of the seven holy TLDs),
293 but it seems that these kinds of cookies are in use "out there"
294 so we cannot be that strict. I've therefore lowered the check
295 to not allow less than two dots. */
298 /* Received and skipped a cookie with a domain using too few
300 badcookie=TRUE; /* mark this as a bad cookie */
301 infof(data, "skipped cookie with illegal dotcount domain: %s\n",
305 /* Now, we make sure that our host is within the given domain,
306 or the given domain is not valid and thus cannot be set. */
308 if('.' == whatptr[0])
309 whatptr++; /* ignore preceeding dot */
311 if(!domain || tailmatch(whatptr, domain)) {
312 const char *tailptr=whatptr;
313 if(tailptr[0] == '.')
315 strstore(&co->domain, tailptr); /* don't prefix w/dots
321 co->tailmatch=TRUE; /* we always do that if the domain name was
325 /* we did not get a tailmatch and then the attempted set domain
326 is not a domain to which the current host belongs. Mark as
329 infof(data, "skipped cookie with bad tailmatch domain: %s\n",
334 else if(Curl_raw_equal("version", name)) {
335 strstore(&co->version, whatptr);
341 else if(Curl_raw_equal("max-age", name)) {
342 /* Defined in RFC2109:
344 Optional. The Max-Age attribute defines the lifetime of the
345 cookie, in seconds. The delta-seconds value is a decimal non-
346 negative integer. After delta-seconds seconds elapse, the
347 client should discard the cookie. A value of zero means the
348 cookie should be discarded immediately.
351 strstore(&co->maxage, whatptr);
357 atoi((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0]) +
360 else if(Curl_raw_equal("expires", name)) {
361 strstore(&co->expirestr, whatptr);
366 /* Note that if the date couldn't get parsed for whatever reason,
367 the cookie will be treated as a session cookie */
368 co->expires = curl_getdate(what, &now);
370 /* Session cookies have expires set to 0 so if we get that back
371 from the date parser let's add a second to make it a
372 non-session cookie */
373 if (co->expires == 0)
375 else if( co->expires < 0 )
379 co->name = strdup(name);
380 co->value = strdup(whatptr);
381 if(!co->name || !co->value) {
387 else this is the second (or more) name we don't know
391 /* this is an "illegal" <what>=<this> pair */
395 if(sscanf(ptr, "%" MAX_COOKIE_LINE_TXT "[^;\r\n]",
397 if(Curl_raw_equal("secure", what)) {
400 else if (Curl_raw_equal("httponly", what)) {
404 unsupported keyword without assign! */
408 if(!semiptr || !*semiptr) {
409 /* we already know there are no more cookies */
415 while(*ptr && ISBLANK(*ptr))
417 semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
420 /* There are no more semicolons, but there's a final name=value pair
422 semiptr=strchr(ptr, '\0');
425 if(!badcookie && !co->domain) {
427 /* no domain was given in the header line, set the default */
428 co->domain=strdup(domain);
434 if(!badcookie && !co->path && path) {
435 /* No path was given in the header line, set the default.
436 Note that the passed-in path to this function MAY have a '?' and
437 following part that MUST not be stored as part of the path. */
438 char *queryp = strchr(path, '?');
440 /* queryp is where the interesting part of the path ends, so now we
441 want to the find the last */
444 endslash = strrchr(path, '/');
446 endslash = memrchr(path, '/', (size_t)(queryp - path));
448 size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
449 co->path=malloc(pathlen+1); /* one extra for the zero byte */
451 memcpy(co->path, path, pathlen);
452 co->path[pathlen]=0; /* zero terminate */
461 if(badcookie || !co->name) {
462 /* we didn't get a cookie name or a bad one,
463 this is an illegal line, bail out */
470 /* This line is NOT a HTTP header style line, we do offer support for
471 reading the odd netscape cookies-file format here */
477 /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
478 marked with httpOnly after the domain name are not accessible
479 from javascripts, but since curl does not operate at javascript
480 level, we include them anyway. In Firefox's cookie files, these
481 lines are preceeded with #HttpOnly_ and then everything is
482 as usual, so we skip 10 characters of the line..
484 if (strncmp(lineptr, "#HttpOnly_", 10) == 0) {
489 if(lineptr[0]=='#') {
490 /* don't even try the comments */
494 /* strip off the possible end-of-line characters */
495 ptr=strchr(lineptr, '\r');
497 *ptr=0; /* clear it */
498 ptr=strchr(lineptr, '\n');
500 *ptr=0; /* clear it */
502 firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
504 /* Here's a quick check to eliminate normal HTTP-headers from this */
505 if(!firstptr || strchr(firstptr, ':')) {
510 /* Now loop through the fields and init the struct we already have
512 for(ptr=firstptr, fields=0; ptr && !badcookie;
513 ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
516 if(ptr[0]=='.') /* skip preceeding dots */
518 co->domain = strdup(ptr);
523 /* This field got its explanation on the 23rd of May 2001 by
526 flag: A TRUE/FALSE value indicating if all machines within a given
527 domain can access the variable. This value is set automatically by
528 the browser, depending on the value you set for the domain.
530 As far as I can see, it is set to true when the cookie says
531 .domain.com and to false when the domain is complete www.domain.com
533 co->tailmatch=(bool)Curl_raw_equal(ptr, "TRUE"); /* store information */
536 /* It turns out, that sometimes the file format allows the path
537 field to remain not filled in, we try to detect this and work
538 around it! Andrés GarcÃa made us aware of this... */
539 if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
540 /* only if the path doesn't look like a boolean option! */
541 co->path = strdup(ptr);
546 /* this doesn't look like a path, make one up! */
547 co->path = strdup("/");
550 fields++; /* add a field and fall down to secure */
553 co->secure = (bool)Curl_raw_equal(ptr, "TRUE");
556 co->expires = curlx_strtoofft(ptr, NULL, 10);
559 co->name = strdup(ptr);
564 co->value = strdup(ptr);
571 /* we got a cookie with blank contents, fix it */
572 co->value = strdup("");
579 if(!badcookie && (7 != fields))
580 /* we did not find the sufficient number of fields */
590 if(!c->running && /* read from a file */
591 c->newsession && /* clean session cookies */
592 !co->expires) { /* this is a session cookie since it doesn't expire! */
597 co->livecookie = c->running;
599 /* now, we have parsed the incoming line, we must now check if this
600 superceeds an already existing cookie, which it may if the previous have
601 the same domain and path as this */
606 if(Curl_raw_equal(clist->name, co->name)) {
607 /* the names are identical */
609 if(clist->domain && co->domain) {
610 if(Curl_raw_equal(clist->domain, co->domain))
611 /* The domains are identical */
614 else if(!clist->domain && !co->domain)
618 /* the domains were identical */
620 if(clist->path && co->path) {
621 if(Curl_raw_equal(clist->path, co->path)) {
627 else if(!clist->path && !co->path)
634 if(replace_old && !co->livecookie && clist->livecookie) {
635 /* Both cookies matched fine, except that the already present
636 cookie is "live", which means it was set from a header, while
637 the new one isn't "live" and thus only read from a file. We let
638 live cookies stay alive */
640 /* Free the newcomer and get out of here! */
646 co->next = clist->next; /* get the next-pointer first */
648 /* then free all the old pointers */
657 free(clist->expirestr);
660 free(clist->version);
664 *clist = *co; /* then store all the new data */
666 free(co); /* free the newly alloced memory */
667 co = clist; /* point to the previous struct instead */
669 /* We have replaced a cookie, now skip the rest of the list but
670 make sure the 'lastc' pointer is properly set */
683 /* Only show this when NOT reading the cookies from a file */
684 infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, expire %d\n",
685 replace_old?"Replaced":"Added", co->name, co->value,
686 co->domain, co->path, co->expires);
689 /* then make the last item point on this new one */
696 c->numcookies++; /* one more cookie in the jar */
700 /*****************************************************************************
704 * Inits a cookie struct to read data from a local file. This is always
705 * called before any cookies are set. File may be NULL.
707 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
709 ****************************************************************************/
710 struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
712 struct CookieInfo *inc,
715 struct CookieInfo *c;
720 /* we didn't get a struct, create one */
721 c = calloc(1, sizeof(struct CookieInfo));
723 return NULL; /* failed to get memory */
724 c->filename = strdup(file?file:"none"); /* copy the name just in case */
727 /* we got an already existing one, use that */
730 c->running = FALSE; /* this is not running, this is init */
732 if(file && strequal(file, "-")) {
736 else if(file && !*file) {
737 /* points to a "" string */
741 fp = file?fopen(file, "r"):NULL;
743 c->newsession = newsession; /* new session? */
749 char *line = malloc(MAX_COOKIE_LINE);
751 while(fgets(line, MAX_COOKIE_LINE, fp)) {
752 if(checkprefix("Set-Cookie:", line)) {
753 /* This is a cookie line, get it! */
761 while(*lineptr && ISBLANK(*lineptr))
764 Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
766 free(line); /* free the line buffer */
772 c->running = TRUE; /* now, we're running */
777 /*****************************************************************************
779 * Curl_cookie_getlist()
781 * For a given host and path, return a linked list of cookies that the
782 * client should send to the server if used now. The secure boolean informs
783 * the cookie if a secure connection is achieved or not.
785 * It shall only return cookies that haven't expired.
787 ****************************************************************************/
789 struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
790 const char *host, const char *path,
793 struct Cookie *newco;
795 time_t now = time(NULL);
796 struct Cookie *mainco=NULL;
798 if(!c || !c->cookies)
799 return NULL; /* no cookie struct or no cookies in the struct */
804 /* only process this cookie if it is not expired or had no expire
805 date AND that if the cookie requires we're secure we must only
806 continue if we are! */
807 if( (!co->expires || (co->expires > now)) &&
808 (co->secure?secure:TRUE) ) {
810 /* now check if the domain is correct */
812 (co->tailmatch && tailmatch(co->domain, host)) ||
813 (!co->tailmatch && Curl_raw_equal(host, co->domain)) ) {
814 /* the right part of the host matches the domain stuff in the
817 /* now check the left part of the path with the cookies path
820 /* not using checkprefix() because matching should be
822 !strncmp(co->path, path, strlen(co->path)) ) {
824 /* and now, we know this is a match and we should create an
825 entry for the return-linked-list */
827 newco = malloc(sizeof(struct Cookie));
829 /* first, copy the whole source cookie: */
830 memcpy(newco, co, sizeof(struct Cookie));
832 /* then modify our next */
833 newco->next = mainco;
835 /* point the main to us */
839 /* failure, clear up the allocated chain and return NULL */
854 return mainco; /* return the new list */
857 /*****************************************************************************
859 * Curl_cookie_clearall()
861 * Clear all existing cookies and reset the counter.
863 ****************************************************************************/
864 void Curl_cookie_clearall(struct CookieInfo *cookies)
867 Curl_cookie_freelist(cookies->cookies, TRUE);
868 cookies->cookies = NULL;
869 cookies->numcookies = 0;
873 /*****************************************************************************
875 * Curl_cookie_freelist()
877 * Free a list of cookies previously returned by Curl_cookie_getlist();
879 * The 'cookiestoo' argument tells this function whether to just free the
880 * list or actually also free all cookies within the list as well.
882 ****************************************************************************/
884 void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo)
893 free(co); /* we only free the struct since the "members" are all just
894 pointed out in the main cookie list! */
901 /*****************************************************************************
903 * Curl_cookie_clearsess()
905 * Free all session cookies in the cookies list.
907 ****************************************************************************/
908 void Curl_cookie_clearsess(struct CookieInfo *cookies)
910 struct Cookie *first, *curr, *next, *prev = NULL;
912 if(!cookies || !cookies->cookies)
915 first = curr = prev = cookies->cookies;
917 for(; curr; curr = next) {
929 cookies->numcookies--;
935 cookies->cookies = first;
939 /*****************************************************************************
941 * Curl_cookie_cleanup()
943 * Free a "cookie object" previous created with cookie_init().
945 ****************************************************************************/
946 void Curl_cookie_cleanup(struct CookieInfo *c)
960 free(c); /* free the base struct as well */
964 /* get_netscape_format()
966 * Formats a string for Netscape output file, w/o a newline at the end.
968 * Function returns a char * to a formatted line. Has to be free()d
970 static char *get_netscape_format(const struct Cookie *co)
973 "%s" /* httponly preamble */
974 "%s%s\t" /* domain */
975 "%s\t" /* tailmatch */
978 "%" FORMAT_OFF_T "\t" /* expires */
981 co->httponly?"#HttpOnly_":"",
982 /* Make sure all domains are prefixed with a dot if they allow
983 tailmatching. This is Mozilla-style. */
984 (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
985 co->domain?co->domain:"unknown",
986 co->tailmatch?"TRUE":"FALSE",
987 co->path?co->path:"/",
988 co->secure?"TRUE":"FALSE",
991 co->value?co->value:"");
995 * Curl_cookie_output()
997 * Writes all internally known cookies to the specified file. Specify
998 * "-" as file name to write to stdout.
1000 * The function returns non-zero on write failure.
1002 int Curl_cookie_output(struct CookieInfo *c, const char *dumphere)
1006 bool use_stdout=FALSE;
1008 if((NULL == c) || (0 == c->numcookies))
1009 /* If there are no known cookies, we don't write or even create any
1013 if(strequal("-", dumphere)) {
1019 out = fopen(dumphere, "w");
1021 return 1; /* failure */
1027 fputs("# Netscape HTTP Cookie File\n"
1028 "# http://curl.haxx.se/rfc/cookie_spec.html\n"
1029 "# This file was generated by libcurl! Edit at your own risk.\n\n",
1034 format_ptr = get_netscape_format(co);
1035 if(format_ptr == NULL) {
1036 fprintf(out, "#\n# Fatal libcurl error\n");
1041 fprintf(out, "%s\n", format_ptr);
1053 struct curl_slist *Curl_cookie_list(struct SessionHandle *data)
1055 struct curl_slist *list = NULL;
1056 struct curl_slist *beg;
1060 if((data->cookies == NULL) ||
1061 (data->cookies->numcookies == 0))
1064 c = data->cookies->cookies;
1068 /* fill the list with _all_ the cookies we know */
1069 line = get_netscape_format(c);
1071 curl_slist_free_all(beg);
1074 list = curl_slist_append(list, line);
1077 curl_slist_free_all(beg);
1080 else if(beg == NULL) {
1089 #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */