2
0

cookie.c 48 KB

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