cookie.c 48 KB

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