cookie.c 49 KB

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