cookie.c 49 KB

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