cookie.c 49 KB

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