cookie.c 47 KB

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