cookie.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, 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 http://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. RECEIVING COOKIE INFORMATION
  24. ============================
  25. struct CookieInfo *cookie_init(char *file);
  26. Inits a cookie struct to store data in a local file. This is always
  27. called before any cookies are set.
  28. int cookies_set(struct CookieInfo *cookie, char *cookie_line);
  29. The 'cookie_line' parameter is a full "Set-cookie:" line as
  30. received from a server.
  31. The function need to replace previously stored lines that this new
  32. line superceeds.
  33. It may remove lines that are expired.
  34. It should return an indication of success/error.
  35. SENDING COOKIE INFORMATION
  36. ==========================
  37. struct Cookies *cookie_getlist(struct CookieInfo *cookie,
  38. char *host, char *path, bool secure);
  39. For a given host and path, return a linked list of cookies that
  40. the client should send to the server if used now. The secure
  41. boolean informs the cookie if a secure connection is achieved or
  42. not.
  43. It shall only return cookies that haven't expired.
  44. Example set of cookies:
  45. Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
  46. Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  47. domain=.fidelity.com; path=/ftgw; secure
  48. Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  49. domain=.fidelity.com; path=/; secure
  50. Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  51. domain=.fidelity.com; path=/; secure
  52. Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  53. domain=.fidelity.com; path=/; secure
  54. Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  55. domain=.fidelity.com; path=/; secure
  56. Set-cookie:
  57. Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
  58. 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
  59. ****/
  60. #include "setup.h"
  61. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  62. #include <stdlib.h>
  63. #include <string.h>
  64. #define _MPRINTF_REPLACE /* without this on windows OS we get undefined reference to snprintf */
  65. #include <curl/mprintf.h>
  66. #include "urldata.h"
  67. #include "cookie.h"
  68. #include "strequal.h"
  69. #include "strtok.h"
  70. #include "sendf.h"
  71. #include "curl_memory.h"
  72. #include "share.h"
  73. #include "strtoofft.h"
  74. #include "rawstr.h"
  75. #include "curl_memrchr.h"
  76. /* The last #include file should be: */
  77. #include "memdebug.h"
  78. static void freecookie(struct Cookie *co)
  79. {
  80. if(co->expirestr)
  81. free(co->expirestr);
  82. if(co->domain)
  83. free(co->domain);
  84. if(co->path)
  85. free(co->path);
  86. if(co->name)
  87. free(co->name);
  88. if(co->value)
  89. free(co->value);
  90. if(co->maxage)
  91. free(co->maxage);
  92. if(co->version)
  93. free(co->version);
  94. free(co);
  95. }
  96. static bool tailmatch(const char *little, const char *bigone)
  97. {
  98. size_t littlelen = strlen(little);
  99. size_t biglen = strlen(bigone);
  100. if(littlelen > biglen)
  101. return FALSE;
  102. return (bool)Curl_raw_equal(little, bigone+biglen-littlelen);
  103. }
  104. /*
  105. * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
  106. */
  107. void Curl_cookie_loadfiles(struct SessionHandle *data)
  108. {
  109. struct curl_slist *list = data->change.cookielist;
  110. if(list) {
  111. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  112. while(list) {
  113. data->cookies = Curl_cookie_init(data,
  114. list->data,
  115. data->cookies,
  116. data->set.cookiesession);
  117. list = list->next;
  118. }
  119. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  120. curl_slist_free_all(data->change.cookielist); /* clean up list */
  121. data->change.cookielist = NULL; /* don't do this again! */
  122. }
  123. }
  124. /*
  125. * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
  126. * that will be freed before the allocated string is stored there.
  127. *
  128. * It is meant to easily replace strdup()
  129. */
  130. static void strstore(char **str, const char *newstr)
  131. {
  132. if(*str)
  133. free(*str);
  134. *str = strdup(newstr);
  135. }
  136. /****************************************************************************
  137. *
  138. * Curl_cookie_add()
  139. *
  140. * Add a single cookie line to the cookie keeping object.
  141. *
  142. ***************************************************************************/
  143. struct Cookie *
  144. Curl_cookie_add(struct SessionHandle *data,
  145. /* The 'data' pointer here may be NULL at times, and thus
  146. must only be used very carefully for things that can deal
  147. with data being NULL. Such as infof() and similar */
  148. struct CookieInfo *c,
  149. bool httpheader, /* TRUE if HTTP header-style line */
  150. char *lineptr, /* first character of the line */
  151. const char *domain, /* default domain */
  152. const char *path) /* full path used when this cookie is set,
  153. used to get default path for the cookie
  154. unless set */
  155. {
  156. struct Cookie *clist;
  157. char name[MAX_NAME];
  158. struct Cookie *co;
  159. struct Cookie *lastc=NULL;
  160. time_t now = time(NULL);
  161. bool replace_old = FALSE;
  162. bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
  163. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  164. (void)data;
  165. #endif
  166. /* First, alloc and init a new struct for it */
  167. co = calloc(1, sizeof(struct Cookie));
  168. if(!co)
  169. return NULL; /* bail out if we're this low on memory */
  170. if(httpheader) {
  171. /* This line was read off a HTTP-header */
  172. const char *ptr;
  173. const char *sep;
  174. const char *semiptr;
  175. char *what;
  176. what = malloc(MAX_COOKIE_LINE);
  177. if(!what) {
  178. free(co);
  179. return NULL;
  180. }
  181. semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
  182. while(*lineptr && ISBLANK(*lineptr))
  183. lineptr++;
  184. ptr = lineptr;
  185. do {
  186. /* we have a <what>=<this> pair or a 'secure' word here */
  187. sep = strchr(ptr, '=');
  188. if(sep && (!semiptr || (semiptr>sep)) ) {
  189. /*
  190. * There is a = sign and if there was a semicolon too, which make sure
  191. * that the semicolon comes _after_ the equal sign.
  192. */
  193. name[0]=what[0]=0; /* init the buffers */
  194. if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;=]=%"
  195. MAX_COOKIE_LINE_TXT "[^;\r\n]",
  196. name, what)) {
  197. /* this is a <name>=<what> pair. We use strstore() below to properly
  198. deal with received cookie headers that have the same string
  199. property set more than once, and then we use the last one. */
  200. const char *whatptr;
  201. /* Strip off trailing whitespace from the 'what' */
  202. size_t len=strlen(what);
  203. while(len && ISBLANK(what[len-1])) {
  204. what[len-1]=0;
  205. len--;
  206. }
  207. /* Skip leading whitespace from the 'what' */
  208. whatptr=what;
  209. while(*whatptr && ISBLANK(*whatptr)) {
  210. whatptr++;
  211. }
  212. if(Curl_raw_equal("path", name)) {
  213. strstore(&co->path, whatptr);
  214. if(!co->path) {
  215. badcookie = TRUE; /* out of memory bad */
  216. break;
  217. }
  218. }
  219. else if(Curl_raw_equal("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 */
  222. const char *domptr=whatptr;
  223. int dotcount=1;
  224. /* Count the dots, we need to make sure that there are enough
  225. of them. */
  226. if('.' == whatptr[0])
  227. /* don't count the initial dot, assume it */
  228. domptr++;
  229. do {
  230. domptr = strchr(domptr, '.');
  231. if(domptr) {
  232. domptr++;
  233. dotcount++;
  234. }
  235. } while(domptr);
  236. /* The original Netscape cookie spec defined that this domain name
  237. MUST have three dots (or two if one of the seven holy TLDs),
  238. but it seems that these kinds of cookies are in use "out there"
  239. so we cannot be that strict. I've therefore lowered the check
  240. to not allow less than two dots. */
  241. if(dotcount < 2) {
  242. /* Received and skipped a cookie with a domain using too few
  243. dots. */
  244. badcookie=TRUE; /* mark this as a bad cookie */
  245. infof(data, "skipped cookie with illegal dotcount domain: %s\n",
  246. whatptr);
  247. }
  248. else {
  249. /* Now, we make sure that our host is within the given domain,
  250. or the given domain is not valid and thus cannot be set. */
  251. if('.' == whatptr[0])
  252. whatptr++; /* ignore preceeding dot */
  253. if(!domain || tailmatch(whatptr, domain)) {
  254. const char *tailptr=whatptr;
  255. if(tailptr[0] == '.')
  256. tailptr++;
  257. strstore(&co->domain, tailptr); /* don't prefix w/dots
  258. internally */
  259. if(!co->domain) {
  260. badcookie = TRUE;
  261. break;
  262. }
  263. co->tailmatch=TRUE; /* we always do that if the domain name was
  264. given */
  265. }
  266. else {
  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
  269. bad. */
  270. badcookie=TRUE;
  271. infof(data, "skipped cookie with bad tailmatch domain: %s\n",
  272. whatptr);
  273. }
  274. }
  275. }
  276. else if(Curl_raw_equal("version", name)) {
  277. strstore(&co->version, whatptr);
  278. if(!co->version) {
  279. badcookie = TRUE;
  280. break;
  281. }
  282. }
  283. else if(Curl_raw_equal("max-age", name)) {
  284. /* Defined in RFC2109:
  285. Optional. The Max-Age attribute defines the lifetime of the
  286. cookie, in seconds. The delta-seconds value is a decimal non-
  287. negative integer. After delta-seconds seconds elapse, the
  288. client should discard the cookie. A value of zero means the
  289. cookie should be discarded immediately.
  290. */
  291. strstore(&co->maxage, whatptr);
  292. if(!co->maxage) {
  293. badcookie = TRUE;
  294. break;
  295. }
  296. co->expires =
  297. strtol((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0],NULL,10)
  298. + (long)now;
  299. }
  300. else if(Curl_raw_equal("expires", name)) {
  301. strstore(&co->expirestr, whatptr);
  302. if(!co->expirestr) {
  303. badcookie = TRUE;
  304. break;
  305. }
  306. /* Note that if the date couldn't get parsed for whatever reason,
  307. the cookie will be treated as a session cookie */
  308. co->expires = curl_getdate(what, &now);
  309. /* Session cookies have expires set to 0 so if we get that back
  310. from the date parser let's add a second to make it a
  311. non-session cookie */
  312. if (co->expires == 0)
  313. co->expires = 1;
  314. else if( co->expires < 0 )
  315. co->expires = 0;
  316. }
  317. else if(!co->name) {
  318. co->name = strdup(name);
  319. co->value = strdup(whatptr);
  320. if(!co->name || !co->value) {
  321. badcookie = TRUE;
  322. break;
  323. }
  324. }
  325. /*
  326. else this is the second (or more) name we don't know
  327. about! */
  328. }
  329. else {
  330. /* this is an "illegal" <what>=<this> pair */
  331. }
  332. }
  333. else {
  334. if(sscanf(ptr, "%" MAX_COOKIE_LINE_TXT "[^;\r\n]",
  335. what)) {
  336. if(Curl_raw_equal("secure", what)) {
  337. co->secure = TRUE;
  338. }
  339. else if (Curl_raw_equal("httponly", what)) {
  340. co->httponly = TRUE;
  341. }
  342. /* else,
  343. unsupported keyword without assign! */
  344. }
  345. }
  346. if(!semiptr || !*semiptr) {
  347. /* we already know there are no more cookies */
  348. semiptr = NULL;
  349. continue;
  350. }
  351. ptr=semiptr+1;
  352. while(*ptr && ISBLANK(*ptr))
  353. ptr++;
  354. semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
  355. if(!semiptr && *ptr)
  356. /* There are no more semicolons, but there's a final name=value pair
  357. coming up */
  358. semiptr=strchr(ptr, '\0');
  359. } while(semiptr);
  360. if(!badcookie && !co->domain) {
  361. if(domain) {
  362. /* no domain was given in the header line, set the default */
  363. co->domain=strdup(domain);
  364. if(!co->domain)
  365. badcookie = TRUE;
  366. }
  367. }
  368. if(!badcookie && !co->path && path) {
  369. /* No path was given in the header line, set the default.
  370. Note that the passed-in path to this function MAY have a '?' and
  371. following part that MUST not be stored as part of the path. */
  372. char *queryp = strchr(path, '?');
  373. /* queryp is where the interesting part of the path ends, so now we
  374. want to the find the last */
  375. char *endslash;
  376. if(!queryp)
  377. endslash = strrchr(path, '/');
  378. else
  379. endslash = memrchr(path, '/', (size_t)(queryp - path));
  380. if(endslash) {
  381. size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
  382. co->path=malloc(pathlen+1); /* one extra for the zero byte */
  383. if(co->path) {
  384. memcpy(co->path, path, pathlen);
  385. co->path[pathlen]=0; /* zero terminate */
  386. }
  387. else
  388. badcookie = TRUE;
  389. }
  390. }
  391. free(what);
  392. if(badcookie || !co->name) {
  393. /* we didn't get a cookie name or a bad one,
  394. this is an illegal line, bail out */
  395. freecookie(co);
  396. return NULL;
  397. }
  398. }
  399. else {
  400. /* This line is NOT a HTTP header style line, we do offer support for
  401. reading the odd netscape cookies-file format here */
  402. char *ptr;
  403. char *firstptr;
  404. char *tok_buf=NULL;
  405. int fields;
  406. /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
  407. marked with httpOnly after the domain name are not accessible
  408. from javascripts, but since curl does not operate at javascript
  409. level, we include them anyway. In Firefox's cookie files, these
  410. lines are preceeded with #HttpOnly_ and then everything is
  411. as usual, so we skip 10 characters of the line..
  412. */
  413. if (strncmp(lineptr, "#HttpOnly_", 10) == 0) {
  414. lineptr += 10;
  415. co->httponly = TRUE;
  416. }
  417. if(lineptr[0]=='#') {
  418. /* don't even try the comments */
  419. free(co);
  420. return NULL;
  421. }
  422. /* strip off the possible end-of-line characters */
  423. ptr=strchr(lineptr, '\r');
  424. if(ptr)
  425. *ptr=0; /* clear it */
  426. ptr=strchr(lineptr, '\n');
  427. if(ptr)
  428. *ptr=0; /* clear it */
  429. firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
  430. /* Here's a quick check to eliminate normal HTTP-headers from this */
  431. if(!firstptr || strchr(firstptr, ':')) {
  432. free(co);
  433. return NULL;
  434. }
  435. /* Now loop through the fields and init the struct we already have
  436. allocated */
  437. for(ptr=firstptr, fields=0; ptr && !badcookie;
  438. ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
  439. switch(fields) {
  440. case 0:
  441. if(ptr[0]=='.') /* skip preceeding dots */
  442. ptr++;
  443. co->domain = strdup(ptr);
  444. if(!co->domain)
  445. badcookie = TRUE;
  446. break;
  447. case 1:
  448. /* This field got its explanation on the 23rd of May 2001 by
  449. Andrés García:
  450. flag: A TRUE/FALSE value indicating if all machines within a given
  451. domain can access the variable. This value is set automatically by
  452. the browser, depending on the value you set for the domain.
  453. As far as I can see, it is set to true when the cookie says
  454. .domain.com and to false when the domain is complete www.domain.com
  455. */
  456. co->tailmatch=(bool)Curl_raw_equal(ptr, "TRUE"); /* store information */
  457. break;
  458. case 2:
  459. /* It turns out, that sometimes the file format allows the path
  460. field to remain not filled in, we try to detect this and work
  461. around it! Andrés García made us aware of this... */
  462. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  463. /* only if the path doesn't look like a boolean option! */
  464. co->path = strdup(ptr);
  465. if(!co->path)
  466. badcookie = TRUE;
  467. break;
  468. }
  469. /* this doesn't look like a path, make one up! */
  470. co->path = strdup("/");
  471. if(!co->path)
  472. badcookie = TRUE;
  473. fields++; /* add a field and fall down to secure */
  474. /* FALLTHROUGH */
  475. case 3:
  476. co->secure = (bool)Curl_raw_equal(ptr, "TRUE");
  477. break;
  478. case 4:
  479. co->expires = curlx_strtoofft(ptr, NULL, 10);
  480. break;
  481. case 5:
  482. co->name = strdup(ptr);
  483. if(!co->name)
  484. badcookie = TRUE;
  485. break;
  486. case 6:
  487. co->value = strdup(ptr);
  488. if(!co->value)
  489. badcookie = TRUE;
  490. break;
  491. }
  492. }
  493. if(6 == fields) {
  494. /* we got a cookie with blank contents, fix it */
  495. co->value = strdup("");
  496. if(!co->value)
  497. badcookie = TRUE;
  498. else
  499. fields++;
  500. }
  501. if(!badcookie && (7 != fields))
  502. /* we did not find the sufficient number of fields */
  503. badcookie = TRUE;
  504. if(badcookie) {
  505. freecookie(co);
  506. return NULL;
  507. }
  508. }
  509. if(!c->running && /* read from a file */
  510. c->newsession && /* clean session cookies */
  511. !co->expires) { /* this is a session cookie since it doesn't expire! */
  512. freecookie(co);
  513. return NULL;
  514. }
  515. co->livecookie = c->running;
  516. /* now, we have parsed the incoming line, we must now check if this
  517. superceeds an already existing cookie, which it may if the previous have
  518. the same domain and path as this */
  519. clist = c->cookies;
  520. replace_old = FALSE;
  521. while(clist) {
  522. if(Curl_raw_equal(clist->name, co->name)) {
  523. /* the names are identical */
  524. if(clist->domain && co->domain) {
  525. if(Curl_raw_equal(clist->domain, co->domain))
  526. /* The domains are identical */
  527. replace_old=TRUE;
  528. }
  529. else if(!clist->domain && !co->domain)
  530. replace_old = TRUE;
  531. if(replace_old) {
  532. /* the domains were identical */
  533. if(clist->path && co->path) {
  534. if(Curl_raw_equal(clist->path, co->path)) {
  535. replace_old = TRUE;
  536. }
  537. else
  538. replace_old = FALSE;
  539. }
  540. else if(!clist->path && !co->path)
  541. replace_old = TRUE;
  542. else
  543. replace_old = FALSE;
  544. }
  545. if(replace_old && !co->livecookie && clist->livecookie) {
  546. /* Both cookies matched fine, except that the already present
  547. cookie is "live", which means it was set from a header, while
  548. the new one isn't "live" and thus only read from a file. We let
  549. live cookies stay alive */
  550. /* Free the newcomer and get out of here! */
  551. freecookie(co);
  552. return NULL;
  553. }
  554. if(replace_old) {
  555. co->next = clist->next; /* get the next-pointer first */
  556. /* then free all the old pointers */
  557. free(clist->name);
  558. if(clist->value)
  559. free(clist->value);
  560. if(clist->domain)
  561. free(clist->domain);
  562. if(clist->path)
  563. free(clist->path);
  564. if(clist->expirestr)
  565. free(clist->expirestr);
  566. if(clist->version)
  567. free(clist->version);
  568. if(clist->maxage)
  569. free(clist->maxage);
  570. *clist = *co; /* then store all the new data */
  571. free(co); /* free the newly alloced memory */
  572. co = clist; /* point to the previous struct instead */
  573. /* We have replaced a cookie, now skip the rest of the list but
  574. make sure the 'lastc' pointer is properly set */
  575. do {
  576. lastc = clist;
  577. clist = clist->next;
  578. } while(clist);
  579. break;
  580. }
  581. }
  582. lastc = clist;
  583. clist = clist->next;
  584. }
  585. if(c->running)
  586. /* Only show this when NOT reading the cookies from a file */
  587. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  588. "expire %" FORMAT_OFF_T "\n",
  589. replace_old?"Replaced":"Added", co->name, co->value,
  590. co->domain, co->path, co->expires);
  591. if(!replace_old) {
  592. /* then make the last item point on this new one */
  593. if(lastc)
  594. lastc->next = co;
  595. else
  596. c->cookies = co;
  597. }
  598. c->numcookies++; /* one more cookie in the jar */
  599. return co;
  600. }
  601. /*****************************************************************************
  602. *
  603. * Curl_cookie_init()
  604. *
  605. * Inits a cookie struct to read data from a local file. This is always
  606. * called before any cookies are set. File may be NULL.
  607. *
  608. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  609. *
  610. ****************************************************************************/
  611. struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
  612. const char *file,
  613. struct CookieInfo *inc,
  614. bool newsession)
  615. {
  616. struct CookieInfo *c;
  617. FILE *fp;
  618. bool fromfile=TRUE;
  619. if(NULL == inc) {
  620. /* we didn't get a struct, create one */
  621. c = calloc(1, sizeof(struct CookieInfo));
  622. if(!c)
  623. return NULL; /* failed to get memory */
  624. c->filename = strdup(file?file:"none"); /* copy the name just in case */
  625. }
  626. else {
  627. /* we got an already existing one, use that */
  628. c = inc;
  629. }
  630. c->running = FALSE; /* this is not running, this is init */
  631. if(file && strequal(file, "-")) {
  632. fp = stdin;
  633. fromfile=FALSE;
  634. }
  635. else if(file && !*file) {
  636. /* points to a "" string */
  637. fp = NULL;
  638. }
  639. else
  640. fp = file?fopen(file, "r"):NULL;
  641. c->newsession = newsession; /* new session? */
  642. if(fp) {
  643. char *lineptr;
  644. bool headerline;
  645. char *line = malloc(MAX_COOKIE_LINE);
  646. if(line) {
  647. while(fgets(line, MAX_COOKIE_LINE, fp)) {
  648. if(checkprefix("Set-Cookie:", line)) {
  649. /* This is a cookie line, get it! */
  650. lineptr=&line[11];
  651. headerline=TRUE;
  652. }
  653. else {
  654. lineptr=line;
  655. headerline=FALSE;
  656. }
  657. while(*lineptr && ISBLANK(*lineptr))
  658. lineptr++;
  659. Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
  660. }
  661. free(line); /* free the line buffer */
  662. }
  663. if(fromfile)
  664. fclose(fp);
  665. }
  666. c->running = TRUE; /* now, we're running */
  667. return c;
  668. }
  669. /* sort this so that the longest path gets before the shorter path */
  670. static int cookie_sort(const void *p1, const void *p2)
  671. {
  672. struct Cookie *c1 = *(struct Cookie **)p1;
  673. struct Cookie *c2 = *(struct Cookie **)p2;
  674. size_t l1 = c1->path?strlen(c1->path):0;
  675. size_t l2 = c2->path?strlen(c2->path):0;
  676. return (l2 > l1) ? 1 : (l2 < l1) ? -1 : 0 ;
  677. }
  678. /*****************************************************************************
  679. *
  680. * Curl_cookie_getlist()
  681. *
  682. * For a given host and path, return a linked list of cookies that the
  683. * client should send to the server if used now. The secure boolean informs
  684. * the cookie if a secure connection is achieved or not.
  685. *
  686. * It shall only return cookies that haven't expired.
  687. *
  688. ****************************************************************************/
  689. struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
  690. const char *host, const char *path,
  691. bool secure)
  692. {
  693. struct Cookie *newco;
  694. struct Cookie *co;
  695. time_t now = time(NULL);
  696. struct Cookie *mainco=NULL;
  697. size_t matches = 0;
  698. if(!c || !c->cookies)
  699. return NULL; /* no cookie struct or no cookies in the struct */
  700. co = c->cookies;
  701. while(co) {
  702. /* only process this cookie if it is not expired or had no expire
  703. date AND that if the cookie requires we're secure we must only
  704. continue if we are! */
  705. if( (!co->expires || (co->expires > now)) &&
  706. (co->secure?secure:TRUE) ) {
  707. /* now check if the domain is correct */
  708. if(!co->domain ||
  709. (co->tailmatch && tailmatch(co->domain, host)) ||
  710. (!co->tailmatch && Curl_raw_equal(host, co->domain)) ) {
  711. /* the right part of the host matches the domain stuff in the
  712. cookie data */
  713. /* now check the left part of the path with the cookies path
  714. requirement */
  715. if(!co->path ||
  716. /* not using checkprefix() because matching should be
  717. case-sensitive */
  718. !strncmp(co->path, path, strlen(co->path)) ) {
  719. /* and now, we know this is a match and we should create an
  720. entry for the return-linked-list */
  721. newco = malloc(sizeof(struct Cookie));
  722. if(newco) {
  723. /* first, copy the whole source cookie: */
  724. memcpy(newco, co, sizeof(struct Cookie));
  725. /* then modify our next */
  726. newco->next = mainco;
  727. /* point the main to us */
  728. mainco = newco;
  729. matches++;
  730. }
  731. else {
  732. fail:
  733. /* failure, clear up the allocated chain and return NULL */
  734. while(mainco) {
  735. co = mainco->next;
  736. free(mainco);
  737. mainco = co;
  738. }
  739. return NULL;
  740. }
  741. }
  742. }
  743. }
  744. co = co->next;
  745. }
  746. if(matches) {
  747. /* Now we need to make sure that if there is a name appearing more than
  748. once, the longest specified path version comes first. To make this
  749. the swiftest way, we just sort them all based on path length. */
  750. struct Cookie **array;
  751. size_t i;
  752. /* alloc an array and store all cookie pointers */
  753. array = (struct Cookie **)malloc(sizeof(struct Cookie *) * matches);
  754. if(!array)
  755. goto fail;
  756. co = mainco;
  757. for(i=0; co; co = co->next)
  758. array[i++] = co;
  759. /* now sort the cookie pointers in path lenth order */
  760. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  761. /* remake the linked list order according to the new order */
  762. mainco = array[0]; /* start here */
  763. for(i=0; i<matches-1; i++)
  764. array[i]->next = array[i+1];
  765. array[matches-1]->next = NULL; /* terminate the list */
  766. free(array); /* remove the temporary data again */
  767. }
  768. return mainco; /* return the new list */
  769. }
  770. /*****************************************************************************
  771. *
  772. * Curl_cookie_clearall()
  773. *
  774. * Clear all existing cookies and reset the counter.
  775. *
  776. ****************************************************************************/
  777. void Curl_cookie_clearall(struct CookieInfo *cookies)
  778. {
  779. if(cookies) {
  780. Curl_cookie_freelist(cookies->cookies, TRUE);
  781. cookies->cookies = NULL;
  782. cookies->numcookies = 0;
  783. }
  784. }
  785. /*****************************************************************************
  786. *
  787. * Curl_cookie_freelist()
  788. *
  789. * Free a list of cookies previously returned by Curl_cookie_getlist();
  790. *
  791. * The 'cookiestoo' argument tells this function whether to just free the
  792. * list or actually also free all cookies within the list as well.
  793. *
  794. ****************************************************************************/
  795. void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo)
  796. {
  797. struct Cookie *next;
  798. if(co) {
  799. while(co) {
  800. next = co->next;
  801. if(cookiestoo)
  802. freecookie(co);
  803. else
  804. free(co); /* we only free the struct since the "members" are all just
  805. pointed out in the main cookie list! */
  806. co = next;
  807. }
  808. }
  809. }
  810. /*****************************************************************************
  811. *
  812. * Curl_cookie_clearsess()
  813. *
  814. * Free all session cookies in the cookies list.
  815. *
  816. ****************************************************************************/
  817. void Curl_cookie_clearsess(struct CookieInfo *cookies)
  818. {
  819. struct Cookie *first, *curr, *next, *prev = NULL;
  820. if(!cookies || !cookies->cookies)
  821. return;
  822. first = curr = prev = cookies->cookies;
  823. for(; curr; curr = next) {
  824. next = curr->next;
  825. if(!curr->expires) {
  826. if(first == curr)
  827. first = next;
  828. if(prev == curr)
  829. prev = next;
  830. else
  831. prev->next = next;
  832. freecookie(curr);
  833. cookies->numcookies--;
  834. }
  835. else
  836. prev = curr;
  837. }
  838. cookies->cookies = first;
  839. }
  840. /*****************************************************************************
  841. *
  842. * Curl_cookie_cleanup()
  843. *
  844. * Free a "cookie object" previous created with cookie_init().
  845. *
  846. ****************************************************************************/
  847. void Curl_cookie_cleanup(struct CookieInfo *c)
  848. {
  849. struct Cookie *co;
  850. struct Cookie *next;
  851. if(c) {
  852. if(c->filename)
  853. free(c->filename);
  854. co = c->cookies;
  855. while(co) {
  856. next = co->next;
  857. freecookie(co);
  858. co = next;
  859. }
  860. free(c); /* free the base struct as well */
  861. }
  862. }
  863. /* get_netscape_format()
  864. *
  865. * Formats a string for Netscape output file, w/o a newline at the end.
  866. *
  867. * Function returns a char * to a formatted line. Has to be free()d
  868. */
  869. static char *get_netscape_format(const struct Cookie *co)
  870. {
  871. return aprintf(
  872. "%s" /* httponly preamble */
  873. "%s%s\t" /* domain */
  874. "%s\t" /* tailmatch */
  875. "%s\t" /* path */
  876. "%s\t" /* secure */
  877. "%" FORMAT_OFF_T "\t" /* expires */
  878. "%s\t" /* name */
  879. "%s", /* value */
  880. co->httponly?"#HttpOnly_":"",
  881. /* Make sure all domains are prefixed with a dot if they allow
  882. tailmatching. This is Mozilla-style. */
  883. (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
  884. co->domain?co->domain:"unknown",
  885. co->tailmatch?"TRUE":"FALSE",
  886. co->path?co->path:"/",
  887. co->secure?"TRUE":"FALSE",
  888. co->expires,
  889. co->name,
  890. co->value?co->value:"");
  891. }
  892. /*
  893. * Curl_cookie_output()
  894. *
  895. * Writes all internally known cookies to the specified file. Specify
  896. * "-" as file name to write to stdout.
  897. *
  898. * The function returns non-zero on write failure.
  899. */
  900. int Curl_cookie_output(struct CookieInfo *c, const char *dumphere)
  901. {
  902. struct Cookie *co;
  903. FILE *out;
  904. bool use_stdout=FALSE;
  905. if((NULL == c) || (0 == c->numcookies))
  906. /* If there are no known cookies, we don't write or even create any
  907. destination file */
  908. return 0;
  909. if(strequal("-", dumphere)) {
  910. /* use stdout */
  911. out = stdout;
  912. use_stdout=TRUE;
  913. }
  914. else {
  915. out = fopen(dumphere, "w");
  916. if(!out)
  917. return 1; /* failure */
  918. }
  919. if(c) {
  920. char *format_ptr;
  921. fputs("# Netscape HTTP Cookie File\n"
  922. "# http://curl.haxx.se/rfc/cookie_spec.html\n"
  923. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  924. out);
  925. co = c->cookies;
  926. while(co) {
  927. format_ptr = get_netscape_format(co);
  928. if(format_ptr == NULL) {
  929. fprintf(out, "#\n# Fatal libcurl error\n");
  930. if(!use_stdout)
  931. fclose(out);
  932. return 1;
  933. }
  934. fprintf(out, "%s\n", format_ptr);
  935. free(format_ptr);
  936. co=co->next;
  937. }
  938. }
  939. if(!use_stdout)
  940. fclose(out);
  941. return 0;
  942. }
  943. struct curl_slist *Curl_cookie_list(struct SessionHandle *data)
  944. {
  945. struct curl_slist *list = NULL;
  946. struct curl_slist *beg;
  947. struct Cookie *c;
  948. char *line;
  949. if((data->cookies == NULL) ||
  950. (data->cookies->numcookies == 0))
  951. return NULL;
  952. c = data->cookies->cookies;
  953. beg = list;
  954. while(c) {
  955. /* fill the list with _all_ the cookies we know */
  956. line = get_netscape_format(c);
  957. if(line == NULL) {
  958. curl_slist_free_all(beg);
  959. return NULL;
  960. }
  961. list = curl_slist_append(list, line);
  962. free(line);
  963. if(list == NULL) {
  964. curl_slist_free_all(beg);
  965. return NULL;
  966. }
  967. else if(beg == NULL) {
  968. beg = list;
  969. }
  970. c = c->next;
  971. }
  972. return list;
  973. }
  974. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */