2
0

cookie.c 50 KB

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