cookie.c 50 KB

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