1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2004, 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 #ifndef CURL_DISABLE_HTTP
96 /* The last #include file should be: */
101 static void freecookie(struct Cookie *co)
117 static bool tailmatch(const char *little, const char *bigone)
119 size_t littlelen = strlen(little);
120 size_t biglen = strlen(bigone);
122 if(littlelen > biglen)
125 return (bool)strequal(little, bigone+biglen-littlelen);
128 /****************************************************************************
132 * Add a single cookie line to the cookie keeping object.
134 ***************************************************************************/
137 Curl_cookie_add(struct SessionHandle *data,
138 /* The 'data' pointer here may be NULL at times, and thus
139 must only be used very carefully for things that can deal
140 with data being NULL. Such as infof() and similar */
142 struct CookieInfo *c,
143 bool httpheader, /* TRUE if HTTP header-style line */
144 char *lineptr, /* first character of the line */
145 char *domain, /* default domain */
146 char *path) /* full path used when this cookie is set,
147 used to get default path for the cookie
150 struct Cookie *clist;
156 struct Cookie *lastc=NULL;
157 time_t now = time(NULL);
158 bool replace_old = FALSE;
159 bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
161 /* First, alloc and init a new struct for it */
162 co = (struct Cookie *)calloc(sizeof(struct Cookie), 1);
164 return NULL; /* bail out if we're this low on memory */
167 /* This line was read off a HTTP-header */
170 what = malloc(MAX_COOKIE_LINE);
176 semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
178 while(*lineptr && isspace((int)*lineptr))
183 /* we have a <what>=<this> pair or a 'secure' word here */
184 sep = strchr(ptr, '=');
185 if(sep && (!semiptr || (semiptr>sep)) ) {
187 * There is a = sign and if there was a semicolon too, which make sure
188 * that the semicolon comes _after_ the equal sign.
191 name[0]=what[0]=0; /* init the buffers */
192 if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;=]=%"
193 MAX_COOKIE_LINE_TXT "[^;\r\n]",
195 /* this is a <name>=<what> pair */
199 /* Strip off trailing whitespace from the 'what' */
200 size_t len=strlen(what);
201 while(len && isspace((int)what[len-1])) {
206 /* Skip leading whitespace from the 'what' */
208 while(isspace((int)*whatptr)) {
212 if(strequal("path", name)) {
213 co->path=strdup(whatptr);
215 badcookie = TRUE; /* out of memory bad */
219 else if(strequal("domain", name)) {
220 /* note that this name may or may not have a preceeding dot, but
221 we don't care about that, we treat the names the same anyway */
223 const char *domptr=whatptr;
226 /* Count the dots, we need to make sure that there are enough
229 if('.' == whatptr[0])
230 /* don't count the initial dot, assume it */
234 domptr = strchr(domptr, '.');
241 /* The original Netscape cookie spec defined that this domain name
242 MUST have three dots (or two if one of the seven holy TLDs),
243 but it seems that these kinds of cookies are in use "out there"
244 so we cannot be that strict. I've therefore lowered the check
245 to not allow less than two dots. */
248 /* Received and skipped a cookie with a domain using too few
250 badcookie=TRUE; /* mark this as a bad cookie */
251 infof(data, "skipped cookie with illegal dotcount domain: %s\n",
255 /* Now, we make sure that our host is within the given domain,
256 or the given domain is not valid and thus cannot be set. */
258 if('.' == whatptr[0])
259 whatptr++; /* ignore preceeding dot */
261 if(!domain || tailmatch(whatptr, domain)) {
262 const char *tailptr=whatptr;
263 if(tailptr[0] == '.')
265 co->domain=strdup(tailptr); /* don't prefix w/dots
271 co->tailmatch=TRUE; /* we always do that if the domain name was
275 /* we did not get a tailmatch and then the attempted set domain
276 is not a domain to which the current host belongs. Mark as
279 infof(data, "skipped cookie with bad tailmatch domain: %s\n",
284 else if(strequal("version", name)) {
285 co->version=strdup(whatptr);
291 else if(strequal("max-age", name)) {
292 /* Defined in RFC2109:
294 Optional. The Max-Age attribute defines the lifetime of the
295 cookie, in seconds. The delta-seconds value is a decimal non-
296 negative integer. After delta-seconds seconds elapse, the
297 client should discard the cookie. A value of zero means the
298 cookie should be discarded immediately.
301 co->maxage = strdup(whatptr);
307 atoi((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0]) + now;
309 else if(strequal("expires", name)) {
310 co->expirestr=strdup(whatptr);
315 co->expires = curl_getdate(what, &now);
318 co->name = strdup(name);
319 co->value = strdup(whatptr);
320 if(!co->name || !co->value) {
326 else this is the second (or more) name we don't know
330 /* this is an "illegal" <what>=<this> pair */
334 if(sscanf(ptr, "%" MAX_COOKIE_LINE_TXT "[^;\r\n]",
336 if(strequal("secure", what))
339 unsupported keyword without assign! */
343 if(!semiptr || !*semiptr) {
344 /* we already know there are no more cookies */
350 while(ptr && *ptr && isspace((int)*ptr))
352 semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
355 /* There are no more semicolons, but there's a final name=value pair
357 semiptr=strchr(ptr, '\0');
360 if(!badcookie && !co->domain) {
362 /* no domain was given in the header line, set the default */
363 co->domain=strdup(domain);
369 if(!badcookie && !co->path && path) {
370 /* no path was given in the header line, set the default */
371 char *endslash = strrchr(path, '/');
373 size_t pathlen = endslash-path+1; /* include the ending slash */
374 co->path=malloc(pathlen+1); /* one extra for the zero byte */
376 memcpy(co->path, path, pathlen);
377 co->path[pathlen]=0; /* zero terminate */
386 if(badcookie || !co->name) {
387 /* we didn't get a cookie name or a bad one,
388 this is an illegal line, bail out */
395 /* This line is NOT a HTTP header style line, we do offer support for
396 reading the odd netscape cookies-file format here */
401 if(lineptr[0]=='#') {
402 /* don't even try the comments */
406 /* strip off the possible end-of-line characters */
407 ptr=strchr(lineptr, '\r');
409 *ptr=0; /* clear it */
410 ptr=strchr(lineptr, '\n');
412 *ptr=0; /* clear it */
414 firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
416 /* Here's a quick check to eliminate normal HTTP-headers from this */
417 if(!firstptr || strchr(firstptr, ':')) {
422 /* Now loop through the fields and init the struct we already have
424 for(ptr=firstptr, fields=0; ptr && !badcookie;
425 ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
428 if(ptr[0]=='.') /* skip preceeding dots */
430 co->domain = strdup(ptr);
435 /* This field got its explanation on the 23rd of May 2001 by
438 flag: A TRUE/FALSE value indicating if all machines within a given
439 domain can access the variable. This value is set automatically by
440 the browser, depending on the value you set for the domain.
442 As far as I can see, it is set to true when the cookie says
443 .domain.com and to false when the domain is complete www.domain.com
445 co->tailmatch=(bool)strequal(ptr, "TRUE"); /* store information */
448 /* It turns out, that sometimes the file format allows the path
449 field to remain not filled in, we try to detect this and work
450 around it! Andrés GarcÃa made us aware of this... */
451 if (strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
452 /* only if the path doesn't look like a boolean option! */
453 co->path = strdup(ptr);
458 /* this doesn't look like a path, make one up! */
459 co->path = strdup("/");
462 fields++; /* add a field and fall down to secure */
465 co->secure = (bool)strequal(ptr, "TRUE");
468 co->expires = atoi(ptr);
471 co->name = strdup(ptr);
476 co->value = strdup(ptr);
483 /* we got a cookie with blank contents, fix it */
484 co->value = strdup("");
491 if(!badcookie && (7 != fields))
492 /* we did not find the sufficient number of fields */
502 if(!c->running && /* read from a file */
503 c->newsession && /* clean session cookies */
504 !co->expires) { /* this is a session cookie since it doesn't expire! */
509 co->livecookie = c->running;
511 /* now, we have parsed the incoming line, we must now check if this
512 superceeds an already existing cookie, which it may if the previous have
513 the same domain and path as this */
518 if(strequal(clist->name, co->name)) {
519 /* the names are identical */
521 if(clist->domain && co->domain) {
522 if(strequal(clist->domain, co->domain))
523 /* The domains are identical */
526 else if(!clist->domain && !co->domain)
530 /* the domains were identical */
532 if(clist->path && co->path) {
533 if(strequal(clist->path, co->path)) {
539 else if(!clist->path && !co->path)
546 if(replace_old && !co->livecookie && clist->livecookie) {
547 /* Both cookies matched fine, except that the already present
548 cookie is "live", which means it was set from a header, while
549 the new one isn't "live" and thus only read from a file. We let
550 live cookies stay alive */
552 /* Free the newcomer and get out of here! */
558 co->next = clist->next; /* get the next-pointer first */
560 /* then free all the old pointers */
570 free(clist->expirestr);
573 free(clist->version);
577 *clist = *co; /* then store all the new data */
579 free(co); /* free the newly alloced memory */
580 co = clist; /* point to the previous struct instead */
582 /* We have replaced a cookie, now skip the rest of the list but
583 make sure the 'lastc' pointer is properly set */
596 /* Only show this when NOT reading the cookies from a file */
597 infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, expire %d\n",
598 replace_old?"Replaced":"Added", co->name, co->value,
599 co->domain, co->path, co->expires);
602 /* then make the last item point on this new one */
609 c->numcookies++; /* one more cookie in the jar */
613 /*****************************************************************************
617 * Inits a cookie struct to read data from a local file. This is always
618 * called before any cookies are set. File may be NULL.
620 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
622 ****************************************************************************/
623 struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
625 struct CookieInfo *inc,
628 struct CookieInfo *c;
633 /* we didn't get a struct, create one */
634 c = (struct CookieInfo *)calloc(1, sizeof(struct CookieInfo));
636 return NULL; /* failed to get memory */
637 c->filename = strdup(file?file:"none"); /* copy the name just in case */
640 /* we got an already existing one, use that */
643 c->running = FALSE; /* this is not running, this is init */
645 if(file && strequal(file, "-")) {
650 fp = file?fopen(file, "r"):NULL;
652 c->newsession = newsession; /* new session? */
658 char *line = (char *)malloc(MAX_COOKIE_LINE);
660 while(fgets(line, MAX_COOKIE_LINE, fp)) {
661 if(checkprefix("Set-Cookie:", line)) {
662 /* This is a cookie line, get it! */
670 while(*lineptr && isspace((int)*lineptr))
673 Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
675 free(line); /* free the line buffer */
681 c->running = TRUE; /* now, we're running */
686 /*****************************************************************************
688 * Curl_cookie_getlist()
690 * For a given host and path, return a linked list of cookies that the
691 * client should send to the server if used now. The secure boolean informs
692 * the cookie if a secure connection is achieved or not.
694 * It shall only return cookies that haven't expired.
696 ****************************************************************************/
698 struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
699 char *host, char *path, bool secure)
701 struct Cookie *newco;
703 time_t now = time(NULL);
704 struct Cookie *mainco=NULL;
706 if(!c || !c->cookies)
707 return NULL; /* no cookie struct or no cookies in the struct */
712 /* only process this cookie if it is not expired or had no expire
713 date AND that if the cookie requires we're secure we must only
714 continue if we are! */
715 if( (co->expires<=0 || (co->expires> now)) &&
716 (co->secure?secure:TRUE) ) {
718 /* now check if the domain is correct */
720 (co->tailmatch && tailmatch(co->domain, host)) ||
721 (!co->tailmatch && strequal(host, co->domain)) ) {
722 /* the right part of the host matches the domain stuff in the
725 /* now check the left part of the path with the cookies path
728 checkprefix(co->path, path) ) {
730 /* and now, we know this is a match and we should create an
731 entry for the return-linked-list */
733 newco = (struct Cookie *)malloc(sizeof(struct Cookie));
735 /* first, copy the whole source cookie: */
736 memcpy(newco, co, sizeof(struct Cookie));
738 /* then modify our next */
739 newco->next = mainco;
741 /* point the main to us */
745 /* failure, clear up the allocated chain and return NULL */
760 return mainco; /* return the new list */
764 /*****************************************************************************
766 * Curl_cookie_freelist()
768 * Free a list of cookies previously returned by Curl_cookie_getlist();
770 ****************************************************************************/
772 void Curl_cookie_freelist(struct Cookie *co)
778 free(co); /* we only free the struct since the "members" are all
785 /*****************************************************************************
787 * Curl_cookie_cleanup()
789 * Free a "cookie object" previous created with cookie_init().
791 ****************************************************************************/
792 void Curl_cookie_cleanup(struct CookieInfo *c)
806 free(c); /* free the base struct as well */
811 * Curl_cookie_output()
813 * Writes all internally known cookies to the specified file. Specify
814 * "-" as file name to write to stdout.
816 * The function returns non-zero on write failure.
818 int Curl_cookie_output(struct CookieInfo *c, char *dumphere)
822 bool use_stdout=FALSE;
824 if((NULL == c) || (0 == c->numcookies))
825 /* If there are no known cookies, we don't write or even create any
829 if(strequal("-", dumphere)) {
835 out = fopen(dumphere, "w");
837 return 1; /* failure */
841 fputs("# Netscape HTTP Cookie File\n"
842 "# http://www.netscape.com/newsref/std/cookie_spec.html\n"
843 "# This file was generated by libcurl! Edit at your own risk.\n\n",
849 "%s%s\t" /* domain */
850 "%s\t" /* tailmatch */
857 /* Make sure all domains are prefixed with a dot if they allow
858 tailmatching. This is Mozilla-style. */
859 (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
860 co->domain?co->domain:"unknown",
861 co->tailmatch?"TRUE":"FALSE",
862 co->path?co->path:"/",
863 co->secure?"TRUE":"FALSE",
864 (unsigned int)co->expires,
866 co->value?co->value:"");
878 #endif /* CURL_DISABLE_HTTP */