2
0

cookie.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, 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 https://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 Curl_easy *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 Curl_easy *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 supersedes.
  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. #include "urldata.h"
  66. #include "cookie.h"
  67. #include "psl.h"
  68. #include "strtok.h"
  69. #include "sendf.h"
  70. #include "slist.h"
  71. #include "share.h"
  72. #include "strtoofft.h"
  73. #include "strcase.h"
  74. #include "curl_memrchr.h"
  75. #include "inet_pton.h"
  76. /* The last 3 #include files should be in this order */
  77. #include "curl_printf.h"
  78. #include "curl_memory.h"
  79. #include "memdebug.h"
  80. static void freecookie(struct Cookie *co)
  81. {
  82. free(co->expirestr);
  83. free(co->domain);
  84. free(co->path);
  85. free(co->spath);
  86. free(co->name);
  87. free(co->value);
  88. free(co->maxage);
  89. free(co->version);
  90. free(co);
  91. }
  92. static bool tailmatch(const char *cooke_domain, const char *hostname)
  93. {
  94. size_t cookie_domain_len = strlen(cooke_domain);
  95. size_t hostname_len = strlen(hostname);
  96. if(hostname_len < cookie_domain_len)
  97. return FALSE;
  98. if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len))
  99. return FALSE;
  100. /* A lead char of cookie_domain is not '.'.
  101. RFC6265 4.1.2.3. The Domain Attribute says:
  102. For example, if the value of the Domain attribute is
  103. "example.com", the user agent will include the cookie in the Cookie
  104. header when making HTTP requests to example.com, www.example.com, and
  105. www.corp.example.com.
  106. */
  107. if(hostname_len == cookie_domain_len)
  108. return TRUE;
  109. if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
  110. return TRUE;
  111. return FALSE;
  112. }
  113. /*
  114. * Return true if the given string is an IP(v4|v6) address.
  115. */
  116. static bool isip(const char *domain)
  117. {
  118. struct in_addr addr;
  119. #ifdef ENABLE_IPV6
  120. struct in6_addr addr6;
  121. #endif
  122. if(Curl_inet_pton(AF_INET, domain, &addr)
  123. #ifdef ENABLE_IPV6
  124. || Curl_inet_pton(AF_INET6, domain, &addr6)
  125. #endif
  126. ) {
  127. /* domain name given as IP address */
  128. return TRUE;
  129. }
  130. return FALSE;
  131. }
  132. /*
  133. * matching cookie path and url path
  134. * RFC6265 5.1.4 Paths and Path-Match
  135. */
  136. static bool pathmatch(const char *cookie_path, const char *request_uri)
  137. {
  138. size_t cookie_path_len;
  139. size_t uri_path_len;
  140. char *uri_path = NULL;
  141. char *pos;
  142. bool ret = FALSE;
  143. /* cookie_path must not have last '/' separator. ex: /sample */
  144. cookie_path_len = strlen(cookie_path);
  145. if(1 == cookie_path_len) {
  146. /* cookie_path must be '/' */
  147. return TRUE;
  148. }
  149. uri_path = strdup(request_uri);
  150. if(!uri_path)
  151. return FALSE;
  152. pos = strchr(uri_path, '?');
  153. if(pos)
  154. *pos = 0x0;
  155. /* #-fragments are already cut off! */
  156. if(0 == strlen(uri_path) || uri_path[0] != '/') {
  157. free(uri_path);
  158. uri_path = strdup("/");
  159. if(!uri_path)
  160. return FALSE;
  161. }
  162. /* here, RFC6265 5.1.4 says
  163. 4. Output the characters of the uri-path from the first character up
  164. to, but not including, the right-most %x2F ("/").
  165. but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
  166. without redirect.
  167. Ignore this algorithm because /hoge is uri path for this case
  168. (uri path is not /).
  169. */
  170. uri_path_len = strlen(uri_path);
  171. if(uri_path_len < cookie_path_len) {
  172. ret = FALSE;
  173. goto pathmatched;
  174. }
  175. /* not using checkprefix() because matching should be case-sensitive */
  176. if(strncmp(cookie_path, uri_path, cookie_path_len)) {
  177. ret = FALSE;
  178. goto pathmatched;
  179. }
  180. /* The cookie-path and the uri-path are identical. */
  181. if(cookie_path_len == uri_path_len) {
  182. ret = TRUE;
  183. goto pathmatched;
  184. }
  185. /* here, cookie_path_len < uri_path_len */
  186. if(uri_path[cookie_path_len] == '/') {
  187. ret = TRUE;
  188. goto pathmatched;
  189. }
  190. ret = FALSE;
  191. pathmatched:
  192. free(uri_path);
  193. return ret;
  194. }
  195. /*
  196. * Return the top-level domain, for optimal hashing.
  197. */
  198. static const char *get_top_domain(const char * const domain, size_t *outlen)
  199. {
  200. size_t len;
  201. const char *first = NULL, *last;
  202. if(!domain)
  203. return NULL;
  204. len = strlen(domain);
  205. last = memrchr(domain, '.', len);
  206. if(last) {
  207. first = memrchr(domain, '.', (last - domain));
  208. if(first)
  209. len -= (++first - domain);
  210. }
  211. if(outlen)
  212. *outlen = len;
  213. return first? first: domain;
  214. }
  215. /*
  216. * A case-insensitive hash for the cookie domains.
  217. */
  218. static size_t cookie_hash_domain(const char *domain, const size_t len)
  219. {
  220. const char *end = domain + len;
  221. size_t h = 5381;
  222. while(domain < end) {
  223. h += h << 5;
  224. h ^= Curl_raw_toupper(*domain++);
  225. }
  226. return (h % COOKIE_HASH_SIZE);
  227. }
  228. /*
  229. * Hash this domain.
  230. */
  231. static size_t cookiehash(const char * const domain)
  232. {
  233. const char *top;
  234. size_t len;
  235. if(!domain || isip(domain))
  236. return 0;
  237. top = get_top_domain(domain, &len);
  238. return cookie_hash_domain(top, len);
  239. }
  240. /*
  241. * cookie path sanitize
  242. */
  243. static char *sanitize_cookie_path(const char *cookie_path)
  244. {
  245. size_t len;
  246. char *new_path = strdup(cookie_path);
  247. if(!new_path)
  248. return NULL;
  249. /* some stupid site sends path attribute with '"'. */
  250. len = strlen(new_path);
  251. if(new_path[0] == '\"') {
  252. memmove((void *)new_path, (const void *)(new_path + 1), len);
  253. len--;
  254. }
  255. if(len && (new_path[len - 1] == '\"')) {
  256. new_path[len - 1] = 0x0;
  257. len--;
  258. }
  259. /* RFC6265 5.2.4 The Path Attribute */
  260. if(new_path[0] != '/') {
  261. /* Let cookie-path be the default-path. */
  262. free(new_path);
  263. new_path = strdup("/");
  264. return new_path;
  265. }
  266. /* convert /hoge/ to /hoge */
  267. if(len && new_path[len - 1] == '/') {
  268. new_path[len - 1] = 0x0;
  269. }
  270. return new_path;
  271. }
  272. /*
  273. * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
  274. *
  275. * NOTE: OOM or cookie parsing failures are ignored.
  276. */
  277. void Curl_cookie_loadfiles(struct Curl_easy *data)
  278. {
  279. struct curl_slist *list = data->change.cookielist;
  280. if(list) {
  281. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  282. while(list) {
  283. struct CookieInfo *newcookies = Curl_cookie_init(data,
  284. list->data,
  285. data->cookies,
  286. data->set.cookiesession);
  287. if(!newcookies)
  288. /* Failure may be due to OOM or a bad cookie; both are ignored
  289. * but only the first should be
  290. */
  291. infof(data, "ignoring failed cookie_init for %s\n", list->data);
  292. else
  293. data->cookies = newcookies;
  294. list = list->next;
  295. }
  296. curl_slist_free_all(data->change.cookielist); /* clean up list */
  297. data->change.cookielist = NULL; /* don't do this again! */
  298. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  299. }
  300. }
  301. /*
  302. * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
  303. * that will be freed before the allocated string is stored there.
  304. *
  305. * It is meant to easily replace strdup()
  306. */
  307. static void strstore(char **str, const char *newstr)
  308. {
  309. free(*str);
  310. *str = strdup(newstr);
  311. }
  312. /*
  313. * remove_expired() removes expired cookies.
  314. */
  315. static void remove_expired(struct CookieInfo *cookies)
  316. {
  317. struct Cookie *co, *nx;
  318. curl_off_t now = (curl_off_t)time(NULL);
  319. unsigned int i;
  320. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  321. struct Cookie *pv = NULL;
  322. co = cookies->cookies[i];
  323. while(co) {
  324. nx = co->next;
  325. if(co->expires && co->expires < now) {
  326. if(!pv) {
  327. cookies->cookies[i] = co->next;
  328. }
  329. else {
  330. pv->next = co->next;
  331. }
  332. cookies->numcookies--;
  333. freecookie(co);
  334. }
  335. else {
  336. pv = co;
  337. }
  338. co = nx;
  339. }
  340. }
  341. }
  342. /* Make sure domain contains a dot or is localhost. */
  343. static bool bad_domain(const char *domain)
  344. {
  345. return !strchr(domain, '.') && !strcasecompare(domain, "localhost");
  346. }
  347. /****************************************************************************
  348. *
  349. * Curl_cookie_add()
  350. *
  351. * Add a single cookie line to the cookie keeping object.
  352. *
  353. * Be aware that sometimes we get an IP-only host name, and that might also be
  354. * a numerical IPv6 address.
  355. *
  356. * Returns NULL on out of memory or invalid cookie. This is suboptimal,
  357. * as they should be treated separately.
  358. ***************************************************************************/
  359. struct Cookie *
  360. Curl_cookie_add(struct Curl_easy *data,
  361. /* The 'data' pointer here may be NULL at times, and thus
  362. must only be used very carefully for things that can deal
  363. with data being NULL. Such as infof() and similar */
  364. struct CookieInfo *c,
  365. bool httpheader, /* TRUE if HTTP header-style line */
  366. bool noexpire, /* if TRUE, skip remove_expired() */
  367. char *lineptr, /* first character of the line */
  368. const char *domain, /* default domain */
  369. const char *path, /* full path used when this cookie is set,
  370. used to get default path for the cookie
  371. unless set */
  372. bool secure) /* TRUE if connection is over secure origin */
  373. {
  374. struct Cookie *clist;
  375. struct Cookie *co;
  376. struct Cookie *lastc = NULL;
  377. time_t now = time(NULL);
  378. bool replace_old = FALSE;
  379. bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
  380. size_t myhash;
  381. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  382. (void)data;
  383. #endif
  384. /* First, alloc and init a new struct for it */
  385. co = calloc(1, sizeof(struct Cookie));
  386. if(!co)
  387. return NULL; /* bail out if we're this low on memory */
  388. if(httpheader) {
  389. /* This line was read off a HTTP-header */
  390. char name[MAX_NAME];
  391. char what[MAX_NAME];
  392. const char *ptr;
  393. const char *semiptr;
  394. size_t linelength = strlen(lineptr);
  395. if(linelength > MAX_COOKIE_LINE) {
  396. /* discard overly long lines at once */
  397. free(co);
  398. return NULL;
  399. }
  400. semiptr = strchr(lineptr, ';'); /* first, find a semicolon */
  401. while(*lineptr && ISBLANK(*lineptr))
  402. lineptr++;
  403. ptr = lineptr;
  404. do {
  405. /* we have a <what>=<this> pair or a stand-alone word here */
  406. name[0] = what[0] = 0; /* init the buffers */
  407. if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
  408. MAX_NAME_TXT "[^;\r\n]",
  409. name, what)) {
  410. /* Use strstore() below to properly deal with received cookie
  411. headers that have the same string property set more than once,
  412. and then we use the last one. */
  413. const char *whatptr;
  414. bool done = FALSE;
  415. bool sep;
  416. size_t len = strlen(what);
  417. size_t nlen = strlen(name);
  418. const char *endofn = &ptr[ nlen ];
  419. if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
  420. ((nlen + len) > MAX_NAME)) {
  421. /* too long individual name or contents, or too long combination of
  422. name + contents. Chrome and Firefox support 4095 or 4096 bytes
  423. combo. */
  424. freecookie(co);
  425. infof(data, "oversized cookie dropped, name/val %zu + %zu bytes\n",
  426. nlen, len);
  427. return NULL;
  428. }
  429. /* name ends with a '=' ? */
  430. sep = (*endofn == '=')?TRUE:FALSE;
  431. if(nlen) {
  432. endofn--; /* move to the last character */
  433. if(ISBLANK(*endofn)) {
  434. /* skip trailing spaces in name */
  435. while(*endofn && ISBLANK(*endofn) && nlen) {
  436. endofn--;
  437. nlen--;
  438. }
  439. name[nlen] = 0; /* new end of name */
  440. }
  441. }
  442. /* Strip off trailing whitespace from the 'what' */
  443. while(len && ISBLANK(what[len-1])) {
  444. what[len-1] = 0;
  445. len--;
  446. }
  447. /* Skip leading whitespace from the 'what' */
  448. whatptr = what;
  449. while(*whatptr && ISBLANK(*whatptr))
  450. whatptr++;
  451. /*
  452. * Check if we have a reserved prefix set before anything else, as we
  453. * otherwise have to test for the prefix in both the cookie name and
  454. * "the rest". Prefixes must start with '__' and end with a '-', so
  455. * only test for names where that can possibly be true.
  456. */
  457. if(nlen > 3 && name[0] == '_' && name[1] == '_') {
  458. if(strncasecompare("__Secure-", name, 9))
  459. co->prefix |= COOKIE_PREFIX__SECURE;
  460. else if(strncasecompare("__Host-", name, 7))
  461. co->prefix |= COOKIE_PREFIX__HOST;
  462. }
  463. if(!co->name) {
  464. /* The very first name/value pair is the actual cookie name */
  465. if(!sep) {
  466. /* Bad name/value pair. */
  467. badcookie = TRUE;
  468. break;
  469. }
  470. co->name = strdup(name);
  471. co->value = strdup(whatptr);
  472. done = TRUE;
  473. if(!co->name || !co->value) {
  474. badcookie = TRUE;
  475. break;
  476. }
  477. }
  478. else if(!len) {
  479. /* this was a "<name>=" with no content, and we must allow
  480. 'secure' and 'httponly' specified this weirdly */
  481. done = TRUE;
  482. /*
  483. * secure cookies are only allowed to be set when the connection is
  484. * using a secure protocol, or when the cookie is being set by
  485. * reading from file
  486. */
  487. if(strcasecompare("secure", name)) {
  488. if(secure || !c->running) {
  489. co->secure = TRUE;
  490. }
  491. else {
  492. badcookie = TRUE;
  493. break;
  494. }
  495. }
  496. else if(strcasecompare("httponly", name))
  497. co->httponly = TRUE;
  498. else if(sep)
  499. /* there was a '=' so we're not done parsing this field */
  500. done = FALSE;
  501. }
  502. if(done)
  503. ;
  504. else if(strcasecompare("path", name)) {
  505. strstore(&co->path, whatptr);
  506. if(!co->path) {
  507. badcookie = TRUE; /* out of memory bad */
  508. break;
  509. }
  510. free(co->spath); /* if this is set again */
  511. co->spath = sanitize_cookie_path(co->path);
  512. if(!co->spath) {
  513. badcookie = TRUE; /* out of memory bad */
  514. break;
  515. }
  516. }
  517. else if(strcasecompare("domain", name)) {
  518. bool is_ip;
  519. /* Now, we make sure that our host is within the given domain,
  520. or the given domain is not valid and thus cannot be set. */
  521. if('.' == whatptr[0])
  522. whatptr++; /* ignore preceding dot */
  523. #ifndef USE_LIBPSL
  524. /*
  525. * Without PSL we don't know when the incoming cookie is set on a
  526. * TLD or otherwise "protected" suffix. To reduce risk, we require a
  527. * dot OR the exact host name being "localhost".
  528. */
  529. if(bad_domain(whatptr))
  530. domain = ":";
  531. #endif
  532. is_ip = isip(domain ? domain : whatptr);
  533. if(!domain
  534. || (is_ip && !strcmp(whatptr, domain))
  535. || (!is_ip && tailmatch(whatptr, domain))) {
  536. strstore(&co->domain, whatptr);
  537. if(!co->domain) {
  538. badcookie = TRUE;
  539. break;
  540. }
  541. if(!is_ip)
  542. co->tailmatch = TRUE; /* we always do that if the domain name was
  543. given */
  544. }
  545. else {
  546. /* we did not get a tailmatch and then the attempted set domain
  547. is not a domain to which the current host belongs. Mark as
  548. bad. */
  549. badcookie = TRUE;
  550. infof(data, "skipped cookie with bad tailmatch domain: %s\n",
  551. whatptr);
  552. }
  553. }
  554. else if(strcasecompare("version", name)) {
  555. strstore(&co->version, whatptr);
  556. if(!co->version) {
  557. badcookie = TRUE;
  558. break;
  559. }
  560. }
  561. else if(strcasecompare("max-age", name)) {
  562. /* Defined in RFC2109:
  563. Optional. The Max-Age attribute defines the lifetime of the
  564. cookie, in seconds. The delta-seconds value is a decimal non-
  565. negative integer. After delta-seconds seconds elapse, the
  566. client should discard the cookie. A value of zero means the
  567. cookie should be discarded immediately.
  568. */
  569. strstore(&co->maxage, whatptr);
  570. if(!co->maxage) {
  571. badcookie = TRUE;
  572. break;
  573. }
  574. }
  575. else if(strcasecompare("expires", name)) {
  576. strstore(&co->expirestr, whatptr);
  577. if(!co->expirestr) {
  578. badcookie = TRUE;
  579. break;
  580. }
  581. }
  582. /*
  583. else this is the second (or more) name we don't know
  584. about! */
  585. }
  586. else {
  587. /* this is an "illegal" <what>=<this> pair */
  588. }
  589. if(!semiptr || !*semiptr) {
  590. /* we already know there are no more cookies */
  591. semiptr = NULL;
  592. continue;
  593. }
  594. ptr = semiptr + 1;
  595. while(*ptr && ISBLANK(*ptr))
  596. ptr++;
  597. semiptr = strchr(ptr, ';'); /* now, find the next semicolon */
  598. if(!semiptr && *ptr)
  599. /* There are no more semicolons, but there's a final name=value pair
  600. coming up */
  601. semiptr = strchr(ptr, '\0');
  602. } while(semiptr);
  603. if(co->maxage) {
  604. CURLofft offt;
  605. offt = curlx_strtoofft((*co->maxage == '\"')?
  606. &co->maxage[1]:&co->maxage[0], NULL, 10,
  607. &co->expires);
  608. if(offt == CURL_OFFT_FLOW)
  609. /* overflow, used max value */
  610. co->expires = CURL_OFF_T_MAX;
  611. else if(!offt) {
  612. if(!co->expires)
  613. /* already expired */
  614. co->expires = 1;
  615. else if(CURL_OFF_T_MAX - now < co->expires)
  616. /* would overflow */
  617. co->expires = CURL_OFF_T_MAX;
  618. else
  619. co->expires += now;
  620. }
  621. }
  622. else if(co->expirestr) {
  623. /* Note that if the date couldn't get parsed for whatever reason,
  624. the cookie will be treated as a session cookie */
  625. co->expires = curl_getdate(co->expirestr, NULL);
  626. /* Session cookies have expires set to 0 so if we get that back
  627. from the date parser let's add a second to make it a
  628. non-session cookie */
  629. if(co->expires == 0)
  630. co->expires = 1;
  631. else if(co->expires < 0)
  632. co->expires = 0;
  633. }
  634. if(!badcookie && !co->domain) {
  635. if(domain) {
  636. /* no domain was given in the header line, set the default */
  637. co->domain = strdup(domain);
  638. if(!co->domain)
  639. badcookie = TRUE;
  640. }
  641. }
  642. if(!badcookie && !co->path && path) {
  643. /* No path was given in the header line, set the default.
  644. Note that the passed-in path to this function MAY have a '?' and
  645. following part that MUST not be stored as part of the path. */
  646. char *queryp = strchr(path, '?');
  647. /* queryp is where the interesting part of the path ends, so now we
  648. want to the find the last */
  649. char *endslash;
  650. if(!queryp)
  651. endslash = strrchr(path, '/');
  652. else
  653. endslash = memrchr(path, '/', (queryp - path));
  654. if(endslash) {
  655. size_t pathlen = (endslash-path + 1); /* include end slash */
  656. co->path = malloc(pathlen + 1); /* one extra for the zero byte */
  657. if(co->path) {
  658. memcpy(co->path, path, pathlen);
  659. co->path[pathlen] = 0; /* zero terminate */
  660. co->spath = sanitize_cookie_path(co->path);
  661. if(!co->spath)
  662. badcookie = TRUE; /* out of memory bad */
  663. }
  664. else
  665. badcookie = TRUE;
  666. }
  667. }
  668. if(badcookie || !co->name) {
  669. /* we didn't get a cookie name or a bad one,
  670. this is an illegal line, bail out */
  671. freecookie(co);
  672. return NULL;
  673. }
  674. }
  675. else {
  676. /* This line is NOT a HTTP header style line, we do offer support for
  677. reading the odd netscape cookies-file format here */
  678. char *ptr;
  679. char *firstptr;
  680. char *tok_buf = NULL;
  681. int fields;
  682. /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
  683. marked with httpOnly after the domain name are not accessible
  684. from javascripts, but since curl does not operate at javascript
  685. level, we include them anyway. In Firefox's cookie files, these
  686. lines are preceded with #HttpOnly_ and then everything is
  687. as usual, so we skip 10 characters of the line..
  688. */
  689. if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
  690. lineptr += 10;
  691. co->httponly = TRUE;
  692. }
  693. if(lineptr[0]=='#') {
  694. /* don't even try the comments */
  695. free(co);
  696. return NULL;
  697. }
  698. /* strip off the possible end-of-line characters */
  699. ptr = strchr(lineptr, '\r');
  700. if(ptr)
  701. *ptr = 0; /* clear it */
  702. ptr = strchr(lineptr, '\n');
  703. if(ptr)
  704. *ptr = 0; /* clear it */
  705. firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
  706. /* Now loop through the fields and init the struct we already have
  707. allocated */
  708. for(ptr = firstptr, fields = 0; ptr && !badcookie;
  709. ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
  710. switch(fields) {
  711. case 0:
  712. if(ptr[0]=='.') /* skip preceding dots */
  713. ptr++;
  714. co->domain = strdup(ptr);
  715. if(!co->domain)
  716. badcookie = TRUE;
  717. break;
  718. case 1:
  719. /* This field got its explanation on the 23rd of May 2001 by
  720. Andrés García:
  721. flag: A TRUE/FALSE value indicating if all machines within a given
  722. domain can access the variable. This value is set automatically by
  723. the browser, depending on the value you set for the domain.
  724. As far as I can see, it is set to true when the cookie says
  725. .domain.com and to false when the domain is complete www.domain.com
  726. */
  727. co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
  728. break;
  729. case 2:
  730. /* It turns out, that sometimes the file format allows the path
  731. field to remain not filled in, we try to detect this and work
  732. around it! Andrés García made us aware of this... */
  733. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  734. /* only if the path doesn't look like a boolean option! */
  735. co->path = strdup(ptr);
  736. if(!co->path)
  737. badcookie = TRUE;
  738. else {
  739. co->spath = sanitize_cookie_path(co->path);
  740. if(!co->spath) {
  741. badcookie = TRUE; /* out of memory bad */
  742. }
  743. }
  744. break;
  745. }
  746. /* this doesn't look like a path, make one up! */
  747. co->path = strdup("/");
  748. if(!co->path)
  749. badcookie = TRUE;
  750. co->spath = strdup("/");
  751. if(!co->spath)
  752. badcookie = TRUE;
  753. fields++; /* add a field and fall down to secure */
  754. /* FALLTHROUGH */
  755. case 3:
  756. co->secure = FALSE;
  757. if(strcasecompare(ptr, "TRUE")) {
  758. if(secure || c->running)
  759. co->secure = TRUE;
  760. else
  761. badcookie = TRUE;
  762. }
  763. break;
  764. case 4:
  765. if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
  766. badcookie = TRUE;
  767. break;
  768. case 5:
  769. co->name = strdup(ptr);
  770. if(!co->name)
  771. badcookie = TRUE;
  772. /* For Netscape file format cookies we check prefix on the name */
  773. if(strncasecompare("__Secure-", co->name, 9))
  774. co->prefix |= COOKIE_PREFIX__SECURE;
  775. else if(strncasecompare("__Host-", co->name, 7))
  776. co->prefix |= COOKIE_PREFIX__HOST;
  777. break;
  778. case 6:
  779. co->value = strdup(ptr);
  780. if(!co->value)
  781. badcookie = TRUE;
  782. break;
  783. }
  784. }
  785. if(6 == fields) {
  786. /* we got a cookie with blank contents, fix it */
  787. co->value = strdup("");
  788. if(!co->value)
  789. badcookie = TRUE;
  790. else
  791. fields++;
  792. }
  793. if(!badcookie && (7 != fields))
  794. /* we did not find the sufficient number of fields */
  795. badcookie = TRUE;
  796. if(badcookie) {
  797. freecookie(co);
  798. return NULL;
  799. }
  800. }
  801. if(co->prefix & COOKIE_PREFIX__SECURE) {
  802. /* The __Secure- prefix only requires that the cookie be set secure */
  803. if(!co->secure) {
  804. freecookie(co);
  805. return NULL;
  806. }
  807. }
  808. if(co->prefix & COOKIE_PREFIX__HOST) {
  809. /*
  810. * The __Host- prefix requires the cookie to be secure, have a "/" path
  811. * and not have a domain set.
  812. */
  813. if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
  814. ;
  815. else {
  816. freecookie(co);
  817. return NULL;
  818. }
  819. }
  820. if(!c->running && /* read from a file */
  821. c->newsession && /* clean session cookies */
  822. !co->expires) { /* this is a session cookie since it doesn't expire! */
  823. freecookie(co);
  824. return NULL;
  825. }
  826. co->livecookie = c->running;
  827. co->creationtime = ++c->lastct;
  828. /* now, we have parsed the incoming line, we must now check if this
  829. supersedes an already existing cookie, which it may if the previous have
  830. the same domain and path as this */
  831. /* at first, remove expired cookies */
  832. if(!noexpire)
  833. remove_expired(c);
  834. #ifdef USE_LIBPSL
  835. /* Check if the domain is a Public Suffix and if yes, ignore the cookie. */
  836. if(domain && co->domain && !isip(co->domain)) {
  837. const psl_ctx_t *psl = Curl_psl_use(data);
  838. int acceptable;
  839. if(psl) {
  840. acceptable = psl_is_cookie_domain_acceptable(psl, domain, co->domain);
  841. Curl_psl_release(data);
  842. }
  843. else
  844. acceptable = !bad_domain(domain);
  845. if(!acceptable) {
  846. infof(data, "cookie '%s' dropped, domain '%s' must not "
  847. "set cookies for '%s'\n", co->name, domain, co->domain);
  848. freecookie(co);
  849. return NULL;
  850. }
  851. }
  852. #endif
  853. myhash = cookiehash(co->domain);
  854. clist = c->cookies[myhash];
  855. replace_old = FALSE;
  856. while(clist) {
  857. if(strcasecompare(clist->name, co->name)) {
  858. /* the names are identical */
  859. if(clist->domain && co->domain) {
  860. if(strcasecompare(clist->domain, co->domain) &&
  861. (clist->tailmatch == co->tailmatch))
  862. /* The domains are identical */
  863. replace_old = TRUE;
  864. }
  865. else if(!clist->domain && !co->domain)
  866. replace_old = TRUE;
  867. if(replace_old) {
  868. /* the domains were identical */
  869. if(clist->spath && co->spath) {
  870. if(clist->secure && !co->secure && !secure) {
  871. size_t cllen;
  872. const char *sep;
  873. /*
  874. * A non-secure cookie may not overlay an existing secure cookie.
  875. * For an existing cookie "a" with path "/login", refuse a new
  876. * cookie "a" with for example path "/login/en", while the path
  877. * "/loginhelper" is ok.
  878. */
  879. sep = strchr(clist->spath + 1, '/');
  880. if(sep)
  881. cllen = sep - clist->spath;
  882. else
  883. cllen = strlen(clist->spath);
  884. if(strncasecompare(clist->spath, co->spath, cllen)) {
  885. freecookie(co);
  886. return NULL;
  887. }
  888. }
  889. else if(strcasecompare(clist->spath, co->spath))
  890. replace_old = TRUE;
  891. else
  892. replace_old = FALSE;
  893. }
  894. else if(!clist->spath && !co->spath)
  895. replace_old = TRUE;
  896. else
  897. replace_old = FALSE;
  898. }
  899. if(replace_old && !co->livecookie && clist->livecookie) {
  900. /* Both cookies matched fine, except that the already present
  901. cookie is "live", which means it was set from a header, while
  902. the new one isn't "live" and thus only read from a file. We let
  903. live cookies stay alive */
  904. /* Free the newcomer and get out of here! */
  905. freecookie(co);
  906. return NULL;
  907. }
  908. if(replace_old) {
  909. co->next = clist->next; /* get the next-pointer first */
  910. /* when replacing, creationtime is kept from old */
  911. co->creationtime = clist->creationtime;
  912. /* then free all the old pointers */
  913. free(clist->name);
  914. free(clist->value);
  915. free(clist->domain);
  916. free(clist->path);
  917. free(clist->spath);
  918. free(clist->expirestr);
  919. free(clist->version);
  920. free(clist->maxage);
  921. *clist = *co; /* then store all the new data */
  922. free(co); /* free the newly alloced memory */
  923. co = clist; /* point to the previous struct instead */
  924. /* We have replaced a cookie, now skip the rest of the list but
  925. make sure the 'lastc' pointer is properly set */
  926. do {
  927. lastc = clist;
  928. clist = clist->next;
  929. } while(clist);
  930. break;
  931. }
  932. }
  933. lastc = clist;
  934. clist = clist->next;
  935. }
  936. if(c->running)
  937. /* Only show this when NOT reading the cookies from a file */
  938. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  939. "expire %" CURL_FORMAT_CURL_OFF_T "\n",
  940. replace_old?"Replaced":"Added", co->name, co->value,
  941. co->domain, co->path, co->expires);
  942. if(!replace_old) {
  943. /* then make the last item point on this new one */
  944. if(lastc)
  945. lastc->next = co;
  946. else
  947. c->cookies[myhash] = co;
  948. c->numcookies++; /* one more cookie in the jar */
  949. }
  950. return co;
  951. }
  952. /*
  953. * get_line() makes sure to only return complete whole lines that fit in 'len'
  954. * bytes and end with a newline.
  955. */
  956. char *Curl_get_line(char *buf, int len, FILE *input)
  957. {
  958. bool partial = FALSE;
  959. while(1) {
  960. char *b = fgets(buf, len, input);
  961. if(b) {
  962. size_t rlen = strlen(b);
  963. if(rlen && (b[rlen-1] == '\n')) {
  964. if(partial) {
  965. partial = FALSE;
  966. continue;
  967. }
  968. return b;
  969. }
  970. /* read a partial, discard the next piece that ends with newline */
  971. partial = TRUE;
  972. }
  973. else
  974. break;
  975. }
  976. return NULL;
  977. }
  978. /*****************************************************************************
  979. *
  980. * Curl_cookie_init()
  981. *
  982. * Inits a cookie struct to read data from a local file. This is always
  983. * called before any cookies are set. File may be NULL.
  984. *
  985. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  986. *
  987. * Returns NULL on out of memory. Invalid cookies are ignored.
  988. ****************************************************************************/
  989. struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
  990. const char *file,
  991. struct CookieInfo *inc,
  992. bool newsession)
  993. {
  994. struct CookieInfo *c;
  995. FILE *fp = NULL;
  996. bool fromfile = TRUE;
  997. char *line = NULL;
  998. if(NULL == inc) {
  999. /* we didn't get a struct, create one */
  1000. c = calloc(1, sizeof(struct CookieInfo));
  1001. if(!c)
  1002. return NULL; /* failed to get memory */
  1003. c->filename = strdup(file?file:"none"); /* copy the name just in case */
  1004. if(!c->filename)
  1005. goto fail; /* failed to get memory */
  1006. }
  1007. else {
  1008. /* we got an already existing one, use that */
  1009. c = inc;
  1010. }
  1011. c->running = FALSE; /* this is not running, this is init */
  1012. if(file && !strcmp(file, "-")) {
  1013. fp = stdin;
  1014. fromfile = FALSE;
  1015. }
  1016. else if(file && !*file) {
  1017. /* points to a "" string */
  1018. fp = NULL;
  1019. }
  1020. else
  1021. fp = file?fopen(file, FOPEN_READTEXT):NULL;
  1022. c->newsession = newsession; /* new session? */
  1023. if(fp) {
  1024. char *lineptr;
  1025. bool headerline;
  1026. line = malloc(MAX_COOKIE_LINE);
  1027. if(!line)
  1028. goto fail;
  1029. while(Curl_get_line(line, MAX_COOKIE_LINE, fp)) {
  1030. if(checkprefix("Set-Cookie:", line)) {
  1031. /* This is a cookie line, get it! */
  1032. lineptr = &line[11];
  1033. headerline = TRUE;
  1034. }
  1035. else {
  1036. lineptr = line;
  1037. headerline = FALSE;
  1038. }
  1039. while(*lineptr && ISBLANK(*lineptr))
  1040. lineptr++;
  1041. Curl_cookie_add(data, c, headerline, TRUE, lineptr, NULL, NULL, TRUE);
  1042. }
  1043. free(line); /* free the line buffer */
  1044. remove_expired(c); /* run this once, not on every cookie */
  1045. if(fromfile)
  1046. fclose(fp);
  1047. }
  1048. c->running = TRUE; /* now, we're running */
  1049. return c;
  1050. fail:
  1051. free(line);
  1052. if(!inc)
  1053. /* Only clean up if we allocated it here, as the original could still be in
  1054. * use by a share handle */
  1055. Curl_cookie_cleanup(c);
  1056. if(fromfile && fp)
  1057. fclose(fp);
  1058. return NULL; /* out of memory */
  1059. }
  1060. /* sort this so that the longest path gets before the shorter path */
  1061. static int cookie_sort(const void *p1, const void *p2)
  1062. {
  1063. struct Cookie *c1 = *(struct Cookie **)p1;
  1064. struct Cookie *c2 = *(struct Cookie **)p2;
  1065. size_t l1, l2;
  1066. /* 1 - compare cookie path lengths */
  1067. l1 = c1->path ? strlen(c1->path) : 0;
  1068. l2 = c2->path ? strlen(c2->path) : 0;
  1069. if(l1 != l2)
  1070. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1071. /* 2 - compare cookie domain lengths */
  1072. l1 = c1->domain ? strlen(c1->domain) : 0;
  1073. l2 = c2->domain ? strlen(c2->domain) : 0;
  1074. if(l1 != l2)
  1075. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1076. /* 3 - compare cookie name lengths */
  1077. l1 = c1->name ? strlen(c1->name) : 0;
  1078. l2 = c2->name ? strlen(c2->name) : 0;
  1079. if(l1 != l2)
  1080. return (l2 > l1) ? 1 : -1;
  1081. /* 4 - compare cookie creation time */
  1082. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1083. }
  1084. /* sort cookies only according to creation time */
  1085. static int cookie_sort_ct(const void *p1, const void *p2)
  1086. {
  1087. struct Cookie *c1 = *(struct Cookie **)p1;
  1088. struct Cookie *c2 = *(struct Cookie **)p2;
  1089. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1090. }
  1091. #define CLONE(field) \
  1092. do { \
  1093. if(src->field) { \
  1094. d->field = strdup(src->field); \
  1095. if(!d->field) \
  1096. goto fail; \
  1097. } \
  1098. } while(0)
  1099. static struct Cookie *dup_cookie(struct Cookie *src)
  1100. {
  1101. struct Cookie *d = calloc(sizeof(struct Cookie), 1);
  1102. if(d) {
  1103. CLONE(expirestr);
  1104. CLONE(domain);
  1105. CLONE(path);
  1106. CLONE(spath);
  1107. CLONE(name);
  1108. CLONE(value);
  1109. CLONE(maxage);
  1110. CLONE(version);
  1111. d->expires = src->expires;
  1112. d->tailmatch = src->tailmatch;
  1113. d->secure = src->secure;
  1114. d->livecookie = src->livecookie;
  1115. d->httponly = src->httponly;
  1116. d->creationtime = src->creationtime;
  1117. }
  1118. return d;
  1119. fail:
  1120. freecookie(d);
  1121. return NULL;
  1122. }
  1123. /*****************************************************************************
  1124. *
  1125. * Curl_cookie_getlist()
  1126. *
  1127. * For a given host and path, return a linked list of cookies that the
  1128. * client should send to the server if used now. The secure boolean informs
  1129. * the cookie if a secure connection is achieved or not.
  1130. *
  1131. * It shall only return cookies that haven't expired.
  1132. *
  1133. ****************************************************************************/
  1134. struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
  1135. const char *host, const char *path,
  1136. bool secure)
  1137. {
  1138. struct Cookie *newco;
  1139. struct Cookie *co;
  1140. struct Cookie *mainco = NULL;
  1141. size_t matches = 0;
  1142. bool is_ip;
  1143. const size_t myhash = cookiehash(host);
  1144. if(!c || !c->cookies[myhash])
  1145. return NULL; /* no cookie struct or no cookies in the struct */
  1146. /* at first, remove expired cookies */
  1147. remove_expired(c);
  1148. /* check if host is an IP(v4|v6) address */
  1149. is_ip = isip(host);
  1150. co = c->cookies[myhash];
  1151. while(co) {
  1152. /* if the cookie requires we're secure we must only continue if we are! */
  1153. if(co->secure?secure:TRUE) {
  1154. /* now check if the domain is correct */
  1155. if(!co->domain ||
  1156. (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
  1157. ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
  1158. /* the right part of the host matches the domain stuff in the
  1159. cookie data */
  1160. /* now check the left part of the path with the cookies path
  1161. requirement */
  1162. if(!co->spath || pathmatch(co->spath, path) ) {
  1163. /* and now, we know this is a match and we should create an
  1164. entry for the return-linked-list */
  1165. newco = dup_cookie(co);
  1166. if(newco) {
  1167. /* then modify our next */
  1168. newco->next = mainco;
  1169. /* point the main to us */
  1170. mainco = newco;
  1171. matches++;
  1172. }
  1173. else
  1174. goto fail;
  1175. }
  1176. }
  1177. }
  1178. co = co->next;
  1179. }
  1180. if(matches) {
  1181. /* Now we need to make sure that if there is a name appearing more than
  1182. once, the longest specified path version comes first. To make this
  1183. the swiftest way, we just sort them all based on path length. */
  1184. struct Cookie **array;
  1185. size_t i;
  1186. /* alloc an array and store all cookie pointers */
  1187. array = malloc(sizeof(struct Cookie *) * matches);
  1188. if(!array)
  1189. goto fail;
  1190. co = mainco;
  1191. for(i = 0; co; co = co->next)
  1192. array[i++] = co;
  1193. /* now sort the cookie pointers in path length order */
  1194. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  1195. /* remake the linked list order according to the new order */
  1196. mainco = array[0]; /* start here */
  1197. for(i = 0; i<matches-1; i++)
  1198. array[i]->next = array[i + 1];
  1199. array[matches-1]->next = NULL; /* terminate the list */
  1200. free(array); /* remove the temporary data again */
  1201. }
  1202. return mainco; /* return the new list */
  1203. fail:
  1204. /* failure, clear up the allocated chain and return NULL */
  1205. Curl_cookie_freelist(mainco);
  1206. return NULL;
  1207. }
  1208. /*****************************************************************************
  1209. *
  1210. * Curl_cookie_clearall()
  1211. *
  1212. * Clear all existing cookies and reset the counter.
  1213. *
  1214. ****************************************************************************/
  1215. void Curl_cookie_clearall(struct CookieInfo *cookies)
  1216. {
  1217. if(cookies) {
  1218. unsigned int i;
  1219. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1220. Curl_cookie_freelist(cookies->cookies[i]);
  1221. cookies->cookies[i] = NULL;
  1222. }
  1223. cookies->numcookies = 0;
  1224. }
  1225. }
  1226. /*****************************************************************************
  1227. *
  1228. * Curl_cookie_freelist()
  1229. *
  1230. * Free a list of cookies previously returned by Curl_cookie_getlist();
  1231. *
  1232. ****************************************************************************/
  1233. void Curl_cookie_freelist(struct Cookie *co)
  1234. {
  1235. struct Cookie *next;
  1236. while(co) {
  1237. next = co->next;
  1238. freecookie(co);
  1239. co = next;
  1240. }
  1241. }
  1242. /*****************************************************************************
  1243. *
  1244. * Curl_cookie_clearsess()
  1245. *
  1246. * Free all session cookies in the cookies list.
  1247. *
  1248. ****************************************************************************/
  1249. void Curl_cookie_clearsess(struct CookieInfo *cookies)
  1250. {
  1251. struct Cookie *first, *curr, *next, *prev = NULL;
  1252. unsigned int i;
  1253. if(!cookies)
  1254. return;
  1255. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1256. if(!cookies->cookies[i])
  1257. continue;
  1258. first = curr = prev = cookies->cookies[i];
  1259. for(; curr; curr = next) {
  1260. next = curr->next;
  1261. if(!curr->expires) {
  1262. if(first == curr)
  1263. first = next;
  1264. if(prev == curr)
  1265. prev = next;
  1266. else
  1267. prev->next = next;
  1268. freecookie(curr);
  1269. cookies->numcookies--;
  1270. }
  1271. else
  1272. prev = curr;
  1273. }
  1274. cookies->cookies[i] = first;
  1275. }
  1276. }
  1277. /*****************************************************************************
  1278. *
  1279. * Curl_cookie_cleanup()
  1280. *
  1281. * Free a "cookie object" previous created with Curl_cookie_init().
  1282. *
  1283. ****************************************************************************/
  1284. void Curl_cookie_cleanup(struct CookieInfo *c)
  1285. {
  1286. if(c) {
  1287. unsigned int i;
  1288. free(c->filename);
  1289. for(i = 0; i < COOKIE_HASH_SIZE; i++)
  1290. Curl_cookie_freelist(c->cookies[i]);
  1291. free(c); /* free the base struct as well */
  1292. }
  1293. }
  1294. /* get_netscape_format()
  1295. *
  1296. * Formats a string for Netscape output file, w/o a newline at the end.
  1297. *
  1298. * Function returns a char * to a formatted line. Has to be free()d
  1299. */
  1300. static char *get_netscape_format(const struct Cookie *co)
  1301. {
  1302. return aprintf(
  1303. "%s" /* httponly preamble */
  1304. "%s%s\t" /* domain */
  1305. "%s\t" /* tailmatch */
  1306. "%s\t" /* path */
  1307. "%s\t" /* secure */
  1308. "%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
  1309. "%s\t" /* name */
  1310. "%s", /* value */
  1311. co->httponly?"#HttpOnly_":"",
  1312. /* Make sure all domains are prefixed with a dot if they allow
  1313. tailmatching. This is Mozilla-style. */
  1314. (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
  1315. co->domain?co->domain:"unknown",
  1316. co->tailmatch?"TRUE":"FALSE",
  1317. co->path?co->path:"/",
  1318. co->secure?"TRUE":"FALSE",
  1319. co->expires,
  1320. co->name,
  1321. co->value?co->value:"");
  1322. }
  1323. /*
  1324. * cookie_output()
  1325. *
  1326. * Writes all internally known cookies to the specified file. Specify
  1327. * "-" as file name to write to stdout.
  1328. *
  1329. * The function returns non-zero on write failure.
  1330. */
  1331. static int cookie_output(struct CookieInfo *c, const char *dumphere)
  1332. {
  1333. struct Cookie *co;
  1334. FILE *out;
  1335. bool use_stdout = FALSE;
  1336. char *format_ptr;
  1337. unsigned int i;
  1338. unsigned int j;
  1339. struct Cookie **array;
  1340. if(!c)
  1341. /* no cookie engine alive */
  1342. return 0;
  1343. /* at first, remove expired cookies */
  1344. remove_expired(c);
  1345. if(!strcmp("-", dumphere)) {
  1346. /* use stdout */
  1347. out = stdout;
  1348. use_stdout = TRUE;
  1349. }
  1350. else {
  1351. out = fopen(dumphere, FOPEN_WRITETEXT);
  1352. if(!out) {
  1353. return 1; /* failure */
  1354. }
  1355. }
  1356. fputs("# Netscape HTTP Cookie File\n"
  1357. "# https://curl.haxx.se/docs/http-cookies.html\n"
  1358. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  1359. out);
  1360. if(c->numcookies) {
  1361. array = malloc(sizeof(struct Cookie *) * c->numcookies);
  1362. if(!array) {
  1363. if(!use_stdout)
  1364. fclose(out);
  1365. return 1;
  1366. }
  1367. j = 0;
  1368. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1369. for(co = c->cookies[i]; co; co = co->next) {
  1370. if(!co->domain)
  1371. continue;
  1372. array[j++] = co;
  1373. }
  1374. }
  1375. qsort(array, c->numcookies, sizeof(struct Cookie *), cookie_sort_ct);
  1376. for(i = 0; i < j; i++) {
  1377. format_ptr = get_netscape_format(array[i]);
  1378. if(format_ptr == NULL) {
  1379. fprintf(out, "#\n# Fatal libcurl error\n");
  1380. free(array);
  1381. if(!use_stdout)
  1382. fclose(out);
  1383. return 1;
  1384. }
  1385. fprintf(out, "%s\n", format_ptr);
  1386. free(format_ptr);
  1387. }
  1388. free(array);
  1389. }
  1390. if(!use_stdout)
  1391. fclose(out);
  1392. return 0;
  1393. }
  1394. static struct curl_slist *cookie_list(struct Curl_easy *data)
  1395. {
  1396. struct curl_slist *list = NULL;
  1397. struct curl_slist *beg;
  1398. struct Cookie *c;
  1399. char *line;
  1400. unsigned int i;
  1401. if((data->cookies == NULL) ||
  1402. (data->cookies->numcookies == 0))
  1403. return NULL;
  1404. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1405. for(c = data->cookies->cookies[i]; c; c = c->next) {
  1406. if(!c->domain)
  1407. continue;
  1408. line = get_netscape_format(c);
  1409. if(!line) {
  1410. curl_slist_free_all(list);
  1411. return NULL;
  1412. }
  1413. beg = Curl_slist_append_nodup(list, line);
  1414. if(!beg) {
  1415. free(line);
  1416. curl_slist_free_all(list);
  1417. return NULL;
  1418. }
  1419. list = beg;
  1420. }
  1421. }
  1422. return list;
  1423. }
  1424. struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
  1425. {
  1426. struct curl_slist *list;
  1427. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1428. list = cookie_list(data);
  1429. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1430. return list;
  1431. }
  1432. void Curl_flush_cookies(struct Curl_easy *data, int cleanup)
  1433. {
  1434. if(data->set.str[STRING_COOKIEJAR]) {
  1435. if(data->change.cookielist) {
  1436. /* If there is a list of cookie files to read, do it first so that
  1437. we have all the told files read before we write the new jar.
  1438. Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
  1439. Curl_cookie_loadfiles(data);
  1440. }
  1441. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1442. /* if we have a destination file for all the cookies to get dumped to */
  1443. if(cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
  1444. infof(data, "WARNING: failed to save cookies in %s\n",
  1445. data->set.str[STRING_COOKIEJAR]);
  1446. }
  1447. else {
  1448. if(cleanup && data->change.cookielist) {
  1449. /* since nothing is written, we can just free the list of cookie file
  1450. names */
  1451. curl_slist_free_all(data->change.cookielist); /* clean up list */
  1452. data->change.cookielist = NULL;
  1453. }
  1454. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1455. }
  1456. if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
  1457. Curl_cookie_cleanup(data->cookies);
  1458. }
  1459. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1460. }
  1461. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */