cookie.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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. /* tokenize on TAB */
  737. firstptr = Curl_strtok_r((char *)lineptr, "\t", &tok_buf);
  738. /*
  739. * Now loop through the fields and init the struct we already have
  740. * allocated
  741. */
  742. fields = 0;
  743. for(ptr = firstptr; ptr;
  744. ptr = Curl_strtok_r(NULL, "\t", &tok_buf), fields++) {
  745. switch(fields) {
  746. case 0:
  747. if(ptr[0]=='.') /* skip preceding dots */
  748. ptr++;
  749. co->domain = strdup(ptr);
  750. if(!co->domain)
  751. return CERR_OUT_OF_MEMORY;
  752. break;
  753. case 1:
  754. /*
  755. * flag: A TRUE/FALSE value indicating if all machines within a given
  756. * domain can access the variable. Set TRUE when the cookie says
  757. * .domain.com and to false when the domain is complete www.domain.com
  758. */
  759. co->tailmatch = !!strcasecompare(ptr, "TRUE");
  760. break;
  761. case 2:
  762. /* The file format allows the path field to remain not filled in */
  763. if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
  764. /* only if the path does not look like a boolean option! */
  765. co->path = strdup(ptr);
  766. if(!co->path)
  767. return CERR_OUT_OF_MEMORY;
  768. else {
  769. co->spath = sanitize_cookie_path(co->path);
  770. if(!co->spath)
  771. return CERR_OUT_OF_MEMORY;
  772. }
  773. break;
  774. }
  775. /* this does not look like a path, make one up! */
  776. co->path = strdup("/");
  777. if(!co->path)
  778. return CERR_OUT_OF_MEMORY;
  779. co->spath = strdup("/");
  780. if(!co->spath)
  781. return CERR_OUT_OF_MEMORY;
  782. fields++; /* add a field and fall down to secure */
  783. FALLTHROUGH();
  784. case 3:
  785. co->secure = FALSE;
  786. if(strcasecompare(ptr, "TRUE")) {
  787. if(secure || ci->running)
  788. co->secure = TRUE;
  789. else
  790. return CERR_BAD_SECURE;
  791. }
  792. break;
  793. case 4:
  794. if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
  795. return CERR_RANGE;
  796. break;
  797. case 5:
  798. co->name = strdup(ptr);
  799. if(!co->name)
  800. return CERR_OUT_OF_MEMORY;
  801. else {
  802. /* For Netscape file format cookies we check prefix on the name */
  803. if(strncasecompare("__Secure-", co->name, 9))
  804. co->prefix_secure = TRUE;
  805. else if(strncasecompare("__Host-", co->name, 7))
  806. co->prefix_host = TRUE;
  807. }
  808. break;
  809. case 6:
  810. co->value = strdup(ptr);
  811. if(!co->value)
  812. return CERR_OUT_OF_MEMORY;
  813. break;
  814. }
  815. }
  816. if(6 == fields) {
  817. /* we got a cookie with blank contents, fix it */
  818. co->value = strdup("");
  819. if(!co->value)
  820. return CERR_OUT_OF_MEMORY;
  821. else
  822. fields++;
  823. }
  824. if(7 != fields)
  825. /* we did not find the sufficient number of fields */
  826. return CERR_FIELDS;
  827. return CERR_OK;
  828. }
  829. static int
  830. is_public_suffix(struct Curl_easy *data,
  831. struct Cookie *co,
  832. const char *domain)
  833. {
  834. #ifdef USE_LIBPSL
  835. /*
  836. * Check if the domain is a Public Suffix and if yes, ignore the cookie. We
  837. * must also check that the data handle is not NULL since the psl code will
  838. * dereference it.
  839. */
  840. DEBUGF(infof(data, "PSL check set-cookie '%s' for domain=%s in %s",
  841. co->name, co->domain, domain));
  842. if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) {
  843. bool acceptable = FALSE;
  844. char lcase[256];
  845. char lcookie[256];
  846. size_t dlen = strlen(domain);
  847. size_t clen = strlen(co->domain);
  848. if((dlen < sizeof(lcase)) && (clen < sizeof(lcookie))) {
  849. const psl_ctx_t *psl = Curl_psl_use(data);
  850. if(psl) {
  851. /* the PSL check requires lowercase domain name and pattern */
  852. Curl_strntolower(lcase, domain, dlen + 1);
  853. Curl_strntolower(lcookie, co->domain, clen + 1);
  854. acceptable = psl_is_cookie_domain_acceptable(psl, lcase, lcookie);
  855. Curl_psl_release(data);
  856. }
  857. else
  858. infof(data, "libpsl problem, rejecting cookie for satety");
  859. }
  860. if(!acceptable) {
  861. infof(data, "cookie '%s' dropped, domain '%s' must not "
  862. "set cookies for '%s'", co->name, domain, co->domain);
  863. return CERR_PSL;
  864. }
  865. }
  866. #else
  867. (void)data;
  868. (void)co;
  869. (void)domain;
  870. DEBUGF(infof(data, "NO PSL to check set-cookie '%s' for domain=%s in %s",
  871. co->name, co->domain, domain));
  872. #endif
  873. return CERR_OK;
  874. }
  875. static int
  876. replace_existing(struct Curl_easy *data,
  877. struct Cookie *co,
  878. struct CookieInfo *ci,
  879. bool secure,
  880. bool *replacep)
  881. {
  882. bool replace_old = FALSE;
  883. struct Curl_llist_node *replace_n = NULL;
  884. struct Curl_llist_node *n;
  885. size_t myhash = cookiehash(co->domain);
  886. for(n = Curl_llist_head(&ci->cookielist[myhash]); n; n = Curl_node_next(n)) {
  887. struct Cookie *clist = Curl_node_elem(n);
  888. if(!strcmp(clist->name, co->name)) {
  889. /* the names are identical */
  890. bool matching_domains = FALSE;
  891. if(clist->domain && co->domain) {
  892. if(strcasecompare(clist->domain, co->domain))
  893. /* The domains are identical */
  894. matching_domains = TRUE;
  895. }
  896. else if(!clist->domain && !co->domain)
  897. matching_domains = TRUE;
  898. if(matching_domains && /* the domains were identical */
  899. clist->spath && co->spath && /* both have paths */
  900. clist->secure && !co->secure && !secure) {
  901. size_t cllen;
  902. const char *sep;
  903. /*
  904. * A non-secure cookie may not overlay an existing secure cookie.
  905. * For an existing cookie "a" with path "/login", refuse a new
  906. * cookie "a" with for example path "/login/en", while the path
  907. * "/loginhelper" is ok.
  908. */
  909. sep = strchr(clist->spath + 1, '/');
  910. if(sep)
  911. cllen = sep - clist->spath;
  912. else
  913. cllen = strlen(clist->spath);
  914. if(strncasecompare(clist->spath, co->spath, cllen)) {
  915. infof(data, "cookie '%s' for domain '%s' dropped, would "
  916. "overlay an existing cookie", co->name, co->domain);
  917. return CERR_BAD_SECURE;
  918. }
  919. }
  920. }
  921. if(!replace_n && !strcmp(clist->name, co->name)) {
  922. /* the names are identical */
  923. if(clist->domain && co->domain) {
  924. if(strcasecompare(clist->domain, co->domain) &&
  925. (clist->tailmatch == co->tailmatch))
  926. /* The domains are identical */
  927. replace_old = TRUE;
  928. }
  929. else if(!clist->domain && !co->domain)
  930. replace_old = TRUE;
  931. if(replace_old) {
  932. /* the domains were identical */
  933. if(clist->spath && co->spath &&
  934. !strcasecompare(clist->spath, co->spath))
  935. replace_old = FALSE;
  936. else if(!clist->spath != !co->spath)
  937. replace_old = FALSE;
  938. }
  939. if(replace_old && !co->livecookie && clist->livecookie) {
  940. /*
  941. * Both cookies matched fine, except that the already present cookie
  942. * is "live", which means it was set from a header, while the new one
  943. * was read from a file and thus is not "live". "live" cookies are
  944. * preferred so the new cookie is freed.
  945. */
  946. return CERR_LIVE_WINS;
  947. }
  948. if(replace_old)
  949. replace_n = n;
  950. }
  951. }
  952. if(replace_n) {
  953. struct Cookie *repl = Curl_node_elem(replace_n);
  954. /* when replacing, creationtime is kept from old */
  955. co->creationtime = repl->creationtime;
  956. /* unlink the old */
  957. Curl_node_remove(replace_n);
  958. /* free the old cookie */
  959. freecookie(repl);
  960. }
  961. *replacep = replace_old;
  962. return CERR_OK;
  963. }
  964. /*
  965. * Curl_cookie_add
  966. *
  967. * Add a single cookie line to the cookie keeping object. Be aware that
  968. * sometimes we get an IP-only hostname, and that might also be a numerical
  969. * IPv6 address.
  970. *
  971. * Returns NULL on out of memory or invalid cookie. This is suboptimal,
  972. * as they should be treated separately.
  973. */
  974. struct Cookie *
  975. Curl_cookie_add(struct Curl_easy *data,
  976. struct CookieInfo *ci,
  977. bool httpheader, /* TRUE if HTTP header-style line */
  978. bool noexpire, /* if TRUE, skip remove_expired() */
  979. const char *lineptr, /* first character of the line */
  980. const char *domain, /* default domain */
  981. const char *path, /* full path used when this cookie is set,
  982. used to get default path for the cookie
  983. unless set */
  984. bool secure) /* TRUE if connection is over secure origin */
  985. {
  986. struct Cookie *co;
  987. size_t myhash;
  988. int rc;
  989. bool replaces = FALSE;
  990. DEBUGASSERT(data);
  991. DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */
  992. if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT)
  993. return NULL;
  994. /* First, alloc and init a new struct for it */
  995. co = calloc(1, sizeof(struct Cookie));
  996. if(!co)
  997. return NULL; /* bail out if we are this low on memory */
  998. if(httpheader)
  999. rc = parse_cookie_header(data, co, ci, lineptr, domain, path, secure);
  1000. else
  1001. rc = parse_netscape(co, ci, lineptr, secure);
  1002. if(rc)
  1003. goto fail;
  1004. if(co->prefix_secure && !co->secure)
  1005. /* The __Secure- prefix only requires that the cookie be set secure */
  1006. goto fail;
  1007. if(co->prefix_host) {
  1008. /*
  1009. * The __Host- prefix requires the cookie to be secure, have a "/" path
  1010. * and not have a domain set.
  1011. */
  1012. if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
  1013. ;
  1014. else
  1015. goto fail;
  1016. }
  1017. if(!ci->running && /* read from a file */
  1018. ci->newsession && /* clean session cookies */
  1019. !co->expires) /* this is a session cookie since it does not expire */
  1020. goto fail;
  1021. co->livecookie = ci->running;
  1022. co->creationtime = ++ci->lastct;
  1023. /*
  1024. * Now we have parsed the incoming line, we must now check if this supersedes
  1025. * an already existing cookie, which it may if the previous have the same
  1026. * domain and path as this.
  1027. */
  1028. /* remove expired cookies */
  1029. if(!noexpire)
  1030. remove_expired(ci);
  1031. if(is_public_suffix(data, co, domain))
  1032. goto fail;
  1033. if(replace_existing(data, co, ci, secure, &replaces))
  1034. goto fail;
  1035. /* add this cookie to the list */
  1036. myhash = cookiehash(co->domain);
  1037. Curl_llist_append(&ci->cookielist[myhash], co, &co->node);
  1038. if(ci->running)
  1039. /* Only show this when NOT reading the cookies from a file */
  1040. infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
  1041. "expire %" FMT_OFF_T,
  1042. replaces ? "Replaced":"Added", co->name, co->value,
  1043. co->domain, co->path, co->expires);
  1044. if(!replaces)
  1045. ci->numcookies++; /* one more cookie in the jar */
  1046. /*
  1047. * Now that we have added a new cookie to the jar, update the expiration
  1048. * tracker in case it is the next one to expire.
  1049. */
  1050. if(co->expires && (co->expires < ci->next_expiration))
  1051. ci->next_expiration = co->expires;
  1052. return co;
  1053. fail:
  1054. freecookie(co);
  1055. return NULL;
  1056. }
  1057. /*
  1058. * Curl_cookie_init()
  1059. *
  1060. * Inits a cookie struct to read data from a local file. This is always
  1061. * called before any cookies are set. File may be NULL in which case only the
  1062. * struct is initialized. Is file is "-" then STDIN is read.
  1063. *
  1064. * If 'newsession' is TRUE, discard all "session cookies" on read from file.
  1065. *
  1066. * Note that 'data' might be called as NULL pointer. If data is NULL, 'file'
  1067. * will be ignored.
  1068. *
  1069. * Returns NULL on out of memory. Invalid cookies are ignored.
  1070. */
  1071. struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
  1072. const char *file,
  1073. struct CookieInfo *ci,
  1074. bool newsession)
  1075. {
  1076. FILE *handle = NULL;
  1077. if(!ci) {
  1078. int i;
  1079. /* we did not get a struct, create one */
  1080. ci = calloc(1, sizeof(struct CookieInfo));
  1081. if(!ci)
  1082. return NULL; /* failed to get memory */
  1083. /* This does not use the destructor callback since we want to add
  1084. and remove to lists while keeping the cookie struct intact */
  1085. for(i = 0; i < COOKIE_HASH_SIZE; i++)
  1086. Curl_llist_init(&ci->cookielist[i], NULL);
  1087. /*
  1088. * Initialize the next_expiration time to signal that we do not have enough
  1089. * information yet.
  1090. */
  1091. ci->next_expiration = CURL_OFF_T_MAX;
  1092. }
  1093. ci->newsession = newsession; /* new session? */
  1094. if(data) {
  1095. FILE *fp = NULL;
  1096. if(file && *file) {
  1097. if(!strcmp(file, "-"))
  1098. fp = stdin;
  1099. else {
  1100. fp = fopen(file, "rb");
  1101. if(!fp)
  1102. infof(data, "WARNING: failed to open cookie file \"%s\"", file);
  1103. else
  1104. handle = fp;
  1105. }
  1106. }
  1107. ci->running = FALSE; /* this is not running, this is init */
  1108. if(fp) {
  1109. struct dynbuf buf;
  1110. Curl_dyn_init(&buf, MAX_COOKIE_LINE);
  1111. while(Curl_get_line(&buf, fp)) {
  1112. char *lineptr = Curl_dyn_ptr(&buf);
  1113. bool headerline = FALSE;
  1114. if(checkprefix("Set-Cookie:", lineptr)) {
  1115. /* This is a cookie line, get it! */
  1116. lineptr += 11;
  1117. headerline = TRUE;
  1118. while(*lineptr && ISBLANK(*lineptr))
  1119. lineptr++;
  1120. }
  1121. Curl_cookie_add(data, ci, headerline, TRUE, lineptr, NULL, NULL, TRUE);
  1122. }
  1123. Curl_dyn_free(&buf); /* free the line buffer */
  1124. /*
  1125. * Remove expired cookies from the hash. We must make sure to run this
  1126. * after reading the file, and not on every cookie.
  1127. */
  1128. remove_expired(ci);
  1129. if(handle)
  1130. fclose(handle);
  1131. }
  1132. data->state.cookie_engine = TRUE;
  1133. }
  1134. ci->running = TRUE; /* now, we are running */
  1135. return ci;
  1136. }
  1137. /*
  1138. * cookie_sort
  1139. *
  1140. * Helper function to sort cookies such that the longest path gets before the
  1141. * shorter path. Path, domain and name lengths are considered in that order,
  1142. * with the creationtime as the tiebreaker. The creationtime is guaranteed to
  1143. * be unique per cookie, so we know we will get an ordering at that point.
  1144. */
  1145. static int cookie_sort(const void *p1, const void *p2)
  1146. {
  1147. struct Cookie *c1 = *(struct Cookie **)p1;
  1148. struct Cookie *c2 = *(struct Cookie **)p2;
  1149. size_t l1, l2;
  1150. /* 1 - compare cookie path lengths */
  1151. l1 = c1->path ? strlen(c1->path) : 0;
  1152. l2 = c2->path ? strlen(c2->path) : 0;
  1153. if(l1 != l2)
  1154. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1155. /* 2 - compare cookie domain lengths */
  1156. l1 = c1->domain ? strlen(c1->domain) : 0;
  1157. l2 = c2->domain ? strlen(c2->domain) : 0;
  1158. if(l1 != l2)
  1159. return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
  1160. /* 3 - compare cookie name lengths */
  1161. l1 = c1->name ? strlen(c1->name) : 0;
  1162. l2 = c2->name ? strlen(c2->name) : 0;
  1163. if(l1 != l2)
  1164. return (l2 > l1) ? 1 : -1;
  1165. /* 4 - compare cookie creation time */
  1166. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1167. }
  1168. /*
  1169. * cookie_sort_ct
  1170. *
  1171. * Helper function to sort cookies according to creation time.
  1172. */
  1173. static int cookie_sort_ct(const void *p1, const void *p2)
  1174. {
  1175. struct Cookie *c1 = *(struct Cookie **)p1;
  1176. struct Cookie *c2 = *(struct Cookie **)p2;
  1177. return (c2->creationtime > c1->creationtime) ? 1 : -1;
  1178. }
  1179. /*
  1180. * Curl_cookie_getlist
  1181. *
  1182. * For a given host and path, return a linked list of cookies that the client
  1183. * should send to the server if used now. The secure boolean informs the cookie
  1184. * if a secure connection is achieved or not.
  1185. *
  1186. * It shall only return cookies that have not expired.
  1187. *
  1188. * Returns 0 when there is a list returned. Otherwise non-zero.
  1189. */
  1190. int Curl_cookie_getlist(struct Curl_easy *data,
  1191. struct CookieInfo *ci,
  1192. const char *host, const char *path,
  1193. bool secure,
  1194. struct Curl_llist *list)
  1195. {
  1196. size_t matches = 0;
  1197. bool is_ip;
  1198. const size_t myhash = cookiehash(host);
  1199. struct Curl_llist_node *n;
  1200. Curl_llist_init(list, NULL);
  1201. if(!ci || !Curl_llist_count(&ci->cookielist[myhash]))
  1202. return 1; /* no cookie struct or no cookies in the struct */
  1203. /* at first, remove expired cookies */
  1204. remove_expired(ci);
  1205. /* check if host is an IP(v4|v6) address */
  1206. is_ip = Curl_host_is_ipnum(host);
  1207. for(n = Curl_llist_head(&ci->cookielist[myhash]);
  1208. n; n = Curl_node_next(n)) {
  1209. struct Cookie *co = Curl_node_elem(n);
  1210. /* if the cookie requires we are secure we must only continue if we are! */
  1211. if(co->secure ? secure : TRUE) {
  1212. /* now check if the domain is correct */
  1213. if(!co->domain ||
  1214. (co->tailmatch && !is_ip &&
  1215. cookie_tailmatch(co->domain, strlen(co->domain), host)) ||
  1216. ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
  1217. /*
  1218. * the right part of the host matches the domain stuff in the
  1219. * cookie data
  1220. */
  1221. /*
  1222. * now check the left part of the path with the cookies path
  1223. * requirement
  1224. */
  1225. if(!co->spath || pathmatch(co->spath, path) ) {
  1226. /*
  1227. * This is a match and we add it to the return-linked-list
  1228. */
  1229. Curl_llist_append(list, co, &co->getnode);
  1230. matches++;
  1231. if(matches >= MAX_COOKIE_SEND_AMOUNT) {
  1232. infof(data, "Included max number of cookies (%zu) in request!",
  1233. matches);
  1234. break;
  1235. }
  1236. }
  1237. }
  1238. }
  1239. }
  1240. if(matches) {
  1241. /*
  1242. * Now we need to make sure that if there is a name appearing more than
  1243. * once, the longest specified path version comes first. To make this
  1244. * the swiftest way, we just sort them all based on path length.
  1245. */
  1246. struct Cookie **array;
  1247. size_t i;
  1248. /* alloc an array and store all cookie pointers */
  1249. array = malloc(sizeof(struct Cookie *) * matches);
  1250. if(!array)
  1251. goto fail;
  1252. n = Curl_llist_head(list);
  1253. for(i = 0; n; n = Curl_node_next(n))
  1254. array[i++] = Curl_node_elem(n);
  1255. /* now sort the cookie pointers in path length order */
  1256. qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
  1257. /* remake the linked list order according to the new order */
  1258. Curl_llist_destroy(list, NULL);
  1259. for(i = 0; i < matches; i++)
  1260. Curl_llist_append(list, array[i], &array[i]->getnode);
  1261. free(array); /* remove the temporary data again */
  1262. }
  1263. return 0; /* success */
  1264. fail:
  1265. /* failure, clear up the allocated chain and return NULL */
  1266. Curl_llist_destroy(list, NULL);
  1267. return 2; /* error */
  1268. }
  1269. /*
  1270. * Curl_cookie_clearall
  1271. *
  1272. * Clear all existing cookies and reset the counter.
  1273. */
  1274. void Curl_cookie_clearall(struct CookieInfo *ci)
  1275. {
  1276. if(ci) {
  1277. unsigned int i;
  1278. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1279. struct Curl_llist_node *n;
  1280. for(n = Curl_llist_head(&ci->cookielist[i]); n;) {
  1281. struct Cookie *c = Curl_node_elem(n);
  1282. struct Curl_llist_node *e = Curl_node_next(n);
  1283. Curl_node_remove(n);
  1284. freecookie(c);
  1285. n = e;
  1286. }
  1287. }
  1288. ci->numcookies = 0;
  1289. }
  1290. }
  1291. /*
  1292. * Curl_cookie_clearsess
  1293. *
  1294. * Free all session cookies in the cookies list.
  1295. */
  1296. void Curl_cookie_clearsess(struct CookieInfo *ci)
  1297. {
  1298. unsigned int i;
  1299. if(!ci)
  1300. return;
  1301. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1302. struct Curl_llist_node *n = Curl_llist_head(&ci->cookielist[i]);
  1303. struct Curl_llist_node *e = NULL;
  1304. for(; n; n = e) {
  1305. struct Cookie *curr = Curl_node_elem(n);
  1306. e = Curl_node_next(n); /* in case the node is removed, get it early */
  1307. if(!curr->expires) {
  1308. Curl_node_remove(n);
  1309. freecookie(curr);
  1310. ci->numcookies--;
  1311. }
  1312. }
  1313. }
  1314. }
  1315. /*
  1316. * Curl_cookie_cleanup()
  1317. *
  1318. * Free a "cookie object" previous created with Curl_cookie_init().
  1319. */
  1320. void Curl_cookie_cleanup(struct CookieInfo *ci)
  1321. {
  1322. if(ci) {
  1323. Curl_cookie_clearall(ci);
  1324. free(ci); /* free the base struct as well */
  1325. }
  1326. }
  1327. /*
  1328. * get_netscape_format()
  1329. *
  1330. * Formats a string for Netscape output file, w/o a newline at the end.
  1331. * Function returns a char * to a formatted line. The caller is responsible
  1332. * for freeing the returned pointer.
  1333. */
  1334. static char *get_netscape_format(const struct Cookie *co)
  1335. {
  1336. return aprintf(
  1337. "%s" /* httponly preamble */
  1338. "%s%s\t" /* domain */
  1339. "%s\t" /* tailmatch */
  1340. "%s\t" /* path */
  1341. "%s\t" /* secure */
  1342. "%" FMT_OFF_T "\t" /* expires */
  1343. "%s\t" /* name */
  1344. "%s", /* value */
  1345. co->httponly ? "#HttpOnly_" : "",
  1346. /*
  1347. * Make sure all domains are prefixed with a dot if they allow
  1348. * tailmatching. This is Mozilla-style.
  1349. */
  1350. (co->tailmatch && co->domain && co->domain[0] != '.') ? "." : "",
  1351. co->domain ? co->domain : "unknown",
  1352. co->tailmatch ? "TRUE" : "FALSE",
  1353. co->path ? co->path : "/",
  1354. co->secure ? "TRUE" : "FALSE",
  1355. co->expires,
  1356. co->name,
  1357. co->value ? co->value : "");
  1358. }
  1359. /*
  1360. * cookie_output()
  1361. *
  1362. * Writes all internally known cookies to the specified file. Specify
  1363. * "-" as filename to write to stdout.
  1364. *
  1365. * The function returns non-zero on write failure.
  1366. */
  1367. static CURLcode cookie_output(struct Curl_easy *data,
  1368. struct CookieInfo *ci,
  1369. const char *filename)
  1370. {
  1371. FILE *out = NULL;
  1372. bool use_stdout = FALSE;
  1373. char *tempstore = NULL;
  1374. CURLcode error = CURLE_OK;
  1375. if(!ci)
  1376. /* no cookie engine alive */
  1377. return CURLE_OK;
  1378. /* at first, remove expired cookies */
  1379. remove_expired(ci);
  1380. if(!strcmp("-", filename)) {
  1381. /* use stdout */
  1382. out = stdout;
  1383. use_stdout = TRUE;
  1384. }
  1385. else {
  1386. error = Curl_fopen(data, filename, &out, &tempstore);
  1387. if(error)
  1388. goto error;
  1389. }
  1390. fputs("# Netscape HTTP Cookie File\n"
  1391. "# https://curl.se/docs/http-cookies.html\n"
  1392. "# This file was generated by libcurl! Edit at your own risk.\n\n",
  1393. out);
  1394. if(ci->numcookies) {
  1395. unsigned int i;
  1396. size_t nvalid = 0;
  1397. struct Cookie **array;
  1398. struct Curl_llist_node *n;
  1399. array = calloc(1, sizeof(struct Cookie *) * ci->numcookies);
  1400. if(!array) {
  1401. error = CURLE_OUT_OF_MEMORY;
  1402. goto error;
  1403. }
  1404. /* only sort the cookies with a domain property */
  1405. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1406. for(n = Curl_llist_head(&ci->cookielist[i]); n;
  1407. n = Curl_node_next(n)) {
  1408. struct Cookie *co = Curl_node_elem(n);
  1409. if(!co->domain)
  1410. continue;
  1411. array[nvalid++] = co;
  1412. }
  1413. }
  1414. qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
  1415. for(i = 0; i < nvalid; i++) {
  1416. char *format_ptr = get_netscape_format(array[i]);
  1417. if(!format_ptr) {
  1418. free(array);
  1419. error = CURLE_OUT_OF_MEMORY;
  1420. goto error;
  1421. }
  1422. fprintf(out, "%s\n", format_ptr);
  1423. free(format_ptr);
  1424. }
  1425. free(array);
  1426. }
  1427. if(!use_stdout) {
  1428. fclose(out);
  1429. out = NULL;
  1430. if(tempstore && Curl_rename(tempstore, filename)) {
  1431. unlink(tempstore);
  1432. error = CURLE_WRITE_ERROR;
  1433. goto error;
  1434. }
  1435. }
  1436. /*
  1437. * If we reach here we have successfully written a cookie file so there is
  1438. * no need to inspect the error, any error case should have jumped into the
  1439. * error block below.
  1440. */
  1441. free(tempstore);
  1442. return CURLE_OK;
  1443. error:
  1444. if(out && !use_stdout)
  1445. fclose(out);
  1446. free(tempstore);
  1447. return error;
  1448. }
  1449. static struct curl_slist *cookie_list(struct Curl_easy *data)
  1450. {
  1451. struct curl_slist *list = NULL;
  1452. struct curl_slist *beg;
  1453. unsigned int i;
  1454. struct Curl_llist_node *n;
  1455. if(!data->cookies || (data->cookies->numcookies == 0))
  1456. return NULL;
  1457. for(i = 0; i < COOKIE_HASH_SIZE; i++) {
  1458. for(n = Curl_llist_head(&data->cookies->cookielist[i]); n;
  1459. n = Curl_node_next(n)) {
  1460. struct Cookie *c = Curl_node_elem(n);
  1461. char *line;
  1462. if(!c->domain)
  1463. continue;
  1464. line = get_netscape_format(c);
  1465. if(!line) {
  1466. curl_slist_free_all(list);
  1467. return NULL;
  1468. }
  1469. beg = Curl_slist_append_nodup(list, line);
  1470. if(!beg) {
  1471. free(line);
  1472. curl_slist_free_all(list);
  1473. return NULL;
  1474. }
  1475. list = beg;
  1476. }
  1477. }
  1478. return list;
  1479. }
  1480. struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
  1481. {
  1482. struct curl_slist *list;
  1483. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1484. list = cookie_list(data);
  1485. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1486. return list;
  1487. }
  1488. void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
  1489. {
  1490. CURLcode res;
  1491. if(data->set.str[STRING_COOKIEJAR]) {
  1492. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1493. /* if we have a destination file for all the cookies to get dumped to */
  1494. res = cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]);
  1495. if(res)
  1496. infof(data, "WARNING: failed to save cookies in %s: %s",
  1497. data->set.str[STRING_COOKIEJAR], curl_easy_strerror(res));
  1498. }
  1499. else {
  1500. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1501. }
  1502. if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
  1503. Curl_cookie_cleanup(data->cookies);
  1504. data->cookies = NULL;
  1505. }
  1506. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1507. }
  1508. #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */