cookie.c 48 KB

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