cookie.c 49 KB

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