cookie.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, 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 *Curl_cookie_init(struct SessionHandle *data,
  26. const char *file, struct CookieInfo *inc, bool newsession);
  27. Inits a cookie struct to store data in a local file. This is always
  28. called before any cookies are set.
  29. struct Cookie *Curl_cookie_add(struct SessionHandle *data,
  30. struct CookieInfo *c, bool httpheader, char *lineptr,
  31. const char *domain, const char *path);
  32. The 'lineptr' parameter is a full "Set-cookie:" line as
  33. received from a server.
  34. The function need to replace previously stored lines that this new
  35. line superceeds.
  36. It may remove lines that are expired.
  37. It should return an indication of success/error.
  38. SENDING COOKIE INFORMATION
  39. ==========================
  40. struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie,
  41. char *host, char *path, bool secure);
  42. For a given host and path, return a linked list of cookies that
  43. the client should send to the server if used now. The secure
  44. boolean informs the cookie if a secure connection is achieved or
  45. not.
  46. It shall only return cookies that haven't expired.
  47. Example set of cookies:
  48. Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
  49. Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  50. domain=.fidelity.com; path=/ftgw; secure
  51. Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  52. domain=.fidelity.com; path=/; secure
  53. Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  54. domain=.fidelity.com; path=/; secure
  55. Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  56. domain=.fidelity.com; path=/; secure
  57. Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
  58. domain=.fidelity.com; path=/; secure
  59. Set-cookie:
  60. Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
  61. 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
  62. ****/
  63. #include "curl_setup.h"
  64. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  65. #define _MPRINTF_REPLACE
  66. #include <curl/mprintf.h>
  67. #include "urldata.h"
  68. #include "cookie.h"
  69. #include "strequal.h"
  70. #include "strtok.h"
  71. #include "sendf.h"
  72. #include "slist.h"
  73. #include "curl_memory.h"
  74. #include "share.h"
  75. #include "strtoofft.h"
  76. #include "rawstr.h"
  77. #include "curl_memrchr.h"
  78. #include "inet_pton.h"
  79. /* The last #include file should be: */
  80. #include "memdebug.h"
  81. static void freecookie(struct Cookie *co)
  82. {
  83. if(co->expirestr)
  84. free(co->expirestr);
  85. if(co->domain)
  86. free(co->domain);
  87. if(co->path)
  88. free(co->path);
  89. if(co->spath)
  90. free(co->spath);
  91. if(co->name)
  92. free(co->name);
  93. if(co->value)
  94. free(co->value);
  95. if(co->maxage)
  96. free(co->maxage);
  97. if(co->version)
  98. free(co->version);
  99. free(co);
  100. }
  101. static bool tailmatch(const char *cooke_domain, const char *hostname)
  102. {
  103. size_t cookie_domain_len = strlen(cooke_domain);
  104. size_t hostname_len = strlen(hostname);
  105. if(hostname_len < cookie_domain_len)
  106. return FALSE;
  107. if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len))
  108. return FALSE;
  109. /* A lead char of cookie_domain is not '.'.
  110. RFC6265 4.1.2.3. The Domain Attribute says:
  111. For example, if the value of the Domain attribute is
  112. "example.com", the user agent will include the cookie in the Cookie
  113. header when making HTTP requests to example.com, www.example.com, and
  114. www.corp.example.com.
  115. */
  116. if(hostname_len == cookie_domain_len)
  117. return TRUE;
  118. if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
  119. return TRUE;
  120. return FALSE;
  121. }
  122. /*
  123. * matching cookie path and url path
  124. * RFC6265 5.1.4 Paths and Path-Match
  125. */
  126. static bool pathmatch(const char* cookie_path, const char* request_uri)
  127. {
  128. size_t cookie_path_len;
  129. size_t uri_path_len;
  130. char* uri_path = NULL;
  131. char* pos;
  132. bool ret = FALSE;
  133. /* cookie_path must not have last '/' separator. ex: /sample */
  134. cookie_path_len = strlen(cookie_path);
  135. if(1 == cookie_path_len) {
  136. /* cookie_path must be '/' */
  137. return TRUE;
  138. }
  139. uri_path = strdup(request_uri);
  140. if(!uri_path)
  141. return FALSE;
  142. pos = strchr(uri_path, '?');
  143. if(pos)
  144. *pos = 0x0;
  145. /* #-fragments are already cut off! */
  146. if(0 == strlen(uri_path) || uri_path[0] != '/') {
  147. free(uri_path);
  148. uri_path = strdup("/");
  149. if(!uri_path)
  150. return FALSE;
  151. }
  152. /* here, RFC6265 5.1.4 says
  153. 4. Output the characters of the uri-path from the first character up
  154. to, but not including, the right-most %x2F ("/").
  155. but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
  156. without redirect.
  157. Ignore this algorithm because /hoge is uri path for this case
  158. (uri path is not /).
  159. */
  160. uri_path_len = strlen(uri_path);
  161. if(uri_path_len < cookie_path_len) {
  162. ret = FALSE;
  163. goto pathmatched;
  164. }
  165. /* not using checkprefix() because matching should be case-sensitive */
  166. if(strncmp(cookie_path, uri_path, cookie_path_len)) {
  167. ret = FALSE;
  168. goto pathmatched;
  169. }
  170. /* The cookie-path and the uri-path are identical. */
  171. if(cookie_path_len == uri_path_len) {
  172. ret = TRUE;
  173. goto pathmatched;
  174. }
  175. /* here, cookie_path_len < url_path_len */
  176. if(uri_path[cookie_path_len] == '/') {
  177. ret = TRUE;
  178. goto pathmatched;
  179. }
  180. ret = FALSE;
  181. pathmatched:
  182. free(uri_path);
  183. return ret;
  184. }
  185. /*
  186. * cookie path sanitize
  187. */
  188. static char *sanitize_cookie_path(const char *cookie_path)
  189. {
  190. size_t len;
  191. char *new_path = strdup(cookie_path);
  192. if(!new_path)
  193. return NULL;
  194. /* some stupid site sends path attribute with '"'. */
  195. if(new_path[0] == '\"') {
  196. memmove((void *)new_path, (const void *)(new_path + 1), strlen(new_path));
  197. }
  198. if(new_path[strlen(new_path) - 1] == '\"') {
  199. new_path[strlen(new_path) - 1] = 0x0;
  200. }
  201. /* RFC6265 5.2.4 The Path Attribute */
  202. if(new_path[0] != '/') {
  203. /* Let cookie-path be the default-path. */
  204. free(new_path);
  205. new_path = strdup("/");
  206. return new_path;
  207. }
  208. /* convert /hoge/ to /hoge */
  209. len = strlen(new_path);
  210. if(1 < len && new_path[len - 1] == '/') {
  211. new_path[len - 1] = 0x0;
  212. }
  213. return new_path;
  214. }
  215. /*
  216. * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
  217. *
  218. * NOTE: OOM or cookie parsing failures are ignored.
  219. */
  220. void Curl_cookie_loadfiles(struct SessionHandle *data)
  221. {
  222. struct curl_slist *list = data->change.cookielist;
  223. if(list) {
  224. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  225. while(list) {
  226. struct CookieInfo *newcookies = Curl_cookie_init(data,
  227. list->data,
  228. data->cookies,
  229. data->set.cookiesession);
  230. if(!newcookies)
  231. /* Failure may be due to OOM or a bad cookie; both are ignored
  232. * but only the first should be
  233. */
  234. infof(data, "ignoring failed cookie_init for %s\n", list->data);
  235. else
  236. data->cookies = newcookies;
  237. list = list->next;
  238. }
  239. curl_slist_free_all(data->change.cookielist); /* clean up list */
  240. data->change.cookielist = NULL; /* don't do this again! */
  241. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  242. }
  243. }
  244. /*
  245. * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
  246. * that will be freed before the allocated string is stored there.
  247. *
  248. * It is meant to easily replace strdup()
  249. */
  250. static void strstore(char **str, const char *newstr)
  251. {
  252. if(*str)
  253. free(*str);
  254. *str = strdup(newstr);
  255. }
  256. /*
  257. * remove_expired() removes expired cookies.
  258. */
  259. static void remove_expired(struct CookieInfo *cookies)
  260. {
  261. struct Cookie *co, *nx, *pv;
  262. curl_off_t now = (curl_off_t)time(NULL);
  263. co = cookies->cookies;
  264. pv = NULL;
  265. while(co) {
  266. nx = co->next;
  267. if((co->expirestr || co->maxage) && co->expires < now) {
  268. if(co == cookies->cookies) {
  269. cookies->cookies = co->next;
  270. }
  271. else {
  272. pv->next = co->next;
  273. }
  274. cookies->numcookies--;
  275. freecookie(co);
  276. }
  277. else {
  278. pv = co;
  279. }
  280. co = nx;
  281. }
  282. }
  283. /*
  284. * Return true if the given string is an IP(v4|v6) address.
  285. */
  286. static bool isip(const char *domain)
  287. {
  288. struct in_addr addr;
  289. #ifdef ENABLE_IPV6
  290. struct in6_addr addr6;
  291. #endif
  292. if(Curl_inet_pton(AF_INET, domain, &addr)
  293. #ifdef ENABLE_IPV6
  294. || Curl_inet_pton(AF_INET6, domain, &addr6)
  295. #endif
  296. ) {
  297. /* domain name given as IP address */
  298. return TRUE;
  299. }
  300. return FALSE;
  301. }
  302. /****************************************************************************
  303. *
  304. * Curl_cookie_add()
  305. *
  306. * Add a single cookie line to the cookie keeping object.
  307. *
  308. * Be aware that sometimes we get an IP-only host name, and that might also be
  309. * a numerical IPv6 address.
  310. *
  311. * Returns NULL on out of memory or invalid cookie. This is suboptimal,
  312. * as they should be treated separately.
  313. ***************************************************************************/
  314. struct Cookie *
  315. Curl_cookie_add(struct SessionHandle *data,
  316. /* The 'data' pointer here may be NULL at times, and thus
  317. must only be used very carefully for things that can deal
  318. with data being NULL. Such as infof() and similar */
  319. struct CookieInfo *c,
  320. bool httpheader, /* TRUE if HTTP header-style line */
  321. char *lineptr, /* first character of the line */
  322. const char *domain, /* default domain */
  323. const char *path) /* full path used when this cookie is set,
  324. used to get default path for the cookie
  325. unless set */
  326. {
  327. struct Cookie *clist;
  328. char name[MAX_NAME];
  329. struct Cookie *co;
  330. struct Cookie *lastc=NULL;
  331. time_t now = time(NULL);
  332. bool replace_old = FALSE;
  333. bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
  334. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  335. (void)data;
  336. #endif
  337. /* First, alloc and init a new struct for it */
  338. co = calloc(1, sizeof(struct Cookie));
  339. if(!co)
  340. return NULL; /* bail out if we're this low on memory */
  341. if(httpheader) {
  342. /* This line was read off a HTTP-header */
  343. const char *ptr;
  344. const char *semiptr;
  345. char *what;
  346. what = malloc(MAX_COOKIE_LINE);
  347. if(!what) {
  348. free(co);
  349. return NULL;
  350. }
  351. semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
  352. while(*lineptr && ISBLANK(*lineptr))
  353. lineptr++;
  354. ptr = lineptr;
  355. do {
  356. /* we have a <what>=<this> pair or a stand-alone word here */
  357. name[0]=what[0]=0; /* init the buffers */
  358. if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n =]=%"
  359. MAX_COOKIE_LINE_TXT "[^;\r\n]",
  360. name, what)) {
  361. /* Use strstore() below to properly deal with received cookie
  362. headers that have the same string property set more than once,
  363. and then we use the last one. */
  364. const char *whatptr;
  365. bool done = FALSE;
  366. bool sep;
  367. size_t len=strlen(what);
  368. const char *endofn = &ptr[ strlen(name) ];
  369. /* skip trailing spaces in name */
  370. while(*endofn && ISBLANK(*endofn))
  371. endofn++;
  372. /* name ends with a '=' ? */
  373. sep = (*endofn == '=')?TRUE:FALSE;
  374. /* Strip off trailing whitespace from the 'what' */
  375. while(len && ISBLANK(what[len-1])) {
  376. what[len-1]=0;
  377. len--;
  378. }
  379. /* Skip leading whitespace from the 'what' */
  380. whatptr=what;
  381. while(*whatptr && ISBLANK(*whatptr))
  382. whatptr++;
  383. if(!len) {
  384. /* this was a "<name>=" with no content, and we must allow
  385. 'secure' and 'httponly' specified this weirdly */
  386. done = TRUE;
  387. if(Curl_raw_equal("secure", name))
  388. co->secure = TRUE;
  389. else if(Curl_raw_equal("httponly", name))
  390. co->httponly = TRUE;
  391. else if(sep)
  392. /* there was a '=' so we're not done parsing this field */
  393. done = FALSE;
  394. }
  395. if(done)
  396. ;
  397. else if(Curl_raw_equal("path", name)) {
  398. strstore(&co->path, whatptr);
  399. if(!co->path) {
  400. badcookie = TRUE; /* out of memory bad */
  401. break;
  402. }
  403. co->spath = sanitize_cookie_path(co->path);
  404. if(!co->spath) {
  405. badcookie = TRUE; /* out of memory bad */
  406. break;
  407. }
  408. }
  409. else if(Curl_raw_equal("domain", name)) {
  410. bool is_ip;
  411. const char *dotp;
  412. /* Now, we make sure that our host is within the given domain,
  413. or the given domain is not valid and thus cannot be set. */
  414. if('.' == whatptr[0])
  415. whatptr++; /* ignore preceding dot */
  416. is_ip = isip(domain ? domain : whatptr);
  417. /* check for more dots */
  418. dotp = strchr(whatptr, '.');
  419. if(!dotp)
  420. domain=":";
  421. if(!domain
  422. || (is_ip && !strcmp(whatptr, domain))
  423. || (!is_ip && tailmatch(whatptr, domain))) {
  424. strstore(&co->domain, whatptr);
  425. if(!co->domain) {
  426. badcookie = TRUE;
  427. break;
  428. }
  429. if(!is_ip)
  430. co->tailmatch=TRUE; /* we always do that if the domain name was
  431. given */
  432. }
  433. else {
  434. /* we did not get a tailmatch and then the attempted set domain
  435. is not a domain to which the current host belongs. Mark as
  436. bad. */
  437. badcookie=TRUE;
  438. infof(data, "skipped cookie with bad tailmatch domain: %s\n",
  439. whatptr);
  440. }
  441. }
  442. else if(Curl_raw_equal("version", name)) {
  443. strstore(&co->version, whatptr);
  444. if(!co->version) {
  445. badcookie = TRUE;
  446. break;
  447. }
  448. }
  449. else if(Curl_raw_equal("max-age", name)) {
  450. /* Defined in RFC2109:
  451. Optional. The Max-Age attribute defines the lifetime of the
  452. cookie, in seconds. The delta-seconds value is a decimal non-
  453. negative integer. After delta-seconds seconds elapse, the
  454. client should discard the cookie. A value of zero means the
  455. cookie should be discarded immediately.
  456. */
  457. strstore(&co->maxage, whatptr);
  458. if(!co->maxage) {
  459. badcookie = TRUE;
  460. break;
  461. }
  462. }
  463. else if(Curl_raw_equal("expires", name)) {
  464. strstore(&co->expirestr, whatptr);
  465. if(!co->expirestr) {
  466. badcookie = TRUE;
  467. break;
  468. }
  469. }
  470. else if(!co->name) {
  471. co->name = strdup(name);
  472. co->value = strdup(whatptr);
  473. if(!co->name || !co->value) {
  474. badcookie = TRUE;
  475. break;
  476. }
  477. }
  478. /*
  479. else this is the second (or more) name we don't know
  480. about! */
  481. }
  482. else {
  483. /* this is an "illegal" <what>=<this> pair */
  484. }
  485. if(!semiptr || !*semiptr) {
  486. /* we already know there are no more cookies */
  487. semiptr = NULL;
  488. continue;
  489. }
  490. ptr=semiptr+1;
  491. while(*ptr && ISBLANK(*ptr))
  492. ptr++;
  493. semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
  494. if(!semiptr && *ptr)
  495. /* There are no more semicolons, but there's a final name=value pair
  496. coming up */
  497. semiptr=strchr(ptr, '\0');
  498. } while(semiptr);
  499. if(co->maxage) {
  500. co->expires =
  501. curlx_strtoofft((*co->maxage=='\"')?
  502. &co->maxage[1]:&co->maxage[0], NULL, 10);
  503. if(CURL_OFF_T_MAX - now < co->expires)
  504. /* avoid overflow */
  505. co->expires = CURL_OFF_T_MAX;
  506. else
  507. co->expires += now;
  508. }
  509. else if(co->expirestr) {
  510. /* Note that if the date couldn't get parsed for whatever reason,
  511. the cookie will be treated as a session cookie */
  512. co->expires = curl_getdate(co->expirestr, NULL);
  513. /* Session cookies have expires set to 0 so if we get that back
  514. from the date parser let's add a second to make it a
  515. non-session cookie */
  516. if(co->expires == 0)
  517. co->expires = 1;
  518. else if(co->expires < 0)
  519. co->expires = 0;
  520. }
  521. if(!badcookie && !co->domain) {
  522. if(domain) {
  523. /* no domain was given in the header line, set the default */
  524. co->domain=strdup(domain);
  525. if(!co->domain)
  526. badcookie = TRUE;
  527. }
  528. }
  529. if(!badcookie && !co->path && path) {
  530. /* No path was given in the header line, set the default.
  531. Note that the passed-in path to this function MAY have a '?' and
  532. following part that MUST not be stored as part of the path. */
  533. char *queryp = strchr(path, '?');
  534. /* queryp is where the interesting part of the path ends, so now we
  535. want to the find the last */
  536. char *endslash;
  537. if(!queryp)
  538. endslash = strrchr(path, '/');
  539. else
  540. endslash = memrchr(path, '/', (size_t)(queryp - path));
  541. if(endslash) {
  542. size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
  543. co->path=malloc(pathlen+1); /* one extra for the zero byte */
  544. if(co->path) {
  545. memcpy(co->path, path, pathlen);
  546. co->path[pathlen]=0; /* zero terminate */
  547. co->spath = sanitize_cookie_path(co->path);
  548. if(!co->spath)
  549. badcookie = TRUE; /* out of memory bad */
  550. }
  551. else
  552. badcookie = TRUE;
  553. }
  554. }
  555. free(what);
  556. if(badcookie || !co->name) {
  557. /* we didn't get a cookie name or a bad one,
  558. this is an illegal line, bail out */
  559. freecookie(co);
  560. return NULL;
  561. }
  562. }
  563. else {
  564. /* This line is NOT a HTTP header style line, we do offer support for
  565. reading the odd netscape cookies-file format here */
  566. char *ptr;
  567. char *firstptr;
  568. char *tok_buf=NULL;
  569. int fields;
  570. /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
  571. marked with httpOnly after the domain name are not accessible
  572. from javascripts, but since curl does not operate at javascript
  573. level, we include them anyway. In Firefox's cookie files, these
  574. lines are preceded with #HttpOnly_ and then everything is
  575. as usual, so we skip 10 characters of the line..
  576. */
  577. if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
  578. lineptr += 10;
  579. co->httponly = TRUE;
  580. }
  581. if(lineptr[0]=='#') {
  582. /* don't even try the comments */
  583. free(co);
  584. return NULL;
  585. }
  586. /* strip off the possible end-of-line characters */
  587. ptr=strchr(lineptr, '\r');
  588. if(ptr)
  589. *ptr=0; /* clear it */
  590. ptr=strchr(lineptr, '\n');
  591. if(ptr)
  592. *ptr=0; /* clear it */
  593. firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
  594. /* Now loop through the fields and init the struct we already have
  595. allocated */
  596. for(ptr=firstptr, fields=0; ptr && !badcookie;
  597. ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
  598. switch(fields) {
  599. case 0:
  600. if(ptr[0]=='.') /* skip preceding dots */
  601. ptr++;
  602. co->domain = strdup(ptr);
  603. if(!co->domain)
  604. badcookie = TRUE;
  605. break;
  606. case 1:
  607. /* This field got its explanation on the 23rd of May 2001 by
  608. Andrés García:
  609. flag: A TRUE/FALSE value indicating if all machines within a given
  610. domain can access the variable. This value is set automatically by
  611. the browser, depending on the value you set for the domain.
  612. As far as I can see, it is set to true when the cookie says
  613. .domain.com and to false when the domain is complete www.domain.com
  614. */
  615. co->tailmatch = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
  616. break;
  617. case 2:
  618. /* It turns out, that sometimes the file format allows the path
  619. field to remain not filled in, we try to detect this and work
  620. around it! Andrés García made us aware of this... */
  621. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  622. /* only if the path doesn't look like a boolean option! */
  623. co->path = strdup(ptr);
  624. if(!co->path)
  625. badcookie = TRUE;
  626. else {
  627. co->spath = sanitize_cookie_path(co->path);
  628. if(!co->spath) {
  629. badcookie = TRUE; /* out of memory bad */
  630. }
  631. }
  632. break;
  633. }
  634. /* this doesn't look like a path, make one up! */
  635. co->path = strdup("/");
  636. if(!co->path)
  637. badcookie = TRUE;
  638. co->spath = strdup("/");
  639. if(!co->spath)
  640. badcookie = TRUE;
  641. fields++; /* add a field and fall down to secure */
  642. /* FALLTHROUGH */
  643. case 3:
  644. co->secure = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
  645. break;
  646. case 4:
  647. co->expires = curlx_strtoofft(ptr, NULL, 10);
  648. break;
  649. case 5:
  650. co->name = strdup(ptr);
  651. if(!co->name)
  652. badcookie = TRUE;
  653. break;
  654. case 6:
  655. co->value = strdup(ptr);
  656. if(!co->value)
  657. badcookie = TRUE;
  658. break;
  659. }
  660. }
  661. if(6 == fields) {
  662. /* we got a cookie with blank contents, fix it */
  663. co->value = strdup("");
  664. if(!co->value)
  665. badcookie = TRUE;
  666. else
  667. fields++;
  668. }
  669. if(!badcookie && (7 != fields))
  670. /* we did not find the sufficient number of fields */
  671. badcookie = TRUE;
  672. if(badcookie) {
  673. freecookie(co);
  674. return NULL;
  675. }
  676. }
  677. if(!c->running && /* read from a file */
  678. c->newsession && /* clean session cookies */
  679. !co->expires) { /* this is a session cookie since it doesn't expire! */
  680. freecookie(co);
  681. return NULL;
  682. }
  683. co->livecookie = c->running;
  684. /* now, we have parsed the incoming line, we must now check if this
  685. superceeds an already existing cookie, which it may if the previous have
  686. the same domain and path as this */
  687. /* at first, remove expired cookies */
  688. remove_expired(c);
  689. clist = c->cookies;
  690. replace_old = FALSE;
  691. while(clist) {
  692. if(Curl_raw_equal(clist->name, co->name)) {
  693. /* the names are identical */
  694. if(clist->domain && co->domain) {
  695. if(Curl_raw_equal(clist->domain, co->domain))
  696. /* The domains are identical */
  697. replace_old=TRUE;
  698. }
  699. else if(!clist->domain && !co->domain)
  700. replace_old = TRUE;
  701. if(replace_old) {
  702. /* the domains were identical */
  703. if(clist->spath && co->spath) {
  704. if(Curl_raw_equal(clist->spath, co->spath)) {
  705. replace_old = TRUE;
  706. }
  707. else
  708. replace_old = FALSE;
  709. }
  710. else if(!clist->spath && !co->spath)
  711. replace_old = TRUE;
  712. else
  713. replace_old = FALSE;
  714. }
  715. if(replace_old && !co->livecookie && clist->livecookie) {
  716. /* Both cookies matched fine, except that the already present
  717. cookie is "live", which means it was set from a header, while
  718. the new one isn't "live" and thus only read from a file. We let
  719. live cookies stay alive */
  720. /* Free the newcomer and get out of here! */
  721. freecookie(co);
  722. return NULL;
  723. }
  724. if(replace_old) {
  725. co->next = clist->next; /* get the next-pointer first */
  726. /* then free all the old pointers */
  727. free(clist->name);
  728. if(clist->value)
  729. free(clist->value);
  730. if(clist->domain)
  731. free(clist->domain);
  732. if(clist->path)
  733. free(clist->path);
  734. if(clist->spath)
  735. free(clist->spath);
  736. if(clist->expirestr)
  737. free(clist->expirestr);
  738. if(clist->version)
  739. free(clist->version);
  740. if(clist->maxage)
  741. free(clist->maxage);
  742. *clist = *co; /* then store all the new data */
  743. free(co); /* free the newly alloced memory */
  744. co = clist; /* point to the previous struct instead */
  745. /* We have replaced a cookie, now skip the rest of the list but
  746. make sure the 'lastc' pointer is properly set */
  747. do {
  748. lastc = clist;
  749. clist = clist->next;
  750. } while(clist);
  751. break;
  752. }
  753. }
  754. lastc = clist;
  755. clist = clist->next;
  756. }
  757. if(c->running)
  758. /* Only show this when NOT reading the cookies from a file */
  759. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  760. "expire %" CURL_FORMAT_CURL_OFF_T "\n",
  761. replace_old?"Replaced":"Added", co->name, co->value,
  762. co->domain, co->path, co->expires);
  763. if(!replace_old) {
  764. /* then make the last item point on this new one */
  765. if(lastc)
  766. lastc->next = co;
  767. else
  768. c->cookies = co;
  769. c->numcookies++; /* one more cookie in the jar */
  770. }
  771. return co;
  772. }
  773. /*****************************************************************************
  774. *
  775. * Curl_cookie_init()
  776. *
  777. * Inits a cookie struct to read data from a local file. This is always
  778. * called before any cookies are set. File may be NULL.
  779. *
  780. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  781. *
  782. * Returns NULL on out of memory. Invalid cookies are ignored.
  783. ****************************************************************************/
  784. struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
  785. const char *file,
  786. struct CookieInfo *inc,
  787. bool newsession)
  788. {
  789. struct CookieInfo *c;
  790. FILE *fp = NULL;
  791. bool fromfile=TRUE;
  792. char *line = NULL;
  793. if(NULL == inc) {
  794. /* we didn't get a struct, create one */
  795. c = calloc(1, sizeof(struct CookieInfo));
  796. if(!c)
  797. return NULL; /* failed to get memory */
  798. c->filename = strdup(file?file:"none"); /* copy the name just in case */
  799. if(!c->filename)
  800. goto fail; /* failed to get memory */
  801. }
  802. else {
  803. /* we got an already existing one, use that */
  804. c = inc;
  805. }
  806. c->running = FALSE; /* this is not running, this is init */
  807. if(file && strequal(file, "-")) {
  808. fp = stdin;
  809. fromfile=FALSE;
  810. }
  811. else if(file && !*file) {
  812. /* points to a "" string */
  813. fp = NULL;
  814. }
  815. else
  816. fp = file?fopen(file, "r"):NULL;
  817. c->newsession = newsession; /* new session? */
  818. if(fp) {
  819. char *lineptr;
  820. bool headerline;
  821. line = malloc(MAX_COOKIE_LINE);
  822. if(!line)
  823. goto fail;
  824. while(fgets(line, MAX_COOKIE_LINE, fp)) {
  825. if(checkprefix("Set-Cookie:", line)) {
  826. /* This is a cookie line, get it! */
  827. lineptr=&line[11];
  828. headerline=TRUE;
  829. }
  830. else {
  831. lineptr=line;
  832. headerline=FALSE;
  833. }
  834. while(*lineptr && ISBLANK(*lineptr))
  835. lineptr++;
  836. Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
  837. }
  838. free(line); /* free the line buffer */
  839. if(fromfile)
  840. fclose(fp);
  841. }
  842. c->running = TRUE; /* now, we're running */
  843. return c;
  844. fail:
  845. Curl_safefree(line);
  846. if(!inc)
  847. /* Only clean up if we allocated it here, as the original could still be in
  848. * use by a share handle */
  849. Curl_cookie_cleanup(c);
  850. if(fromfile && fp)
  851. fclose(fp);
  852. return NULL; /* out of memory */
  853. }
  854. /* sort this so that the longest path gets before the shorter path */
  855. static int cookie_sort(const void *p1, const void *p2)
  856. {
  857. struct Cookie *c1 = *(struct Cookie **)p1;
  858. struct Cookie *c2 = *(struct Cookie **)p2;
  859. size_t l1, l2;
  860. /* 1 - compare cookie path lengths */
  861. l1 = c1->path ? strlen(c1->path) : 0;
  862. l2 = c2->path ? strlen(c2->path) : 0;
  863. if(l1 != l2)
  864. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  865. /* 2 - compare cookie domain lengths */
  866. l1 = c1->domain ? strlen(c1->domain) : 0;
  867. l2 = c2->domain ? strlen(c2->domain) : 0;
  868. if(l1 != l2)
  869. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  870. /* 3 - compare cookie names */
  871. if(c1->name && c2->name)
  872. return strcmp(c1->name, c2->name);
  873. /* sorry, can't be more deterministic */
  874. return 0;
  875. }
  876. /*****************************************************************************
  877. *
  878. * Curl_cookie_getlist()
  879. *
  880. * For a given host and path, return a linked list of cookies that the
  881. * client should send to the server if used now. The secure boolean informs
  882. * the cookie if a secure connection is achieved or not.
  883. *
  884. * It shall only return cookies that haven't expired.
  885. *
  886. ****************************************************************************/
  887. struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
  888. const char *host, const char *path,
  889. bool secure)
  890. {
  891. struct Cookie *newco;
  892. struct Cookie *co;
  893. time_t now = time(NULL);
  894. struct Cookie *mainco=NULL;
  895. size_t matches = 0;
  896. bool is_ip;
  897. if(!c || !c->cookies)
  898. return NULL; /* no cookie struct or no cookies in the struct */
  899. /* at first, remove expired cookies */
  900. remove_expired(c);
  901. /* check if host is an IP(v4|v6) address */
  902. is_ip = isip(host);
  903. co = c->cookies;
  904. while(co) {
  905. /* only process this cookie if it is not expired or had no expire
  906. date AND that if the cookie requires we're secure we must only
  907. continue if we are! */
  908. if((!co->expires || (co->expires > now)) &&
  909. (co->secure?secure:TRUE)) {
  910. /* now check if the domain is correct */
  911. if(!co->domain ||
  912. (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
  913. ((!co->tailmatch || is_ip) && Curl_raw_equal(host, co->domain)) ) {
  914. /* the right part of the host matches the domain stuff in the
  915. cookie data */
  916. /* now check the left part of the path with the cookies path
  917. requirement */
  918. if(!co->spath || pathmatch(co->spath, path) ) {
  919. /* and now, we know this is a match and we should create an
  920. entry for the return-linked-list */
  921. newco = malloc(sizeof(struct Cookie));
  922. if(newco) {
  923. /* first, copy the whole source cookie: */
  924. memcpy(newco, co, sizeof(struct Cookie));
  925. /* then modify our next */
  926. newco->next = mainco;
  927. /* point the main to us */
  928. mainco = newco;
  929. matches++;
  930. }
  931. else {
  932. fail:
  933. /* failure, clear up the allocated chain and return NULL */
  934. while(mainco) {
  935. co = mainco->next;
  936. free(mainco);
  937. mainco = co;
  938. }
  939. return NULL;
  940. }
  941. }
  942. }
  943. }
  944. co = co->next;
  945. }
  946. if(matches) {
  947. /* Now we need to make sure that if there is a name appearing more than
  948. once, the longest specified path version comes first. To make this
  949. the swiftest way, we just sort them all based on path length. */
  950. struct Cookie **array;
  951. size_t i;
  952. /* alloc an array and store all cookie pointers */
  953. array = malloc(sizeof(struct Cookie *) * matches);
  954. if(!array)
  955. goto fail;
  956. co = mainco;
  957. for(i=0; co; co = co->next)
  958. array[i++] = co;
  959. /* now sort the cookie pointers in path length order */
  960. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  961. /* remake the linked list order according to the new order */
  962. mainco = array[0]; /* start here */
  963. for(i=0; i<matches-1; i++)
  964. array[i]->next = array[i+1];
  965. array[matches-1]->next = NULL; /* terminate the list */
  966. free(array); /* remove the temporary data again */
  967. }
  968. return mainco; /* return the new list */
  969. }
  970. /*****************************************************************************
  971. *
  972. * Curl_cookie_clearall()
  973. *
  974. * Clear all existing cookies and reset the counter.
  975. *
  976. ****************************************************************************/
  977. void Curl_cookie_clearall(struct CookieInfo *cookies)
  978. {
  979. if(cookies) {
  980. Curl_cookie_freelist(cookies->cookies, TRUE);
  981. cookies->cookies = NULL;
  982. cookies->numcookies = 0;
  983. }
  984. }
  985. /*****************************************************************************
  986. *
  987. * Curl_cookie_freelist()
  988. *
  989. * Free a list of cookies previously returned by Curl_cookie_getlist();
  990. *
  991. * The 'cookiestoo' argument tells this function whether to just free the
  992. * list or actually also free all cookies within the list as well.
  993. *
  994. ****************************************************************************/
  995. void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo)
  996. {
  997. struct Cookie *next;
  998. while(co) {
  999. next = co->next;
  1000. if(cookiestoo)
  1001. freecookie(co);
  1002. else
  1003. free(co); /* we only free the struct since the "members" are all just
  1004. pointed out in the main cookie list! */
  1005. co = next;
  1006. }
  1007. }
  1008. /*****************************************************************************
  1009. *
  1010. * Curl_cookie_clearsess()
  1011. *
  1012. * Free all session cookies in the cookies list.
  1013. *
  1014. ****************************************************************************/
  1015. void Curl_cookie_clearsess(struct CookieInfo *cookies)
  1016. {
  1017. struct Cookie *first, *curr, *next, *prev = NULL;
  1018. if(!cookies || !cookies->cookies)
  1019. return;
  1020. first = curr = prev = cookies->cookies;
  1021. for(; curr; curr = next) {
  1022. next = curr->next;
  1023. if(!curr->expires) {
  1024. if(first == curr)
  1025. first = next;
  1026. if(prev == curr)
  1027. prev = next;
  1028. else
  1029. prev->next = next;
  1030. freecookie(curr);
  1031. cookies->numcookies--;
  1032. }
  1033. else
  1034. prev = curr;
  1035. }
  1036. cookies->cookies = first;
  1037. }
  1038. /*****************************************************************************
  1039. *
  1040. * Curl_cookie_cleanup()
  1041. *
  1042. * Free a "cookie object" previous created with Curl_cookie_init().
  1043. *
  1044. ****************************************************************************/
  1045. void Curl_cookie_cleanup(struct CookieInfo *c)
  1046. {
  1047. if(c) {
  1048. if(c->filename)
  1049. free(c->filename);
  1050. Curl_cookie_freelist(c->cookies, TRUE);
  1051. free(c); /* free the base struct as well */
  1052. }
  1053. }
  1054. /* get_netscape_format()
  1055. *
  1056. * Formats a string for Netscape output file, w/o a newline at the end.
  1057. *
  1058. * Function returns a char * to a formatted line. Has to be free()d
  1059. */
  1060. static char *get_netscape_format(const struct Cookie *co)
  1061. {
  1062. return aprintf(
  1063. "%s" /* httponly preamble */
  1064. "%s%s\t" /* domain */
  1065. "%s\t" /* tailmatch */
  1066. "%s\t" /* path */
  1067. "%s\t" /* secure */
  1068. "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
  1069. "%s\t" /* name */
  1070. "%s", /* value */
  1071. co->httponly?"#HttpOnly_":"",
  1072. /* Make sure all domains are prefixed with a dot if they allow
  1073. tailmatching. This is Mozilla-style. */
  1074. (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
  1075. co->domain?co->domain:"unknown",
  1076. co->tailmatch?"TRUE":"FALSE",
  1077. co->path?co->path:"/",
  1078. co->secure?"TRUE":"FALSE",
  1079. co->expires,
  1080. co->name,
  1081. co->value?co->value:"");
  1082. }
  1083. /*
  1084. * cookie_output()
  1085. *
  1086. * Writes all internally known cookies to the specified file. Specify
  1087. * "-" as file name to write to stdout.
  1088. *
  1089. * The function returns non-zero on write failure.
  1090. */
  1091. static int cookie_output(struct CookieInfo *c, const char *dumphere)
  1092. {
  1093. struct Cookie *co;
  1094. FILE *out;
  1095. bool use_stdout=FALSE;
  1096. if((NULL == c) || (0 == c->numcookies))
  1097. /* If there are no known cookies, we don't write or even create any
  1098. destination file */
  1099. return 0;
  1100. /* at first, remove expired cookies */
  1101. remove_expired(c);
  1102. if(strequal("-", dumphere)) {
  1103. /* use stdout */
  1104. out = stdout;
  1105. use_stdout=TRUE;
  1106. }
  1107. else {
  1108. out = fopen(dumphere, "w");
  1109. if(!out)
  1110. return 1; /* failure */
  1111. }
  1112. if(c) {
  1113. char *format_ptr;
  1114. fputs("# Netscape HTTP Cookie File\n"
  1115. "# http://curl.haxx.se/docs/http-cookies.html\n"
  1116. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  1117. out);
  1118. co = c->cookies;
  1119. while(co) {
  1120. format_ptr = get_netscape_format(co);
  1121. if(format_ptr == NULL) {
  1122. fprintf(out, "#\n# Fatal libcurl error\n");
  1123. if(!use_stdout)
  1124. fclose(out);
  1125. return 1;
  1126. }
  1127. fprintf(out, "%s\n", format_ptr);
  1128. free(format_ptr);
  1129. co=co->next;
  1130. }
  1131. }
  1132. if(!use_stdout)
  1133. fclose(out);
  1134. return 0;
  1135. }
  1136. struct curl_slist *Curl_cookie_list(struct SessionHandle *data)
  1137. {
  1138. struct curl_slist *list = NULL;
  1139. struct curl_slist *beg;
  1140. struct Cookie *c;
  1141. char *line;
  1142. if((data->cookies == NULL) ||
  1143. (data->cookies->numcookies == 0))
  1144. return NULL;
  1145. c = data->cookies->cookies;
  1146. while(c) {
  1147. /* fill the list with _all_ the cookies we know */
  1148. line = get_netscape_format(c);
  1149. if(!line) {
  1150. curl_slist_free_all(list);
  1151. return NULL;
  1152. }
  1153. beg = Curl_slist_append_nodup(list, line);
  1154. if(!beg) {
  1155. free(line);
  1156. curl_slist_free_all(list);
  1157. return NULL;
  1158. }
  1159. list = beg;
  1160. c = c->next;
  1161. }
  1162. return list;
  1163. }
  1164. void Curl_flush_cookies(struct SessionHandle *data, int cleanup)
  1165. {
  1166. if(data->set.str[STRING_COOKIEJAR]) {
  1167. if(data->change.cookielist) {
  1168. /* If there is a list of cookie files to read, do it first so that
  1169. we have all the told files read before we write the new jar.
  1170. Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
  1171. Curl_cookie_loadfiles(data);
  1172. }
  1173. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1174. /* if we have a destination file for all the cookies to get dumped to */
  1175. if(cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
  1176. infof(data, "WARNING: failed to save cookies in %s\n",
  1177. data->set.str[STRING_COOKIEJAR]);
  1178. }
  1179. else {
  1180. if(cleanup && data->change.cookielist) {
  1181. /* since nothing is written, we can just free the list of cookie file
  1182. names */
  1183. curl_slist_free_all(data->change.cookielist); /* clean up list */
  1184. data->change.cookielist = NULL;
  1185. }
  1186. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1187. }
  1188. if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
  1189. Curl_cookie_cleanup(data->cookies);
  1190. }
  1191. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1192. }
  1193. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */