2
0

cookie.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  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. static int
  407. parse_cookie_header(struct Curl_easy *data,
  408. struct Cookie *co,
  409. struct CookieInfo *ci,
  410. const char *ptr,
  411. const char *domain, /* default domain */
  412. const char *path, /* full path used when this cookie is
  413. set, used to get default path for
  414. the cookie unless set */
  415. bool secure) /* TRUE if connection is over secure
  416. origin */
  417. {
  418. /* This line was read off an HTTP-header */
  419. time_t now;
  420. size_t linelength = strlen(ptr);
  421. if(linelength > MAX_COOKIE_LINE)
  422. /* discard overly long lines at once */
  423. return CERR_TOO_LONG;
  424. now = time(NULL);
  425. do {
  426. size_t vlen;
  427. size_t nlen;
  428. while(*ptr && ISBLANK(*ptr))
  429. ptr++;
  430. /* we have a <name>=<value> pair or a stand-alone word here */
  431. nlen = strcspn(ptr, ";\t\r\n=");
  432. if(nlen) {
  433. bool done = FALSE;
  434. bool sep = FALSE;
  435. const char *namep = ptr;
  436. const char *valuep;
  437. ptr += nlen;
  438. /* trim trailing spaces and tabs after name */
  439. while(nlen && ISBLANK(namep[nlen - 1]))
  440. nlen--;
  441. if(*ptr == '=') {
  442. vlen = strcspn(++ptr, ";\r\n");
  443. valuep = ptr;
  444. sep = TRUE;
  445. ptr = &valuep[vlen];
  446. /* Strip off trailing whitespace from the value */
  447. while(vlen && ISBLANK(valuep[vlen-1]))
  448. vlen--;
  449. /* Skip leading whitespace from the value */
  450. while(vlen && ISBLANK(*valuep)) {
  451. valuep++;
  452. vlen--;
  453. }
  454. /* Reject cookies with a TAB inside the value */
  455. if(memchr(valuep, '\t', vlen)) {
  456. infof(data, "cookie contains TAB, dropping");
  457. return CERR_TAB;
  458. }
  459. }
  460. else {
  461. valuep = NULL;
  462. vlen = 0;
  463. }
  464. /*
  465. * Check for too long individual name or contents, or too long
  466. * combination of name + contents. Chrome and Firefox support 4095 or
  467. * 4096 bytes combo
  468. */
  469. if(nlen >= (MAX_NAME-1) || vlen >= (MAX_NAME-1) ||
  470. ((nlen + vlen) > MAX_NAME)) {
  471. infof(data, "oversized cookie dropped, name/val %zu + %zu bytes",
  472. nlen, vlen);
  473. return CERR_TOO_BIG;
  474. }
  475. /*
  476. * Check if we have a reserved prefix set before anything else, as we
  477. * otherwise have to test for the prefix in both the cookie name and
  478. * "the rest". Prefixes must start with '__' and end with a '-', so
  479. * only test for names where that can possibly be true.
  480. */
  481. if(nlen >= 7 && namep[0] == '_' && namep[1] == '_') {
  482. if(strncasecompare("__Secure-", namep, 9))
  483. co->prefix_secure = TRUE;
  484. else if(strncasecompare("__Host-", namep, 7))
  485. co->prefix_host = TRUE;
  486. }
  487. /*
  488. * Use strstore() below to properly deal with received cookie
  489. * headers that have the same string property set more than once,
  490. * and then we use the last one.
  491. */
  492. if(!co->name) {
  493. /* The very first name/value pair is the actual cookie name */
  494. if(!sep)
  495. /* Bad name/value pair. */
  496. return CERR_NO_SEP;
  497. strstore(&co->name, namep, nlen);
  498. strstore(&co->value, valuep, vlen);
  499. done = TRUE;
  500. if(!co->name || !co->value)
  501. return CERR_NO_NAME_VALUE;
  502. if(invalid_octets(co->value) || invalid_octets(co->name)) {
  503. infof(data, "invalid octets in name/value, cookie dropped");
  504. return CERR_INVALID_OCTET;
  505. }
  506. }
  507. else if(!vlen) {
  508. /*
  509. * this was a "<name>=" with no content, and we must allow
  510. * 'secure' and 'httponly' specified this weirdly
  511. */
  512. done = TRUE;
  513. /*
  514. * secure cookies are only allowed to be set when the connection is
  515. * using a secure protocol, or when the cookie is being set by
  516. * reading from file
  517. */
  518. if((nlen == 6) && strncasecompare("secure", namep, 6)) {
  519. if(secure || !ci->running) {
  520. co->secure = TRUE;
  521. }
  522. else {
  523. return CERR_BAD_SECURE;
  524. }
  525. }
  526. else if((nlen == 8) && strncasecompare("httponly", namep, 8))
  527. co->httponly = TRUE;
  528. else if(sep)
  529. /* there was a '=' so we are not done parsing this field */
  530. done = FALSE;
  531. }
  532. if(done)
  533. ;
  534. else if((nlen == 4) && strncasecompare("path", namep, 4)) {
  535. strstore(&co->path, valuep, vlen);
  536. if(!co->path)
  537. return CERR_OUT_OF_MEMORY;
  538. free(co->spath); /* if this is set again */
  539. co->spath = sanitize_cookie_path(co->path);
  540. if(!co->spath)
  541. return CERR_OUT_OF_MEMORY;
  542. }
  543. else if((nlen == 6) &&
  544. strncasecompare("domain", namep, 6) && vlen) {
  545. bool is_ip;
  546. /*
  547. * Now, we make sure that our host is within the given domain, or
  548. * the given domain is not valid and thus cannot be set.
  549. */
  550. if('.' == valuep[0]) {
  551. valuep++; /* ignore preceding dot */
  552. vlen--;
  553. }
  554. #ifndef USE_LIBPSL
  555. /*
  556. * Without PSL we do not know when the incoming cookie is set on a
  557. * TLD or otherwise "protected" suffix. To reduce risk, we require a
  558. * dot OR the exact hostname being "localhost".
  559. */
  560. if(bad_domain(valuep, vlen))
  561. domain = ":";
  562. #endif
  563. is_ip = Curl_host_is_ipnum(domain ? domain : valuep);
  564. if(!domain
  565. || (is_ip && !strncmp(valuep, domain, vlen) &&
  566. (vlen == strlen(domain)))
  567. || (!is_ip && cookie_tailmatch(valuep, vlen, domain))) {
  568. strstore(&co->domain, valuep, vlen);
  569. if(!co->domain)
  570. return CERR_OUT_OF_MEMORY;
  571. if(!is_ip)
  572. co->tailmatch = TRUE; /* we always do that if the domain name was
  573. given */
  574. }
  575. else {
  576. /*
  577. * We did not get a tailmatch and then the attempted set domain is
  578. * not a domain to which the current host belongs. Mark as bad.
  579. */
  580. infof(data, "skipped cookie with bad tailmatch domain: %s",
  581. valuep);
  582. return CERR_NO_TAILMATCH;
  583. }
  584. }
  585. else if((nlen == 7) && strncasecompare("version", namep, 7)) {
  586. /* just ignore */
  587. }
  588. else if((nlen == 7) && strncasecompare("max-age", namep, 7)) {
  589. /*
  590. * Defined in RFC2109:
  591. *
  592. * Optional. The Max-Age attribute defines the lifetime of the
  593. * cookie, in seconds. The delta-seconds value is a decimal non-
  594. * negative integer. After delta-seconds seconds elapse, the
  595. * client should discard the cookie. A value of zero means the
  596. * cookie should be discarded immediately.
  597. */
  598. CURLofft offt;
  599. const char *maxage = valuep;
  600. offt = curlx_strtoofft((*maxage == '\"') ?
  601. &maxage[1] : &maxage[0], NULL, 10,
  602. &co->expires);
  603. switch(offt) {
  604. case CURL_OFFT_FLOW:
  605. /* overflow, used max value */
  606. co->expires = CURL_OFF_T_MAX;
  607. break;
  608. case CURL_OFFT_INVAL:
  609. /* negative or otherwise bad, expire */
  610. co->expires = 1;
  611. break;
  612. case CURL_OFFT_OK:
  613. if(!co->expires)
  614. /* already expired */
  615. co->expires = 1;
  616. else if(CURL_OFF_T_MAX - now < co->expires)
  617. /* would overflow */
  618. co->expires = CURL_OFF_T_MAX;
  619. else
  620. co->expires += now;
  621. break;
  622. }
  623. }
  624. else if((nlen == 7) && strncasecompare("expires", namep, 7)) {
  625. if(!co->expires) {
  626. /*
  627. * Let max-age have priority.
  628. *
  629. * If the date cannot get parsed for whatever reason, the cookie
  630. * will be treated as a session cookie
  631. */
  632. co->expires = Curl_getdate_capped(valuep);
  633. /*
  634. * Session cookies have expires set to 0 so if we get that back
  635. * from the date parser let's add a second to make it a
  636. * non-session cookie
  637. */
  638. if(co->expires == 0)
  639. co->expires = 1;
  640. else if(co->expires < 0)
  641. co->expires = 0;
  642. }
  643. }
  644. /*
  645. * Else, this is the second (or more) name we do not know about!
  646. */
  647. }
  648. else {
  649. /* this is an "illegal" <what>=<this> pair */
  650. }
  651. while(*ptr && ISBLANK(*ptr))
  652. ptr++;
  653. if(*ptr == ';')
  654. ptr++;
  655. else
  656. break;
  657. } while(1);
  658. if(!co->domain && domain) {
  659. /* no domain was given in the header line, set the default */
  660. co->domain = strdup(domain);
  661. if(!co->domain)
  662. return CERR_OUT_OF_MEMORY;
  663. }
  664. if(!co->path && path) {
  665. /*
  666. * No path was given in the header line, set the default. Note that the
  667. * passed-in path to this function MAY have a '?' and following part that
  668. * MUST NOT be stored as part of the path.
  669. */
  670. char *queryp = strchr(path, '?');
  671. /*
  672. * queryp is where the interesting part of the path ends, so now we
  673. * want to the find the last
  674. */
  675. char *endslash;
  676. if(!queryp)
  677. endslash = strrchr(path, '/');
  678. else
  679. endslash = memrchr(path, '/', (queryp - path));
  680. if(endslash) {
  681. size_t pathlen = (endslash-path + 1); /* include end slash */
  682. co->path = Curl_memdup0(path, pathlen);
  683. if(co->path) {
  684. co->spath = sanitize_cookie_path(co->path);
  685. if(!co->spath)
  686. return CERR_OUT_OF_MEMORY;
  687. }
  688. else
  689. return CERR_OUT_OF_MEMORY;
  690. }
  691. }
  692. /*
  693. * If we did not get a cookie name, or a bad one, the this is an illegal
  694. * line so bail out.
  695. */
  696. if(!co->name)
  697. return CERR_BAD;
  698. data->req.setcookies++;
  699. return CERR_OK;
  700. }
  701. static int
  702. parse_netscape(struct Cookie *co,
  703. struct CookieInfo *ci,
  704. const char *lineptr,
  705. bool secure) /* TRUE if connection is over secure
  706. origin */
  707. {
  708. /*
  709. * This line is NOT an HTTP header style line, we do offer support for
  710. * reading the odd netscape cookies-file format here
  711. */
  712. char *ptr;
  713. char *firstptr;
  714. char *tok_buf = NULL;
  715. int fields;
  716. /*
  717. * In 2008, Internet Explorer introduced HTTP-only cookies to prevent XSS
  718. * attacks. Cookies marked httpOnly are not accessible to JavaScript. In
  719. * Firefox's cookie files, they are prefixed #HttpOnly_ and the rest
  720. * remains as usual, so we skip 10 characters of the line.
  721. */
  722. if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
  723. lineptr += 10;
  724. co->httponly = TRUE;
  725. }
  726. if(lineptr[0]=='#')
  727. /* do not even try the comments */
  728. return CERR_COMMENT;
  729. /* strip off the possible end-of-line characters */
  730. ptr = strchr(lineptr, '\r');
  731. if(ptr)
  732. *ptr = 0; /* clear it */
  733. ptr = strchr(lineptr, '\n');
  734. if(ptr)
  735. *ptr = 0; /* clear it */
  736. firstptr = strtok_r((char *)lineptr, "\t", &tok_buf); /* tokenize on TAB */
  737. /*
  738. * Now loop through the fields and init the struct we already have
  739. * allocated
  740. */
  741. fields = 0;
  742. for(ptr = firstptr; ptr; ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
  743. switch(fields) {
  744. case 0:
  745. if(ptr[0]=='.') /* skip preceding dots */
  746. ptr++;
  747. co->domain = strdup(ptr);
  748. if(!co->domain)
  749. return CERR_OUT_OF_MEMORY;
  750. break;
  751. case 1:
  752. /*
  753. * flag: A TRUE/FALSE value indicating if all machines within a given
  754. * domain can access the variable. Set TRUE when the cookie says
  755. * .domain.com and to false when the domain is complete www.domain.com
  756. */
  757. co->tailmatch = !!strcasecompare(ptr, "TRUE");
  758. break;
  759. case 2:
  760. /* The file format allows the path field to remain not filled in */
  761. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  762. /* only if the path does not look like a boolean option! */
  763. co->path = strdup(ptr);
  764. if(!co->path)
  765. return CERR_OUT_OF_MEMORY;
  766. else {
  767. co->spath = sanitize_cookie_path(co->path);
  768. if(!co->spath)
  769. return CERR_OUT_OF_MEMORY;
  770. }
  771. break;
  772. }
  773. /* this does not look like a path, make one up! */
  774. co->path = strdup("/");
  775. if(!co->path)
  776. return CERR_OUT_OF_MEMORY;
  777. co->spath = strdup("/");
  778. if(!co->spath)
  779. return CERR_OUT_OF_MEMORY;
  780. fields++; /* add a field and fall down to secure */
  781. FALLTHROUGH();
  782. case 3:
  783. co->secure = FALSE;
  784. if(strcasecompare(ptr, "TRUE")) {
  785. if(secure || ci->running)
  786. co->secure = TRUE;
  787. else
  788. return CERR_BAD_SECURE;
  789. }
  790. break;
  791. case 4:
  792. if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
  793. return CERR_RANGE;
  794. break;
  795. case 5:
  796. co->name = strdup(ptr);
  797. if(!co->name)
  798. return CERR_OUT_OF_MEMORY;
  799. else {
  800. /* For Netscape file format cookies we check prefix on the name */
  801. if(strncasecompare("__Secure-", co->name, 9))
  802. co->prefix_secure = TRUE;
  803. else if(strncasecompare("__Host-", co->name, 7))
  804. co->prefix_host = TRUE;
  805. }
  806. break;
  807. case 6:
  808. co->value = strdup(ptr);
  809. if(!co->value)
  810. return CERR_OUT_OF_MEMORY;
  811. break;
  812. }
  813. }
  814. if(6 == fields) {
  815. /* we got a cookie with blank contents, fix it */
  816. co->value = strdup("");
  817. if(!co->value)
  818. return CERR_OUT_OF_MEMORY;
  819. else
  820. fields++;
  821. }
  822. if(7 != fields)
  823. /* we did not find the sufficient number of fields */
  824. return CERR_FIELDS;
  825. return CERR_OK;
  826. }
  827. static int
  828. is_public_suffix(struct Curl_easy *data,
  829. struct Cookie *co,
  830. const char *domain)
  831. {
  832. #ifdef USE_LIBPSL
  833. /*
  834. * Check if the domain is a Public Suffix and if yes, ignore the cookie. We
  835. * must also check that the data handle is not NULL since the psl code will
  836. * dereference it.
  837. */
  838. DEBUGF(infof(data, "PSL check set-cookie '%s' for domain=%s in %s",
  839. co->name, co->domain, domain));
  840. if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) {
  841. bool acceptable = FALSE;
  842. char lcase[256];
  843. char lcookie[256];
  844. size_t dlen = strlen(domain);
  845. size_t clen = strlen(co->domain);
  846. if((dlen < sizeof(lcase)) && (clen < sizeof(lcookie))) {
  847. const psl_ctx_t *psl = Curl_psl_use(data);
  848. if(psl) {
  849. /* the PSL check requires lowercase domain name and pattern */
  850. Curl_strntolower(lcase, domain, dlen + 1);
  851. Curl_strntolower(lcookie, co->domain, clen + 1);
  852. acceptable = psl_is_cookie_domain_acceptable(psl, lcase, lcookie);
  853. Curl_psl_release(data);
  854. }
  855. else
  856. infof(data, "libpsl problem, rejecting cookie for satety");
  857. }
  858. if(!acceptable) {
  859. infof(data, "cookie '%s' dropped, domain '%s' must not "
  860. "set cookies for '%s'", co->name, domain, co->domain);
  861. return CERR_PSL;
  862. }
  863. }
  864. #else
  865. (void)data;
  866. (void)co;
  867. (void)domain;
  868. DEBUGF(infof(data, "NO PSL to check set-cookie '%s' for domain=%s in %s",
  869. co->name, co->domain, domain));
  870. #endif
  871. return CERR_OK;
  872. }
  873. static int
  874. replace_existing(struct Curl_easy *data,
  875. struct Cookie *co,
  876. struct CookieInfo *ci,
  877. bool secure,
  878. bool *replacep)
  879. {
  880. bool replace_old = FALSE;
  881. struct Curl_llist_node *replace_n = NULL;
  882. struct Curl_llist_node *n;
  883. size_t myhash = cookiehash(co->domain);
  884. for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
  885. struct Cookie *clist = Curl_node_elem(n);
  886. if(!strcmp(clist->name, co->name)) {
  887. /* the names are identical */
  888. bool matching_domains = FALSE;
  889. if(clist->domain && co->domain) {
  890. if(strcasecompare(clist->domain, co->domain))
  891. /* The domains are identical */
  892. matching_domains = TRUE;
  893. }
  894. else if(!clist->domain && !co->domain)
  895. matching_domains = TRUE;
  896. if(matching_domains && /* the domains were identical */
  897. clist->spath && co->spath && /* both have paths */
  898. clist->secure && !co->secure && !secure) {
  899. size_t cllen;
  900. const char *sep;
  901. /*
  902. * A non-secure cookie may not overlay an existing secure cookie.
  903. * For an existing cookie "a" with path "/login", refuse a new
  904. * cookie "a" with for example path "/login/en", while the path
  905. * "/loginhelper" is ok.
  906. */
  907. sep = strchr(clist->spath + 1, '/');
  908. if(sep)
  909. cllen = sep - clist->spath;
  910. else
  911. cllen = strlen(clist->spath);
  912. if(strncasecompare(clist->spath, co->spath, cllen)) {
  913. infof(data, "cookie '%s' for domain '%s' dropped, would "
  914. "overlay an existing cookie", co->name, co->domain);
  915. return CERR_BAD_SECURE;
  916. }
  917. }
  918. }
  919. if(!replace_n && !strcmp(clist->name, co->name)) {
  920. /* the names are identical */
  921. if(clist->domain && co->domain) {
  922. if(strcasecompare(clist->domain, co->domain) &&
  923. (clist->tailmatch == co->tailmatch))
  924. /* The domains are identical */
  925. replace_old = TRUE;
  926. }
  927. else if(!clist->domain && !co->domain)
  928. replace_old = TRUE;
  929. if(replace_old) {
  930. /* the domains were identical */
  931. if(clist->spath && co->spath &&
  932. !strcasecompare(clist->spath, co->spath))
  933. replace_old = FALSE;
  934. else if(!clist->spath != !co->spath)
  935. replace_old = FALSE;
  936. }
  937. if(replace_old && !co->livecookie && clist->livecookie) {
  938. /*
  939. * Both cookies matched fine, except that the already present cookie
  940. * is "live", which means it was set from a header, while the new one
  941. * was read from a file and thus is not "live". "live" cookies are
  942. * preferred so the new cookie is freed.
  943. */
  944. return CERR_LIVE_WINS;
  945. }
  946. if(replace_old)
  947. replace_n = n;
  948. }
  949. }
  950. if(replace_n) {
  951. struct Cookie *repl = Curl_node_elem(replace_n);
  952. /* when replacing, creationtime is kept from old */
  953. co->creationtime = repl->creationtime;
  954. /* unlink the old */
  955. Curl_node_remove(replace_n);
  956. /* free the old cookie */
  957. freecookie(repl);
  958. }
  959. *replacep = replace_old;
  960. return CERR_OK;
  961. }
  962. /*
  963. * Curl_cookie_add
  964. *
  965. * Add a single cookie line to the cookie keeping object. Be aware that
  966. * sometimes we get an IP-only hostname, and that might also be a numerical
  967. * IPv6 address.
  968. *
  969. * Returns NULL on out of memory or invalid cookie. This is suboptimal,
  970. * as they should be treated separately.
  971. */
  972. struct Cookie *
  973. Curl_cookie_add(struct Curl_easy *data,
  974. struct CookieInfo *ci,
  975. bool httpheader, /* TRUE if HTTP header-style line */
  976. bool noexpire, /* if TRUE, skip remove_expired() */
  977. const char *lineptr, /* first character of the line */
  978. const char *domain, /* default domain */
  979. const char *path, /* full path used when this cookie is set,
  980. used to get default path for the cookie
  981. unless set */
  982. bool secure) /* TRUE if connection is over secure origin */
  983. {
  984. struct Cookie *co;
  985. size_t myhash;
  986. int rc;
  987. bool replaces = FALSE;
  988. DEBUGASSERT(data);
  989. DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */
  990. if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT)
  991. return NULL;
  992. /* First, alloc and init a new struct for it */
  993. co = calloc(1, sizeof(struct Cookie));
  994. if(!co)
  995. return NULL; /* bail out if we are this low on memory */
  996. if(httpheader)
  997. rc = parse_cookie_header(data, co, ci, lineptr, domain, path, secure);
  998. else
  999. rc = parse_netscape(co, ci, lineptr, secure);
  1000. if(rc)
  1001. goto fail;
  1002. if(co->prefix_secure && !co->secure)
  1003. /* The __Secure- prefix only requires that the cookie be set secure */
  1004. goto fail;
  1005. if(co->prefix_host) {
  1006. /*
  1007. * The __Host- prefix requires the cookie to be secure, have a "/" path
  1008. * and not have a domain set.
  1009. */
  1010. if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
  1011. ;
  1012. else
  1013. goto fail;
  1014. }
  1015. if(!ci->running && /* read from a file */
  1016. ci->newsession && /* clean session cookies */
  1017. !co->expires) /* this is a session cookie since it does not expire */
  1018. goto fail;
  1019. co->livecookie = ci->running;
  1020. co->creationtime = ++ci->lastct;
  1021. /*
  1022. * Now we have parsed the incoming line, we must now check if this supersedes
  1023. * an already existing cookie, which it may if the previous have the same
  1024. * domain and path as this.
  1025. */
  1026. /* remove expired cookies */
  1027. if(!noexpire)
  1028. remove_expired(ci);
  1029. if(is_public_suffix(data, co, domain))
  1030. goto fail;
  1031. if(replace_existing(data, co, ci, secure, &replaces))
  1032. goto fail;
  1033. /* add this cookie to the list */
  1034. myhash = cookiehash(co->domain);
  1035. Curl_llist_append(&ci->cookielist[myhash], co, &co->node);
  1036. if(ci->running)
  1037. /* Only show this when NOT reading the cookies from a file */
  1038. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  1039. "expire %" FMT_OFF_T,
  1040. replaces ? "Replaced":"Added", co->name, co->value,
  1041. co->domain, co->path, co->expires);
  1042. if(!replaces)
  1043. ci->numcookies++; /* one more cookie in the jar */
  1044. /*
  1045. * Now that we have added a new cookie to the jar, update the expiration
  1046. * tracker in case it is the next one to expire.
  1047. */
  1048. if(co->expires && (co->expires < ci->next_expiration))
  1049. ci->next_expiration = co->expires;
  1050. return co;
  1051. fail:
  1052. freecookie(co);
  1053. return NULL;
  1054. }
  1055. /*
  1056. * Curl_cookie_init()
  1057. *
  1058. * Inits a cookie struct to read data from a local file. This is always
  1059. * called before any cookies are set. File may be NULL in which case only the
  1060. * struct is initialized. Is file is "-" then STDIN is read.
  1061. *
  1062. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  1063. *
  1064. * Note that 'data' might be called as NULL pointer. If data is NULL, 'file'
  1065. * will be ignored.
  1066. *
  1067. * Returns NULL on out of memory. Invalid cookies are ignored.
  1068. */
  1069. struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
  1070. const char *file,
  1071. struct CookieInfo *ci,
  1072. bool newsession)
  1073. {
  1074. FILE *handle = NULL;
  1075. if(!ci) {
  1076. int i;
  1077. /* we did not get a struct, create one */
  1078. ci = calloc(1, sizeof(struct CookieInfo));
  1079. if(!ci)
  1080. return NULL; /* failed to get memory */
  1081. /* This does not use the destructor callback since we want to add
  1082. and remove to lists while keeping the cookie struct intact */
  1083. for(i = 0; i < COOKIE_HASH_SIZE; i++)
  1084. Curl_llist_init(&ci->cookielist[i], NULL);
  1085. /*
  1086. * Initialize the next_expiration time to signal that we do not have enough
  1087. * information yet.
  1088. */
  1089. ci->next_expiration = CURL_OFF_T_MAX;
  1090. }
  1091. ci->newsession = newsession; /* new session? */
  1092. if(data) {
  1093. FILE *fp = NULL;
  1094. if(file && *file) {
  1095. if(!strcmp(file, "-"))
  1096. fp = stdin;
  1097. else {
  1098. fp = fopen(file, "rb");
  1099. if(!fp)
  1100. infof(data, "WARNING: failed to open cookie file \"%s\"", file);
  1101. else
  1102. handle = fp;
  1103. }
  1104. }
  1105. ci->running = FALSE; /* this is not running, this is init */
  1106. if(fp) {
  1107. struct dynbuf buf;
  1108. Curl_dyn_init(&buf, MAX_COOKIE_LINE);
  1109. while(Curl_get_line(&buf, fp)) {
  1110. char *lineptr = Curl_dyn_ptr(&buf);
  1111. bool headerline = FALSE;
  1112. if(checkprefix("Set-Cookie:", lineptr)) {
  1113. /* This is a cookie line, get it! */
  1114. lineptr += 11;
  1115. headerline = TRUE;
  1116. while(*lineptr && ISBLANK(*lineptr))
  1117. lineptr++;
  1118. }
  1119. Curl_cookie_add(data, ci, headerline, TRUE, lineptr, NULL, NULL, TRUE);
  1120. }
  1121. Curl_dyn_free(&buf); /* free the line buffer */
  1122. /*
  1123. * Remove expired cookies from the hash. We must make sure to run this
  1124. * after reading the file, and not on every cookie.
  1125. */
  1126. remove_expired(ci);
  1127. if(handle)
  1128. fclose(handle);
  1129. }
  1130. data->state.cookie_engine = TRUE;
  1131. }
  1132. ci->running = TRUE; /* now, we are running */
  1133. return ci;
  1134. }
  1135. /*
  1136. * cookie_sort
  1137. *
  1138. * Helper function to sort cookies such that the longest path gets before the
  1139. * shorter path. Path, domain and name lengths are considered in that order,
  1140. * with the creationtime as the tiebreaker. The creationtime is guaranteed to
  1141. * be unique per cookie, so we know we will get an ordering at that point.
  1142. */
  1143. static int cookie_sort(const void *p1, const void *p2)
  1144. {
  1145. struct Cookie *c1 = *(struct Cookie **)p1;
  1146. struct Cookie *c2 = *(struct Cookie **)p2;
  1147. size_t l1, l2;
  1148. /* 1 - compare cookie path lengths */
  1149. l1 = c1->path ? strlen(c1->path) : 0;
  1150. l2 = c2->path ? strlen(c2->path) : 0;
  1151. if(l1 != l2)
  1152. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1153. /* 2 - compare cookie domain lengths */
  1154. l1 = c1->domain ? strlen(c1->domain) : 0;
  1155. l2 = c2->domain ? strlen(c2->domain) : 0;
  1156. if(l1 != l2)
  1157. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1158. /* 3 - compare cookie name lengths */
  1159. l1 = c1->name ? strlen(c1->name) : 0;
  1160. l2 = c2->name ? strlen(c2->name) : 0;
  1161. if(l1 != l2)
  1162. return (l2 > l1) ? 1 : -1;
  1163. /* 4 - compare cookie creation time */
  1164. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1165. }
  1166. /*
  1167. * cookie_sort_ct
  1168. *
  1169. * Helper function to sort cookies according to creation time.
  1170. */
  1171. static int cookie_sort_ct(const void *p1, const void *p2)
  1172. {
  1173. struct Cookie *c1 = *(struct Cookie **)p1;
  1174. struct Cookie *c2 = *(struct Cookie **)p2;
  1175. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1176. }
  1177. /*
  1178. * Curl_cookie_getlist
  1179. *
  1180. * For a given host and path, return a linked list of cookies that the client
  1181. * should send to the server if used now. The secure boolean informs the cookie
  1182. * if a secure connection is achieved or not.
  1183. *
  1184. * It shall only return cookies that have not expired.
  1185. *
  1186. * Returns 0 when there is a list returned. Otherwise non-zero.
  1187. */
  1188. int Curl_cookie_getlist(struct Curl_easy *data,
  1189. struct CookieInfo *ci,
  1190. const char *host, const char *path,
  1191. bool secure,
  1192. struct Curl_llist *list)
  1193. {
  1194. size_t matches = 0;
  1195. bool is_ip;
  1196. const size_t myhash = cookiehash(host);
  1197. struct Curl_llist_node *n;
  1198. Curl_llist_init(list, NULL);
  1199. if(!ci || !Curl_llist_count(&ci->cookielist[myhash]))
  1200. return 1; /* no cookie struct or no cookies in the struct */
  1201. /* at first, remove expired cookies */
  1202. remove_expired(ci);
  1203. /* check if host is an IP(v4|v6) address */
  1204. is_ip = Curl_host_is_ipnum(host);
  1205. for(n = Curl_llist_head(&ci->cookielist[myhash]);
  1206. n; n = Curl_node_next(n)) {
  1207. struct Cookie *co = Curl_node_elem(n);
  1208. /* if the cookie requires we are secure we must only continue if we are! */
  1209. if(co->secure ? secure : TRUE) {
  1210. /* now check if the domain is correct */
  1211. if(!co->domain ||
  1212. (co->tailmatch && !is_ip &&
  1213. cookie_tailmatch(co->domain, strlen(co->domain), host)) ||
  1214. ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
  1215. /*
  1216. * the right part of the host matches the domain stuff in the
  1217. * cookie data
  1218. */
  1219. /*
  1220. * now check the left part of the path with the cookies path
  1221. * requirement
  1222. */
  1223. if(!co->spath || pathmatch(co->spath, path) ) {
  1224. /*
  1225. * This is a match and we add it to the return-linked-list
  1226. */
  1227. Curl_llist_append(list, co, &co->getnode);
  1228. matches++;
  1229. if(matches >= MAX_COOKIE_SEND_AMOUNT) {
  1230. infof(data, "Included max number of cookies (%zu) in request!",
  1231. matches);
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. }
  1237. }
  1238. if(matches) {
  1239. /*
  1240. * Now we need to make sure that if there is a name appearing more than
  1241. * once, the longest specified path version comes first. To make this
  1242. * the swiftest way, we just sort them all based on path length.
  1243. */
  1244. struct Cookie **array;
  1245. size_t i;
  1246. /* alloc an array and store all cookie pointers */
  1247. array = malloc(sizeof(struct Cookie *) * matches);
  1248. if(!array)
  1249. goto fail;
  1250. n = Curl_llist_head(list);
  1251. for(i = 0; n; n = Curl_node_next(n))
  1252. array[i++] = Curl_node_elem(n);
  1253. /* now sort the cookie pointers in path length order */
  1254. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  1255. /* remake the linked list order according to the new order */
  1256. Curl_llist_destroy(list, NULL);
  1257. for(i = 0; i < matches; i++)
  1258. Curl_llist_append(list, array[i], &array[i]->getnode);
  1259. free(array); /* remove the temporary data again */
  1260. }
  1261. return 0; /* success */
  1262. fail:
  1263. /* failure, clear up the allocated chain and return NULL */
  1264. Curl_llist_destroy(list, NULL);
  1265. return 2; /* error */
  1266. }
  1267. /*
  1268. * Curl_cookie_clearall
  1269. *
  1270. * Clear all existing cookies and reset the counter.
  1271. */
  1272. void Curl_cookie_clearall(struct CookieInfo *ci)
  1273. {
  1274. if(ci) {
  1275. unsigned int i;
  1276. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1277. struct Curl_llist_node *n;
  1278. for(n = Curl_llist_head(&ci->cookielist[i]); n;) {
  1279. struct Cookie *c = Curl_node_elem(n);
  1280. struct Curl_llist_node *e = Curl_node_next(n);
  1281. Curl_node_remove(n);
  1282. freecookie(c);
  1283. n = e;
  1284. }
  1285. }
  1286. ci->numcookies = 0;
  1287. }
  1288. }
  1289. /*
  1290. * Curl_cookie_clearsess
  1291. *
  1292. * Free all session cookies in the cookies list.
  1293. */
  1294. void Curl_cookie_clearsess(struct CookieInfo *ci)
  1295. {
  1296. unsigned int i;
  1297. if(!ci)
  1298. return;
  1299. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1300. struct Curl_llist_node *n = Curl_llist_head(&ci->cookielist[i]);
  1301. struct Curl_llist_node *e = NULL;
  1302. for(; n; n = e) {
  1303. struct Cookie *curr = Curl_node_elem(n);
  1304. e = Curl_node_next(n); /* in case the node is removed, get it early */
  1305. if(!curr->expires) {
  1306. Curl_node_remove(n);
  1307. freecookie(curr);
  1308. ci->numcookies--;
  1309. }
  1310. }
  1311. }
  1312. }
  1313. /*
  1314. * Curl_cookie_cleanup()
  1315. *
  1316. * Free a "cookie object" previous created with Curl_cookie_init().
  1317. */
  1318. void Curl_cookie_cleanup(struct CookieInfo *ci)
  1319. {
  1320. if(ci) {
  1321. Curl_cookie_clearall(ci);
  1322. free(ci); /* free the base struct as well */
  1323. }
  1324. }
  1325. /*
  1326. * get_netscape_format()
  1327. *
  1328. * Formats a string for Netscape output file, w/o a newline at the end.
  1329. * Function returns a char * to a formatted line. The caller is responsible
  1330. * for freeing the returned pointer.
  1331. */
  1332. static char *get_netscape_format(const struct Cookie *co)
  1333. {
  1334. return aprintf(
  1335. "%s" /* httponly preamble */
  1336. "%s%s\t" /* domain */
  1337. "%s\t" /* tailmatch */
  1338. "%s\t" /* path */
  1339. "%s\t" /* secure */
  1340. "%" FMT_OFF_T "\t" /* expires */
  1341. "%s\t" /* name */
  1342. "%s", /* value */
  1343. co->httponly ? "#HttpOnly_" : "",
  1344. /*
  1345. * Make sure all domains are prefixed with a dot if they allow
  1346. * tailmatching. This is Mozilla-style.
  1347. */
  1348. (co->tailmatch && co->domain && co->domain[0] != '.') ? "." : "",
  1349. co->domain ? co->domain : "unknown",
  1350. co->tailmatch ? "TRUE" : "FALSE",
  1351. co->path ? co->path : "/",
  1352. co->secure ? "TRUE" : "FALSE",
  1353. co->expires,
  1354. co->name,
  1355. co->value ? co->value : "");
  1356. }
  1357. /*
  1358. * cookie_output()
  1359. *
  1360. * Writes all internally known cookies to the specified file. Specify
  1361. * "-" as filename to write to stdout.
  1362. *
  1363. * The function returns non-zero on write failure.
  1364. */
  1365. static CURLcode cookie_output(struct Curl_easy *data,
  1366. struct CookieInfo *ci,
  1367. const char *filename)
  1368. {
  1369. FILE *out = NULL;
  1370. bool use_stdout = FALSE;
  1371. char *tempstore = NULL;
  1372. CURLcode error = CURLE_OK;
  1373. if(!ci)
  1374. /* no cookie engine alive */
  1375. return CURLE_OK;
  1376. /* at first, remove expired cookies */
  1377. remove_expired(ci);
  1378. if(!strcmp("-", filename)) {
  1379. /* use stdout */
  1380. out = stdout;
  1381. use_stdout = TRUE;
  1382. }
  1383. else {
  1384. error = Curl_fopen(data, filename, &out, &tempstore);
  1385. if(error)
  1386. goto error;
  1387. }
  1388. fputs("# Netscape HTTP Cookie File\n"
  1389. "# https://curl.se/docs/http-cookies.html\n"
  1390. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  1391. out);
  1392. if(ci->numcookies) {
  1393. unsigned int i;
  1394. size_t nvalid = 0;
  1395. struct Cookie **array;
  1396. struct Curl_llist_node *n;
  1397. array = calloc(1, sizeof(struct Cookie *) * ci->numcookies);
  1398. if(!array) {
  1399. error = CURLE_OUT_OF_MEMORY;
  1400. goto error;
  1401. }
  1402. /* only sort the cookies with a domain property */
  1403. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1404. for(n = Curl_llist_head(&ci->cookielist[i]); n;
  1405. n = Curl_node_next(n)) {
  1406. struct Cookie *co = Curl_node_elem(n);
  1407. if(!co->domain)
  1408. continue;
  1409. array[nvalid++] = co;
  1410. }
  1411. }
  1412. qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
  1413. for(i = 0; i < nvalid; i++) {
  1414. char *format_ptr = get_netscape_format(array[i]);
  1415. if(!format_ptr) {
  1416. free(array);
  1417. error = CURLE_OUT_OF_MEMORY;
  1418. goto error;
  1419. }
  1420. fprintf(out, "%s\n", format_ptr);
  1421. free(format_ptr);
  1422. }
  1423. free(array);
  1424. }
  1425. if(!use_stdout) {
  1426. fclose(out);
  1427. out = NULL;
  1428. if(tempstore && Curl_rename(tempstore, filename)) {
  1429. unlink(tempstore);
  1430. error = CURLE_WRITE_ERROR;
  1431. goto error;
  1432. }
  1433. }
  1434. /*
  1435. * If we reach here we have successfully written a cookie file so there is
  1436. * no need to inspect the error, any error case should have jumped into the
  1437. * error block below.
  1438. */
  1439. free(tempstore);
  1440. return CURLE_OK;
  1441. error:
  1442. if(out && !use_stdout)
  1443. fclose(out);
  1444. free(tempstore);
  1445. return error;
  1446. }
  1447. static struct curl_slist *cookie_list(struct Curl_easy *data)
  1448. {
  1449. struct curl_slist *list = NULL;
  1450. struct curl_slist *beg;
  1451. unsigned int i;
  1452. struct Curl_llist_node *n;
  1453. if(!data->cookies || (data->cookies->numcookies == 0))
  1454. return NULL;
  1455. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1456. for(n = Curl_llist_head(&data->cookies->cookielist[i]); n;
  1457. n = Curl_node_next(n)) {
  1458. struct Cookie *c = Curl_node_elem(n);
  1459. char *line;
  1460. if(!c->domain)
  1461. continue;
  1462. line = get_netscape_format(c);
  1463. if(!line) {
  1464. curl_slist_free_all(list);
  1465. return NULL;
  1466. }
  1467. beg = Curl_slist_append_nodup(list, line);
  1468. if(!beg) {
  1469. free(line);
  1470. curl_slist_free_all(list);
  1471. return NULL;
  1472. }
  1473. list = beg;
  1474. }
  1475. }
  1476. return list;
  1477. }
  1478. struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
  1479. {
  1480. struct curl_slist *list;
  1481. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1482. list = cookie_list(data);
  1483. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1484. return list;
  1485. }
  1486. void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
  1487. {
  1488. CURLcode res;
  1489. if(data->set.str[STRING_COOKIEJAR]) {
  1490. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1491. /* if we have a destination file for all the cookies to get dumped to */
  1492. res = cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]);
  1493. if(res)
  1494. infof(data, "WARNING: failed to save cookies in %s: %s",
  1495. data->set.str[STRING_COOKIEJAR], curl_easy_strerror(res));
  1496. }
  1497. else {
  1498. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1499. }
  1500. if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
  1501. Curl_cookie_cleanup(data->cookies);
  1502. data->cookies = NULL;
  1503. }
  1504. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1505. }
  1506. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */