cookie.c 49 KB

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