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