cookie.c 50 KB

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