cookie.c 49 KB

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