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.
21 * $Id: cookie.c,v 1.52 2004/03/10 09:41:37 bagder Exp $
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: */
102 free_cookiemess(struct Cookie *co)
116 static bool tailmatch(const char *little, const char *bigone)
118 size_t littlelen = strlen(little);
119 size_t biglen = strlen(bigone);
121 if(littlelen > biglen)
124 return (bool)strequal(little, bigone+biglen-littlelen);
127 /****************************************************************************
131 * Add a single cookie line to the cookie keeping object.
133 ***************************************************************************/
136 Curl_cookie_add(struct SessionHandle *data,
137 /* The 'data' pointer here may be NULL at times, and thus
138 must only be used very carefully for things that can deal
139 with data being NULL. Such as infof() and similar */
141 struct CookieInfo *c,
142 bool httpheader, /* TRUE if HTTP header-style line */
143 char *lineptr, /* first character of the line */
144 char *domain, /* default domain */
145 char *path) /* full path used when this cookie is set,
146 used to get default path for the cookie
149 struct Cookie *clist;
150 char what[MAX_COOKIE_LINE];
155 struct Cookie *lastc=NULL;
156 time_t now = time(NULL);
157 bool replace_old = FALSE;
158 bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
160 /* First, alloc and init a new struct for it */
161 co = (struct Cookie *)calloc(sizeof(struct Cookie), 1);
163 return NULL; /* bail out if we're this low on memory */
166 /* This line was read off a HTTP-header */
168 semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
170 while(*lineptr && isspace((int)*lineptr))
175 /* we have a <what>=<this> pair or a 'secure' word here */
176 sep = strchr(ptr, '=');
177 if(sep && (!semiptr || (semiptr>sep)) ) {
179 * There is a = sign and if there was a semicolon too, which make sure
180 * that the semicolon comes _after_ the equal sign.
183 name[0]=what[0]=0; /* init the buffers */
184 if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;=]=%"
185 MAX_COOKIE_LINE_TXT "[^;\r\n]",
187 /* this is a <name>=<what> pair */
191 /* Strip off trailing whitespace from the 'what' */
192 size_t len=strlen(what);
193 while(len && isspace((int)what[len-1])) {
198 /* Skip leading whitespace from the 'what' */
200 while(isspace((int)*whatptr)) {
204 if(strequal("path", name)) {
205 co->path=strdup(whatptr);
207 else if(strequal("domain", name)) {
208 /* note that this name may or may not have a preceeding dot, but
209 we don't care about that, we treat the names the same anyway */
211 const char *domptr=whatptr;
215 static const char *seventhree[]= {
216 "com", "edu", "net", "org", "gov", "mil", "int"
219 /* Count the dots, we need to make sure that there are THREE dots
220 in the normal domains, or TWO in the seventhree-domains. */
222 if('.' == whatptr[0])
223 /* don't count the initial dot, assume it */
227 domptr = strchr(domptr, '.');
235 i<sizeof(seventhree)/sizeof(seventhree[0]); i++) {
236 if(tailmatch(seventhree[i], whatptr)) {
237 dotcount++; /* we allow one dot less for these */
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",
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(!domain || tailmatch(whatptr, domain)) {
259 const char *tailptr=whatptr;
260 if(tailptr[0] == '.')
262 co->domain=strdup(tailptr); /* don't prefix w/dots internally */
263 co->tailmatch=TRUE; /* we always do that if the domain name was
267 /* we did not get a tailmatch and then the attempted set domain
268 is not a domain to which the current host belongs. Mark as
271 infof(data, "skipped cookie with bad tailmatch domain: %s",
276 else if(strequal("version", name)) {
277 co->version=strdup(whatptr);
279 else if(strequal("max-age", name)) {
280 /* Defined in RFC2109:
282 Optional. The Max-Age attribute defines the lifetime of the
283 cookie, in seconds. The delta-seconds value is a decimal non-
284 negative integer. After delta-seconds seconds elapse, the
285 client should discard the cookie. A value of zero means the
286 cookie should be discarded immediately.
289 co->maxage = strdup(whatptr);
291 atoi((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0]) + now;
293 else if(strequal("expires", name)) {
294 co->expirestr=strdup(whatptr);
295 co->expires = curl_getdate(what, &now);
298 co->name = strdup(name);
299 co->value = strdup(whatptr);
302 else this is the second (or more) name we don't know
306 /* this is an "illegal" <what>=<this> pair */
310 if(sscanf(ptr, "%" MAX_COOKIE_LINE_TXT "[^;\r\n]",
312 if(strequal("secure", what))
315 unsupported keyword without assign! */
319 if(!semiptr || !*semiptr) {
320 /* we already know there are no more cookies */
326 while(ptr && *ptr && isspace((int)*ptr))
328 semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
331 /* There are no more semicolons, but there's a final name=value pair
333 semiptr=strchr(ptr, '\0');
336 if(badcookie || (NULL == co->name)) {
337 /* we didn't get a cookie name or a bad one,
338 this is an illegal line, bail out */
353 if(NULL == co->domain)
354 /* no domain was given in the header line, set the default now */
355 co->domain=domain?strdup(domain):NULL;
356 if((NULL == co->path) && path) {
357 /* no path was given in the header line, set the default now */
358 char *endslash = strrchr(path, '/');
360 size_t pathlen = endslash-path+1; /* include the ending slash */
361 co->path=malloc(pathlen+1); /* one extra for the zero byte */
363 memcpy(co->path, path, pathlen);
364 co->path[pathlen]=0; /* zero terminate */
370 /* This line is NOT a HTTP header style line, we do offer support for
371 reading the odd netscape cookies-file format here */
376 if(lineptr[0]=='#') {
377 /* don't even try the comments */
381 /* strip off the possible end-of-line characters */
382 ptr=strchr(lineptr, '\r');
384 *ptr=0; /* clear it */
385 ptr=strchr(lineptr, '\n');
387 *ptr=0; /* clear it */
389 firstptr=strtok_r(lineptr, "\t", &tok_buf); /* first tokenize it on the TAB */
391 /* Here's a quick check to eliminate normal HTTP-headers from this */
392 if(!firstptr || strchr(firstptr, ':')) {
397 /* Now loop through the fields and init the struct we already have
399 for(ptr=firstptr, fields=0; ptr;
400 ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
403 if(ptr[0]=='.') /* skip preceeding dots */
405 co->domain = strdup(ptr);
408 /* This field got its explanation on the 23rd of May 2001 by
411 flag: A TRUE/FALSE value indicating if all machines within a given
412 domain can access the variable. This value is set automatically by
413 the browser, depending on the value you set for the domain.
415 As far as I can see, it is set to true when the cookie says
416 .domain.com and to false when the domain is complete www.domain.com
418 co->tailmatch=(bool)strequal(ptr, "TRUE"); /* store information */
421 /* It turns out, that sometimes the file format allows the path
422 field to remain not filled in, we try to detect this and work
423 around it! Andrés GarcÃa made us aware of this... */
424 if (strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
425 /* only if the path doesn't look like a boolean option! */
426 co->path = strdup(ptr);
429 /* this doesn't look like a path, make one up! */
430 co->path = strdup("/");
431 fields++; /* add a field and fall down to secure */
434 co->secure = (bool)strequal(ptr, "TRUE");
437 co->expires = atoi(ptr);
440 co->name = strdup(ptr);
443 co->value = strdup(ptr);
449 /* we got a cookie with blank contents, fix it */
450 co->value = strdup("");
452 else if(7 != fields) {
453 /* we did not find the sufficient number of fields to recognize this
454 as a valid line, abort and go home */
460 if(!c->running && /* read from a file */
461 c->newsession && /* clean session cookies */
462 !co->expires) { /* this is a session cookie since it doesn't expire! */
467 co->livecookie = c->running;
469 /* now, we have parsed the incoming line, we must now check if this
470 superceeds an already existing cookie, which it may if the previous have
471 the same domain and path as this */
476 if(strequal(clist->name, co->name)) {
477 /* the names are identical */
479 if(clist->domain && co->domain) {
480 if(strequal(clist->domain, co->domain))
481 /* The domains are identical */
484 else if(!clist->domain && !co->domain)
488 /* the domains were identical */
490 if(clist->path && co->path) {
491 if(strequal(clist->path, co->path)) {
497 else if(!clist->path && !co->path)
504 if(replace_old && !co->livecookie && clist->livecookie) {
505 /* Both cookies matched fine, except that the already present
506 cookie is "live", which means it was set from a header, while
507 the new one isn't "live" and thus only read from a file. We let
508 live cookies stay alive */
510 /* Free the newcomer and get out of here! */
525 co->next = clist->next; /* get the next-pointer first */
527 /* then free all the old pointers */
537 free(clist->expirestr);
540 free(clist->version);
544 *clist = *co; /* then store all the new data */
546 free(co); /* free the newly alloced memory */
547 co = clist; /* point to the previous struct instead */
549 /* We have replaced a cookie, now skip the rest of the list but
550 make sure the 'lastc' pointer is properly set */
563 /* Only show this when NOT reading the cookies from a file */
564 infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, expire %d\n",
565 replace_old?"Replaced":"Added", co->name, co->value,
566 co->domain, co->path, co->expires);
569 /* then make the last item point on this new one */
576 c->numcookies++; /* one more cookie in the jar */
580 /*****************************************************************************
584 * Inits a cookie struct to read data from a local file. This is always
585 * called before any cookies are set. File may be NULL.
587 * If 'newsession' is TRUE, discard all "session cookies" on read from file.
589 ****************************************************************************/
590 struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
592 struct CookieInfo *inc,
595 char line[MAX_COOKIE_LINE];
596 struct CookieInfo *c;
601 /* we didn't get a struct, create one */
602 c = (struct CookieInfo *)malloc(sizeof(struct CookieInfo));
604 return NULL; /* failed to get memory */
605 memset(c, 0, sizeof(struct CookieInfo));
606 c->filename = strdup(file?file:"none"); /* copy the name just in case */
609 /* we got an already existing one, use that */
612 c->running = FALSE; /* this is not running, this is init */
614 if(file && strequal(file, "-")) {
619 fp = file?fopen(file, "r"):NULL;
621 c->newsession = newsession; /* new session? */
626 while(fgets(line, MAX_COOKIE_LINE, fp)) {
627 if(checkprefix("Set-Cookie:", line)) {
628 /* This is a cookie line, get it! */
636 while(*lineptr && isspace((int)*lineptr))
639 Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
645 c->running = TRUE; /* now, we're running */
650 /*****************************************************************************
652 * Curl_cookie_getlist()
654 * For a given host and path, return a linked list of cookies that the
655 * client should send to the server if used now. The secure boolean informs
656 * the cookie if a secure connection is achieved or not.
658 * It shall only return cookies that haven't expired.
660 ****************************************************************************/
662 struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
663 char *host, char *path, bool secure)
665 struct Cookie *newco;
667 time_t now = time(NULL);
668 struct Cookie *mainco=NULL;
670 if(!c || !c->cookies)
671 return NULL; /* no cookie struct or no cookies in the struct */
676 /* only process this cookie if it is not expired or had no expire
677 date AND that if the cookie requires we're secure we must only
678 continue if we are! */
679 if( (co->expires<=0 || (co->expires> now)) &&
680 (co->secure?secure:TRUE) ) {
682 /* now check if the domain is correct */
684 (co->tailmatch && tailmatch(co->domain, host)) ||
685 (!co->tailmatch && strequal(host, co->domain)) ) {
686 /* the right part of the host matches the domain stuff in the
689 /* now check the left part of the path with the cookies path
692 checkprefix(co->path, path) ) {
694 /* and now, we know this is a match and we should create an
695 entry for the return-linked-list */
697 newco = (struct Cookie *)malloc(sizeof(struct Cookie));
699 /* first, copy the whole source cookie: */
700 memcpy(newco, co, sizeof(struct Cookie));
702 /* then modify our next */
703 newco->next = mainco;
705 /* point the main to us */
714 return mainco; /* return the new list */
718 /*****************************************************************************
720 * Curl_cookie_freelist()
722 * Free a list of cookies previously returned by Curl_cookie_getlist();
724 ****************************************************************************/
726 void Curl_cookie_freelist(struct Cookie *co)
732 free(co); /* we only free the struct since the "members" are all
739 /*****************************************************************************
741 * Curl_cookie_cleanup()
743 * Free a "cookie object" previous created with cookie_init().
745 ****************************************************************************/
746 void Curl_cookie_cleanup(struct CookieInfo *c)
776 free(c); /* free the base struct as well */
781 * Curl_cookie_output()
783 * Writes all internally known cookies to the specified file. Specify
784 * "-" as file name to write to stdout.
786 * The function returns non-zero on write failure.
788 int Curl_cookie_output(struct CookieInfo *c, char *dumphere)
792 bool use_stdout=FALSE;
794 if((NULL == c) || (0 == c->numcookies))
795 /* If there are no known cookies, we don't write or even create any
799 if(strequal("-", dumphere)) {
805 out = fopen(dumphere, "w");
807 return 1; /* failure */
811 fputs("# Netscape HTTP Cookie File\n"
812 "# http://www.netscape.com/newsref/std/cookie_spec.html\n"
813 "# This file was generated by libcurl! Edit at your own risk.\n\n",
819 "%s%s\t" /* domain */
820 "%s\t" /* tailmatch */
827 /* Make sure all domains are prefixed with a dot if they allow
828 tailmatching. This is Mozilla-style. */
829 (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
830 co->domain?co->domain:"unknown",
831 co->tailmatch?"TRUE":"FALSE",
832 co->path?co->path:"/",
833 co->secure?"TRUE":"FALSE",
834 (unsigned int)co->expires,
836 co->value?co->value:"");
848 #endif /* CURL_DISABLE_HTTP */