cookie.c 50 KB

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