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 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
|
/* CFStream.c
Copyright (c) 2000-2019, Apple Inc. and the Swift project authors
Portions Copyright (c) 2014-2019, Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
Responsibility: John Iarocci
*/
#include "CFRuntime.h"
#include "CFNumber.h"
#include <string.h>
#include "CFStreamInternal.h"
#include "CFRuntime_Internal.h"
#include <stdio.h>
#if TARGET_OS_WIN32
#include <process.h>
#endif
#if defined(DEBUG)
#include <assert.h>
#endif
enum {
MIN_STATUS_CODE_BIT = 0,
// ..status bits...
MAX_STATUS_CODE_BIT = 4,
CONSTANT_CALLBACKS = 5,
CALLING_CLIENT = 6, // MUST remain 6 since it's value is used elsewhere.
HAVE_CLOSED = 7,
// Values above used to be defined and others may rely on their values
// Values below should not matter if they are re-ordered or shift
SHARED_SOURCE
};
/* CALLING_CLIENT really determines whether stream events will be sent to the client immediately, or posted for the next time through the runloop. Since the client may not be prepared for re-entrancy, we must always set/clear this bit around public entry points. -- REW, 9/5/2001
Also, CALLING_CLIENT is now used from CFFilteredStream.c (which has a copy of the #define above). Really gross. We should find a way to avoid that.... -- REW, 3/27/2002 */
// Used in CFNetwork too
/* sSharesSources holds two mappings, one the inverse of the other, between a stream and the
RunLoop+RunLoopMode pair that it's scheduled in. If the stream is scheduled in more than
one loop or mode, it can't share RunLoopSources with others, and is not in this dict.
*/
static CFLock_t sSourceLock = CFLockInit;
static CFMutableDictionaryRef sSharedSources = NULL;
// Just reads the bits, for those cases where we don't want to go through any callback checking
#define __CFStreamGetStatus(x) __CFBitfieldGetValue((x)->flags, MAX_STATUS_CODE_BIT, MIN_STATUS_CODE_BIT)
CF_PRIVATE CFStreamStatus _CFStreamGetStatus(struct _CFStream *stream);
static Boolean _CFStreamRemoveRunLoopAndModeFromArray(CFMutableArrayRef runLoopsAndModes, CFRunLoopRef rl, CFStringRef mode);
static void _wakeUpRunLoop(struct _CFStream *stream);
CF_INLINE void checkRLMArray(CFArrayRef arr)
{
#if defined(DEBUG)
assert(arr == NULL || (CFArrayGetCount(arr) % 2) == 0);
#endif
}
CF_INLINE void _CFStreamLock(struct _CFStream* stream) {
__CFLock(&stream->streamLock);
}
CF_INLINE void _CFStreamUnlock(struct _CFStream* stream) {
__CFUnlock(&stream->streamLock);
}
CF_INLINE CFRunLoopSourceRef _CFStreamCopySource(struct _CFStream* stream) {
CFRunLoopSourceRef source = NULL;
if (stream) {
_CFStreamLock(stream);
if (stream->client)
source = stream->client->rlSource;
if (source)
CFRetain(source);
_CFStreamUnlock(stream);
}
return source;
}
CF_INLINE void _CFStreamSetSource(struct _CFStream* stream, CFRunLoopSourceRef source, Boolean invalidateOldSource) {
#if __HAS_DISPATCH__
CFRunLoopSourceRef oldSource = NULL;
if (stream) {
_CFStreamLock(stream);
if (stream->client) {
oldSource = stream->client->rlSource;
if (oldSource != NULL)
CFRetain(oldSource);
stream->client->rlSource = source;
if (source != NULL)
CFRetain(source);
}
_CFStreamUnlock(stream);
}
if (oldSource) {
// Lose our extra retain
CFRelease(oldSource);
if (invalidateOldSource)
CFRunLoopSourceInvalidate(oldSource);
// And lose the one that held it in our stream as well
CFRelease(oldSource);
}
#endif
}
CF_INLINE const struct _CFStreamCallBacks *_CFStreamGetCallBackPtr(struct _CFStream *stream) {
return stream->callBacks;
}
CF_INLINE void _CFStreamSetStatusCode(struct _CFStream *stream, CFStreamStatus newStatus) {
CFStreamStatus status = __CFStreamGetStatus(stream);
if (((status != kCFStreamStatusClosed) && (status != kCFStreamStatusError)) ||
((status == kCFStreamStatusClosed) && (newStatus == kCFStreamStatusError)))
{
__CFBitfieldSetValue(stream->flags, MAX_STATUS_CODE_BIT, MIN_STATUS_CODE_BIT, newStatus);
}
}
CF_INLINE void _CFStreamScheduleEvent(struct _CFStream *stream, CFStreamEventType event) {
#if __HAS_DISPATCH__
if (stream->client && (stream->client->when & event)) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
stream->client->whatToSignal |= event;
CFRunLoopSourceSignal(source);
CFRelease(source);
_wakeUpRunLoop(stream);
}
}
#endif
}
CF_INLINE void _CFStreamSetStreamError(struct _CFStream *stream, CFStreamError *err) {
if (!stream->error) {
stream->error = (CFErrorRef)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(CFStreamError), 0);
}
memmove((void *)stream->error, err, sizeof(CFStreamError));
}
static CFStringRef __CFStreamCopyDescription(CFTypeRef cf) {
struct _CFStream *stream = (struct _CFStream *)cf;
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
CFStringRef contextDescription;
CFStringRef desc;
if (cb->copyDescription) {
if (cb->version == 0) {
contextDescription = ((CFStringRef(*)(void *))cb->copyDescription)(_CFStreamGetInfoPointer(stream));
} else {
contextDescription = cb->copyDescription(stream, _CFStreamGetInfoPointer(stream));
}
} else {
contextDescription = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("info = %p"), _CFStreamGetInfoPointer(stream));
}
if (CFGetTypeID(cf) == _kCFRuntimeIDCFReadStream) {
desc = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("<CFReadStream %p>{%@}"), stream, contextDescription);
} else {
desc = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("<CFWriteStream %p>{%@}"), stream, contextDescription);
}
CFRelease(contextDescription);
return desc;
}
static void _CFStreamDetachSource(struct _CFStream* stream) {
if (stream && stream->client && stream->client->rlSource) {
if (!__CFBitIsSet(stream->flags, SHARED_SOURCE)) {
_CFStreamSetSource(stream, NULL, TRUE);
}
else {
CFArrayRef runLoopAndSourceKey;
CFMutableArrayRef list;
CFIndex count;
CFIndex i;
__CFLock(&sSourceLock);
runLoopAndSourceKey = (CFArrayRef)CFDictionaryGetValue(sSharedSources, stream);
list = (CFMutableArrayRef)CFDictionaryGetValue(sSharedSources, runLoopAndSourceKey);
count = CFArrayGetCount(list);
i = CFArrayGetFirstIndexOfValue(list, CFRangeMake(0, count), stream);
if (i != kCFNotFound) {
CFArrayRemoveValueAtIndex(list, i);
count--;
}
CFAssert(CFArrayGetFirstIndexOfValue(list, CFRangeMake(0, CFArrayGetCount(list)), stream) == kCFNotFound, __kCFLogAssertion, "CFStreamClose: stream found twice in its shared source's list");
#if __HAS_DISPATCH__
if (count == 0) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopRemoveSource((CFRunLoopRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 0), source, (CFStringRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 1));
CFRelease(source);
}
CFDictionaryRemoveValue(sSharedSources, runLoopAndSourceKey);
}
#endif
CFDictionaryRemoveValue(sSharedSources, stream);
_CFStreamSetSource(stream, NULL, count == 0);
__CFBitClear(stream->flags, SHARED_SOURCE);
__CFUnlock(&sSourceLock);
}
}
}
CF_PRIVATE void _CFStreamClose(struct _CFStream *stream) {
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (status == kCFStreamStatusNotOpen || status == kCFStreamStatusClosed || (status == kCFStreamStatusError && __CFBitIsSet(stream->flags, HAVE_CLOSED))) {
// Stream is not open from the client's perspective; do not callout and do not update our status to "closed"
return;
}
if (! __CFBitIsSet(stream->flags, HAVE_CLOSED)) {
__CFBitSet(stream->flags, HAVE_CLOSED);
__CFBitSet(stream->flags, CALLING_CLIENT);
if (cb->close) {
cb->close(stream, _CFStreamGetInfoPointer(stream));
}
if (stream->client) {
_CFStreamDetachSource(stream);
}
_CFStreamSetStatusCode(stream, kCFStreamStatusClosed);
__CFBitClear(stream->flags, CALLING_CLIENT);
}
}
//static int numStreamInstances = 0;
static void __CFStreamDeallocate(CFTypeRef cf) {
struct _CFStream *stream = (struct _CFStream *)cf;
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
CFAllocatorRef alloc = CFGetAllocator(stream);
// numStreamInstances --;
// Close the stream
_CFStreamClose(stream);
if (stream->client) {
CFStreamClientContext *cbContext;
cbContext = &(stream->client->cbContext);
if (cbContext->info && cbContext->release) {
cbContext->release(cbContext->info);
}
if (stream->client->runLoopsAndModes) {
CFRelease(stream->client->runLoopsAndModes);
}
CFAllocatorDeallocate(alloc, stream->client);
stream->client = NULL; // Just in case finalize, below, calls back in to us
}
if (cb && cb->finalize) {
if (cb->version == 0) {
((void(*)(void *))cb->finalize)(_CFStreamGetInfoPointer(stream));
} else {
cb->finalize(stream, _CFStreamGetInfoPointer(stream));
}
}
if (stream->error) {
if (cb && cb->version < 2) {
CFAllocatorDeallocate(alloc, (void *)stream->error);
} else {
CFRelease(stream->error);
}
}
if (!__CFBitIsSet(stream->flags, CONSTANT_CALLBACKS)) {
CFAllocatorDeallocate(alloc, (void *)stream->callBacks);
}
if (stream->previousRunloopsAndModes) {
CFRelease(stream->previousRunloopsAndModes);
stream->previousRunloopsAndModes = NULL;
}
#if __HAS_DISPATCH__
if (stream->queue) {
dispatch_release(stream->queue);
stream->queue = NULL;
}
#endif
}
const CFRuntimeClass __CFReadStreamClass = {
0,
"CFReadStream",
NULL, // init
NULL, // copy
__CFStreamDeallocate,
NULL,
NULL,
NULL, // copyHumanDesc
__CFStreamCopyDescription
};
const CFRuntimeClass __CFWriteStreamClass = {
0,
"CFWriteStream",
NULL, // init
NULL, // copy
__CFStreamDeallocate,
NULL,
NULL,
NULL, // copyHumanDesc
__CFStreamCopyDescription
};
CONST_STRING_DECL(kCFStreamPropertySocketNativeHandle, "kCFStreamPropertySocketNativeHandle")
CONST_STRING_DECL(kCFStreamPropertySocketRemoteHostName, "kCFStreamPropertySocketRemoteHostName")
CONST_STRING_DECL(kCFStreamPropertySocketRemotePortNumber, "kCFStreamPropertySocketRemotePortNumber")
CONST_STRING_DECL(kCFStreamPropertyDataWritten, "kCFStreamPropertyDataWritten")
CONST_STRING_DECL(kCFStreamPropertyAppendToFile, "kCFStreamPropertyAppendToFile")
CF_EXPORT CFTypeID CFReadStreamGetTypeID(void) {
return _kCFRuntimeIDCFReadStream;
}
CF_EXPORT CFTypeID CFWriteStreamGetTypeID(void) {
return _kCFRuntimeIDCFWriteStream;
}
static struct _CFStream *_CFStreamCreate(CFAllocatorRef allocator, Boolean isReadStream) {
struct _CFStream *newStream = (struct _CFStream *)_CFRuntimeCreateInstance(allocator, isReadStream ? _kCFRuntimeIDCFReadStream : _kCFRuntimeIDCFWriteStream, _CFSTREAM_SIZE, NULL);
if (newStream) {
_CFStreamSetStatusCode(newStream, kCFStreamStatusNotOpen);
newStream->streamLock = CFLockInit;
}
return newStream;
}
CF_EXPORT void* _CFStreamGetInfoPointer(struct _CFStream* stream) {
return stream == NULL? NULL : stream->info;
}
CF_PRIVATE struct _CFStream *_CFStreamCreateWithConstantCallbacks(CFAllocatorRef alloc, void *info, const struct _CFStreamCallBacks *cb, Boolean isReading) {
struct _CFStream *newStream;
if (cb->version != 1) return NULL;
newStream = _CFStreamCreate(alloc, isReading);
if (newStream) {
__CFBitSet(newStream->flags, CONSTANT_CALLBACKS);
newStream->callBacks = cb;
if (cb->create) {
newStream->info = cb->create(newStream, info);
} else {
newStream->info = info;
}
}
return newStream;
}
CF_EXPORT CFReadStreamRef CFReadStreamCreate(CFAllocatorRef alloc, const CFReadStreamCallBacks *callbacks, void *info) {
struct _CFStream *newStream = _CFStreamCreate(alloc, TRUE);
struct _CFStreamCallBacks *cb;
if (!newStream) return NULL;
cb = (struct _CFStreamCallBacks *)CFAllocatorAllocate(alloc, sizeof(struct _CFStreamCallBacks), 0);
if (!cb) {
CFRelease(newStream);
return NULL;
}
if (callbacks->version == 0) {
CFReadStreamCallBacksV0 *cbV0 = (CFReadStreamCallBacksV0 *)callbacks;
CFStreamClientContext *ctxt = (CFStreamClientContext *)info;
newStream->info = ctxt->retain ? (void *)ctxt->retain(ctxt->info) : ctxt->info;
cb->version = 0;
cb->create = (void *(*)(struct _CFStream *, void *))ctxt->retain;
cb->finalize = (void(*)(struct _CFStream *, void *))ctxt->release;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))ctxt->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))cbV0->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))cbV0->openCompleted;
cb->read = (CFIndex (*)(CFReadStreamRef, UInt8 *, CFIndex, CFErrorRef *, Boolean *, void *))cbV0->read;
cb->getBuffer = (const UInt8 *(*)(CFReadStreamRef, CFIndex, CFIndex *, CFErrorRef *, Boolean *, void *))cbV0->getBuffer;
cb->canRead = (Boolean (*)(CFReadStreamRef, CFErrorRef*, void*))cbV0->canRead;
cb->write = NULL;
cb->canWrite = NULL;
cb->close = (void (*)(struct _CFStream *, void *))cbV0->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))cbV0->copyProperty;
cb->setProperty = NULL;
cb->requestEvents = NULL;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV0->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV0->unschedule;
} else if (callbacks->version == 1) {
CFReadStreamCallBacksV1 *cbV1 = (CFReadStreamCallBacksV1 *)callbacks;
newStream->info = cbV1->create ? cbV1->create((CFReadStreamRef)newStream, info) : info;
cb->version = 1;
cb->create = (void *(*)(struct _CFStream *, void *))cbV1->create;
cb->finalize = (void(*)(struct _CFStream *, void *))cbV1->finalize;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))cbV1->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))cbV1->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))cbV1->openCompleted;
cb->read = (CFIndex (*)(CFReadStreamRef, UInt8 *, CFIndex, CFErrorRef *, Boolean *, void *))cbV1->read;
cb->getBuffer = (const UInt8 *(*)(CFReadStreamRef, CFIndex, CFIndex *, CFErrorRef *, Boolean *, void *))cbV1->getBuffer;
cb->canRead = (Boolean (*)(CFReadStreamRef, CFErrorRef*, void*))cbV1->canRead;
cb->write = NULL;
cb->canWrite = NULL;
cb->close = (void (*)(struct _CFStream *, void *))cbV1->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))cbV1->copyProperty;
cb->setProperty = (Boolean(*)(struct _CFStream *, CFStringRef, CFTypeRef, void *))cbV1->setProperty;
cb->requestEvents = (void(*)(struct _CFStream *, CFOptionFlags, void *))cbV1->requestEvents;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV1->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV1->unschedule;
} else {
newStream->info = callbacks->create ? callbacks->create((CFReadStreamRef)newStream, info) : info;
cb->version = 2;
cb->create = (void *(*)(struct _CFStream *, void *))callbacks->create;
cb->finalize = (void(*)(struct _CFStream *, void *))callbacks->finalize;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))callbacks->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))callbacks->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))callbacks->openCompleted;
cb->read = callbacks->read;
cb->getBuffer = callbacks->getBuffer;
cb->canRead = callbacks->canRead;
cb->write = NULL;
cb->canWrite = NULL;
cb->close = (void (*)(struct _CFStream *, void *))callbacks->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))callbacks->copyProperty;
cb->setProperty = (Boolean(*)(struct _CFStream *, CFStringRef, CFTypeRef, void *))callbacks->setProperty;
cb->requestEvents = (void(*)(struct _CFStream *, CFOptionFlags, void *))callbacks->requestEvents;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))callbacks->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))callbacks->unschedule;
}
newStream->callBacks = cb;
return (CFReadStreamRef)newStream;
}
CF_EXPORT CFWriteStreamRef CFWriteStreamCreate(CFAllocatorRef alloc, const CFWriteStreamCallBacks *callbacks, void *info) {
struct _CFStream *newStream = _CFStreamCreate(alloc, FALSE);
struct _CFStreamCallBacks *cb;
if (!newStream) return NULL;
cb = (struct _CFStreamCallBacks *)CFAllocatorAllocate(alloc, sizeof(struct _CFStreamCallBacks), 0);
if (!cb) {
CFRelease(newStream);
return NULL;
}
if (callbacks->version == 0) {
CFWriteStreamCallBacksV0 *cbV0 = (CFWriteStreamCallBacksV0 *)callbacks;
CFStreamClientContext *ctxt = (CFStreamClientContext *)info;
newStream->info = ctxt->retain ? (void *)ctxt->retain(ctxt->info) : ctxt->info;
cb->version = 0;
cb->create = (void *(*)(struct _CFStream *, void *))ctxt->retain;
cb->finalize = (void(*)(struct _CFStream *, void *))ctxt->release;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))ctxt->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))cbV0->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))cbV0->openCompleted;
cb->read = NULL;
cb->getBuffer = NULL;
cb->canRead = NULL;
cb->write = (CFIndex(*)(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength, CFErrorRef *error, void *info))cbV0->write;
cb->canWrite = (Boolean(*)(CFWriteStreamRef stream, CFErrorRef *error, void *info))cbV0->canWrite;
cb->close = (void (*)(struct _CFStream *, void *))cbV0->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))cbV0->copyProperty;
cb->setProperty = NULL;
cb->requestEvents = NULL;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV0->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV0->unschedule;
} else if (callbacks->version == 1) {
CFWriteStreamCallBacksV1 *cbV1 = (CFWriteStreamCallBacksV1 *)callbacks;
cb->version = 1;
newStream->info = cbV1->create ? cbV1->create((CFWriteStreamRef)newStream, info) : info;
cb->create = (void *(*)(struct _CFStream *, void *))cbV1->create;
cb->finalize = (void(*)(struct _CFStream *, void *))cbV1->finalize;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))cbV1->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))cbV1->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))cbV1->openCompleted;
cb->read = NULL;
cb->getBuffer = NULL;
cb->canRead = NULL;
cb->write = (CFIndex(*)(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength, CFErrorRef *error, void *info))cbV1->write;
cb->canWrite = (Boolean(*)(CFWriteStreamRef stream, CFErrorRef *error, void *info))cbV1->canWrite;
cb->close = (void (*)(struct _CFStream *, void *))cbV1->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))cbV1->copyProperty;
cb->setProperty = (Boolean (*)(struct _CFStream *, CFStringRef, CFTypeRef, void *))cbV1->setProperty;
cb->requestEvents = (void(*)(struct _CFStream *, CFOptionFlags, void *))cbV1->requestEvents;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV1->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))cbV1->unschedule;
} else {
cb->version = callbacks->version;
newStream->info = callbacks->create ? callbacks->create((CFWriteStreamRef)newStream, info) : info;
cb->create = (void *(*)(struct _CFStream *, void *))callbacks->create;
cb->finalize = (void(*)(struct _CFStream *, void *))callbacks->finalize;
cb->copyDescription = (CFStringRef(*)(struct _CFStream *, void *))callbacks->copyDescription;
cb->open = (Boolean(*)(struct _CFStream *, CFErrorRef *, Boolean *, void *))callbacks->open;
cb->openCompleted = (Boolean (*)(struct _CFStream *, CFErrorRef *, void *))callbacks->openCompleted;
cb->read = NULL;
cb->getBuffer = NULL;
cb->canRead = NULL;
cb->write = callbacks->write;
cb->canWrite = callbacks->canWrite;
cb->close = (void (*)(struct _CFStream *, void *))callbacks->close;
cb->copyProperty = (CFTypeRef (*)(struct _CFStream *, CFStringRef, void *))callbacks->copyProperty;
cb->setProperty = (Boolean (*)(struct _CFStream *, CFStringRef, CFTypeRef, void *))callbacks->setProperty;
cb->requestEvents = (void(*)(struct _CFStream *, CFOptionFlags, void *))callbacks->requestEvents;
cb->schedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))callbacks->schedule;
cb->unschedule = (void (*)(struct _CFStream *, CFRunLoopRef, CFStringRef, void *))callbacks->unschedule;
}
newStream->callBacks = cb;
return (CFWriteStreamRef)newStream;
}
static void _signalEventSync(struct _CFStream* stream)
{
CFOptionFlags eventMask;
__CFBitSet(stream->flags, CALLING_CLIENT);
_CFStreamLock(stream);
struct _CFStreamClient* client = stream->client;
if (client == NULL || stream->client->whatToSignal == 0) {
stream->pendingEventsToDeliver = false;
_CFStreamUnlock(stream);
} else {
void* info = NULL;
void (*release) (void*) = NULL;
void (*cb)(struct _CFStream *, CFStreamEventType, void *) = client == NULL? NULL : client->cb;
if (stream->client->cbContext.retain == NULL)
info = stream->client->cbContext.info;
else {
info = stream->client->cbContext.retain(stream->client->cbContext.info);
release = stream->client->cbContext.release;
}
CFOptionFlags whatToSignal = stream->client->whatToSignal;
stream->client->whatToSignal = 0;
stream->pendingEventsToDeliver = false;
_CFStreamUnlock(stream);
for (eventMask = 1; eventMask <= whatToSignal; eventMask = eventMask << 1) {
_CFStreamLock(stream);
Boolean shouldSignal = ((eventMask & whatToSignal) && stream->client && (stream->client->when & eventMask));
_CFStreamUnlock(stream);
if (shouldSignal && client) {
cb(stream, eventMask, info);
/* What happens if the callback sets the client to NULL? We're in a loop here... Hmm. */
/* After writing that comment, I see: <rdar://problem/6793636> CFReadStreamSetClient(..., NULL) unsafely releases info pointer immediately */
/* Of note, when the stream callbacks are set to to NULL, we're re-initalized so as not to receive more events, so we
* should break pout of this loop */
}
}
if (release)
(*release) (info);
}
__CFBitClear(stream->flags, CALLING_CLIENT);
}
#if __HAS_DISPATCH__
static void _signalEventQueue(dispatch_queue_t q, struct _CFStream* stream)
{
CFRetain(stream);
dispatch_async(q, ^{
_signalEventSync(stream);
CFRelease(stream);
});
}
#endif
static void _cfstream_solo_signalEventSync(void* info)
{
CFTypeID typeID = CFGetTypeID((CFTypeRef) info);
if (typeID != CFReadStreamGetTypeID() && typeID != CFWriteStreamGetTypeID()) {
CFLog(__kCFLogAssertion, CFSTR("Expected a read or write stream for %p"), info);
#if defined(DEBUG)
abort();
#endif
} else {
struct _CFStream* stream = (struct _CFStream*) info;
_CFStreamLock(stream);
if (stream->pendingEventsToDeliver) {
_CFStreamUnlock(stream);
} else {
#if __HAS_DISPATCH__
dispatch_queue_t queue = stream->queue;
if (queue) dispatch_retain(queue);
CFRetain(stream);
_CFStreamUnlock(stream);
/* Since the array version holds a retain, we do it here as well, as opposed to taking a second retain in the client callback */
if (queue == 0)
_signalEventSync(stream);
else {
_signalEventQueue(queue, stream);
dispatch_release(queue);
}
CFRelease(stream);
#else
_signalEventSync(stream);
#endif
}
}
}
static void _cfstream_shared_signalEventSync(void* info)
{
CFTypeID typeID = CFGetTypeID((CFTypeRef) info);
if (typeID != CFArrayGetTypeID()) {
CFLog(__kCFLogAssertion, CFSTR("Expected an array for %p"), info);
#if defined(DEBUG)
abort();
#endif
} else {
CFMutableArrayRef list = (CFMutableArrayRef) info;
CFIndex c, i;
#if __HAS_DISPATCH__
dispatch_queue_t queue = 0;
#endif
struct _CFStream* stream = NULL;
__CFLock(&sSourceLock);
/* Looks like, we grab the first stream that wants an event... */
/* Note that I grab an extra retain when I pull out the stream here... */
c = CFArrayGetCount(list);
for (i = 0; i < c; i++) {
struct _CFStream* s = (struct _CFStream*)CFArrayGetValueAtIndex(list, i);
if (s->pendingEventsToDeliver) {
continue;
}
if (s->client->whatToSignal) {
stream = s;
CFRetain(stream);
#if __HAS_DISPATCH__
queue = stream->queue;
if (queue) dispatch_retain(queue);
#endif
stream->pendingEventsToDeliver = true;
break;
}
}
#if __HAS_DISPATCH__
/* And then we also signal any other streams in this array so that we get them next go? */
for (; i < c; i++) {
struct _CFStream* s = (struct _CFStream*)CFArrayGetValueAtIndex(list, i);
if (s == stream) {
continue;
}
if (s->pendingEventsToDeliver) {
continue;
}
if (s->client->whatToSignal) {
CFRunLoopSourceRef source = _CFStreamCopySource(s);
if (source) {
CFRunLoopSourceSignal(source);
CFRelease(source);
}
break;
}
}
#endif
__CFUnlock(&sSourceLock);
/* We're sitting here now, possibly with a stream that needs to be processed by the common routine */
if (stream) {
#if __HAS_DISPATCH__
if (queue == 0)
_signalEventSync(stream);
else {
_signalEventQueue(queue, stream);
dispatch_release(queue);
}
#else
_signalEventSync(stream);
#endif
/* Lose our extra retain */
CFRelease(stream);
}
}
}
static CFArrayRef _CFStreamCopyRunLoopsAndModes(struct _CFStream *stream)
{
CFArrayRef result = NULL;
if (stream && stream->client) {
_CFStreamLock(stream);
if (stream->client->runLoopsAndModes) {
result = CFArrayCreateCopy(CFGetAllocator(stream), stream->client->runLoopsAndModes);
}
checkRLMArray(result);
_CFStreamUnlock(stream);
}
return result;
}
static void _wakeUpRunLoop(struct _CFStream *stream) {
CFArrayRef rlArray = _CFStreamCopyRunLoopsAndModes(stream);
if (rlArray) {
CFIndex cnt = CFArrayGetCount(rlArray);
CFRunLoopRef rl = NULL;
if (cnt == 2) {
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(rlArray, 0);
} else if (cnt > 2) {
CFIndex idx;
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(rlArray, 0);
for (idx = 2; NULL != rl && idx < cnt; idx+=2) {
CFRunLoopRef value = (CFRunLoopRef)CFArrayGetValueAtIndex(rlArray, idx);
if (value != rl) rl = NULL;
}
if (NULL == rl) { /* more than one different rl, so we must pick one */
for (idx = 0; idx < cnt; idx+=2) {
CFRunLoopRef value = (CFRunLoopRef)CFArrayGetValueAtIndex(rlArray, idx);
CFStringRef currentMode = CFRunLoopCopyCurrentMode(value);
if (NULL != currentMode && CFEqual(currentMode, CFArrayGetValueAtIndex(rlArray, idx+1)) && CFRunLoopIsWaiting(value)) {
CFRelease(currentMode);
rl = value;
break;
}
if (NULL != currentMode) CFRelease(currentMode);
}
if (NULL == rl) { /* didn't choose one above, so choose first */
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(rlArray, 0);
}
}
}
if (NULL != rl) {
CFRunLoopWakeUp(rl);
}
CFRelease(rlArray);
}
}
CF_PRIVATE void _CFStreamSignalEvent(struct _CFStream *stream, CFStreamEventType event, CFErrorRef error, Boolean synchronousAllowed) {
// Update our internal status; we must use the primitive __CFStreamGetStatus(), because CFStreamGetStatus() calls us, and we can end up in an infinite loop.
CFStreamStatus status = __CFStreamGetStatus(stream);
// Sanity check the event
if (status == kCFStreamStatusNotOpen) {
// No events allowed; this is almost certainly a bug in the stream's implementation
CFLog(__kCFLogAssertion, CFSTR("Stream %p is sending an event before being opened"), stream);
event = 0;
} else if (status == kCFStreamStatusClosed || status == kCFStreamStatusError) {
// no further events are allowed
event = 0;
} else if (status == kCFStreamStatusAtEnd) {
// Only error events are allowed
event &= kCFStreamEventErrorOccurred;
} else if (status != kCFStreamStatusOpening) {
// cannot send open completed; that happened already
event &= ~kCFStreamEventOpenCompleted;
}
// Change status if appropriate
if (event & kCFStreamEventOpenCompleted && status == kCFStreamStatusOpening) {
_CFStreamSetStatusCode(stream, kCFStreamStatusOpen);
}
if (event & kCFStreamEventEndEncountered && status < kCFStreamStatusAtEnd) {
_CFStreamSetStatusCode(stream, kCFStreamStatusAtEnd);
}
if (event & kCFStreamEventErrorOccurred) {
if (_CFStreamGetCallBackPtr(stream)->version < 2) {
_CFStreamSetStreamError(stream, (CFStreamError *)error);
} else {
CFAssert(error, __kCFLogAssertion, "CFStream: kCFStreamEventErrorOccurred signalled, but error is NULL!");
CFRetain(error);
if (stream->error) CFRelease(stream->error);
stream->error = error;
}
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
}
#if __HAS_DISPATCH__
// Now signal any pertinent event - if not already signaled
if (stream->client && (stream->client->when & event) != 0 && (stream->client->whatToSignal & event) == 0) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
Boolean signalNow = FALSE;
stream->client->whatToSignal |= event;
if (synchronousAllowed && !__CFBitIsSet(stream->flags, CALLING_CLIENT)) {
CFRunLoopRef rl = CFRunLoopGetCurrent();
CFStringRef mode = CFRunLoopCopyCurrentMode(rl);
if (mode) {
if (CFRunLoopContainsSource(rl, source, mode))
signalNow = TRUE;
}
if (mode)
CFRelease(mode);
}
if (signalNow) {
// Can call out safely right now
_cfstream_solo_signalEventSync(stream);
} else {
// Schedule for later delivery
if (source) {
CFRunLoopSourceSignal(source);
}
_wakeUpRunLoop(stream);
}
CFRelease(source);
}
}
#endif
}
CF_PRIVATE CFStreamStatus _CFStreamGetStatus(struct _CFStream *stream) {
CFStreamStatus status = __CFStreamGetStatus(stream);
// Status code just represents the value when last we checked; if we were in the middle of doing work at that time, we need to find out if the work has completed, now. If we find out about a status change, we need to inform the client as well, so we call _CFStreamSignalEvent. This will take care of updating our internal status correctly, too.
__CFBitSet(stream->flags, CALLING_CLIENT);
if (status == kCFStreamStatusOpening) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (cb->openCompleted) {
Boolean isComplete;
if (cb->version < 2) {
CFStreamError err = {0, 0};
isComplete = ((_CFStreamCBOpenCompletedV1)(cb->openCompleted))(stream, &err, _CFStreamGetInfoPointer(stream));
if (err.error != 0) _CFStreamSetStreamError(stream, &err);
} else {
isComplete = cb->openCompleted(stream, &(stream->error), _CFStreamGetInfoPointer(stream));
}
if (isComplete) {
if (!stream->error) {
status = kCFStreamStatusOpen;
} else {
status = kCFStreamStatusError;
}
_CFStreamSetStatusCode(stream, status);
if (status == kCFStreamStatusOpen) {
_CFStreamScheduleEvent(stream, kCFStreamEventOpenCompleted);
} else {
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
}
}
}
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return status;
}
CF_EXPORT CFStreamStatus CFReadStreamGetStatus(CFReadStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFStreamStatus, (NSInputStream *)stream, streamStatus);
return _CFStreamGetStatus((struct _CFStream *)stream);
}
CF_EXPORT CFStreamStatus CFWriteStreamGetStatus(CFWriteStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFStreamStatus, (NSOutputStream *)stream, streamStatus);
return _CFStreamGetStatus((struct _CFStream *)stream);
}
static CFStreamError _CFStreamGetStreamError(struct _CFStream *stream) {
CFStreamError result;
if (!stream->error) {
result.error = 0;
result.domain = 0;
} else if (_CFStreamGetCallBackPtr(stream)->version < 2) {
CFStreamError *streamError = (CFStreamError *)(stream->error);
result.error = streamError->error;
result.domain = streamError->domain;
} else {
result = _CFStreamErrorFromError(stream->error);
}
return result;
}
CF_EXPORT CFStreamError CFReadStreamGetError(CFReadStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFStreamError, (NSInputStream *)stream, _cfStreamError);
return _CFStreamGetStreamError((struct _CFStream *)stream);
}
CF_EXPORT CFStreamError CFWriteStreamGetError(CFWriteStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFStreamError, (NSOutputStream *)stream, _cfStreamError);
return _CFStreamGetStreamError((struct _CFStream *)stream);
}
static CFErrorRef _CFStreamCopyError(struct _CFStream *stream) {
if (!stream->error) {
return NULL;
} else if (_CFStreamGetCallBackPtr(stream)->version < 2) {
return _CFStreamCreateErrorFromStreamError(CFGetAllocator(stream), (CFStreamError *)(stream->error));
} else {
CFRetain(stream->error);
return stream->error;
}
}
CF_EXPORT CFErrorRef CFReadStreamCopyError(CFReadStreamRef stream) {
CF_OBJC_RETAINED_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFErrorRef, (NSInputStream *)stream, streamError);
return _CFStreamCopyError((struct _CFStream *)stream);
}
CF_EXPORT CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream) {
CF_OBJC_RETAINED_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFErrorRef, (NSOutputStream *)stream, streamError);
return _CFStreamCopyError((struct _CFStream *)stream);
}
CF_PRIVATE Boolean _CFStreamOpen(struct _CFStream *stream) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
Boolean success, openComplete;
if (_CFStreamGetStatus(stream) != kCFStreamStatusNotOpen) {
return FALSE;
}
__CFBitSet(stream->flags, CALLING_CLIENT);
_CFStreamSetStatusCode(stream, kCFStreamStatusOpening);
if (cb->open) {
if (cb->version < 2) {
CFStreamError err = {0, 0};
success = ((_CFStreamCBOpenV1)(cb->open))(stream, &err, &openComplete, _CFStreamGetInfoPointer(stream));
if (err.error != 0) _CFStreamSetStreamError(stream, &err);
} else {
success = cb->open(stream, &(stream->error), &openComplete, _CFStreamGetInfoPointer(stream));
}
} else {
success = TRUE;
openComplete = TRUE;
}
if (openComplete) {
if (success) {
// 2957690 - Guard against the possibility that the stream has already signalled itself in to a later state (like AtEnd)
if (__CFStreamGetStatus(stream) == kCFStreamStatusOpening) {
_CFStreamSetStatusCode(stream, kCFStreamStatusOpen);
}
_CFStreamScheduleEvent(stream, kCFStreamEventOpenCompleted);
} else {
#if TARGET_OS_WIN32
_CFStreamClose(stream);
#endif
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
}
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return success;
}
CF_EXPORT Boolean CFReadStreamOpen(CFReadStreamRef stream) {
if(CF_IS_OBJC(_kCFRuntimeIDCFReadStream, stream)) {
(void)CF_OBJC_CALLV((NSInputStream *)stream, open);
return TRUE;
}
return _CFStreamOpen((struct _CFStream *)stream);
}
CF_EXPORT Boolean CFWriteStreamOpen(CFWriteStreamRef stream) {
if(CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, stream)) {
(void)CF_OBJC_CALLV((NSOutputStream *)stream, open);
return TRUE;
}
return _CFStreamOpen((struct _CFStream *)stream);
}
CF_EXPORT void CFReadStreamClose(CFReadStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, void, (NSInputStream *)stream, close);
_CFStreamClose((struct _CFStream *)stream);
}
CF_EXPORT void CFWriteStreamClose(CFWriteStreamRef stream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, void, (NSOutputStream *)stream, close);
_CFStreamClose((struct _CFStream *)stream);
}
CF_EXPORT Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef readStream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, Boolean, (NSInputStream *)readStream, hasBytesAvailable);
struct _CFStream *stream = (struct _CFStream *)readStream;
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb;
if (status != kCFStreamStatusOpen && status != kCFStreamStatusReading) {
return FALSE;
}
cb = _CFStreamGetCallBackPtr(stream);
if (cb->canRead == NULL) {
return TRUE; // No way to know without trying....
} else {
Boolean result;
__CFBitSet(stream->flags, CALLING_CLIENT);
if (cb->version < 2) {
result = ((_CFStreamCBCanReadV1)(cb->canRead))((CFReadStreamRef)stream, _CFStreamGetInfoPointer(stream));
} else {
result = cb->canRead((CFReadStreamRef)stream, &(stream->error), _CFStreamGetInfoPointer(stream));
if (stream->error) {
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
}
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return result;
}
}
static void waitForOpen(struct _CFStream *stream);
CFIndex CFReadStreamRead(CFReadStreamRef readStream, UInt8 *buffer, CFIndex bufferLength) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFIndex, (NSInputStream *)readStream, read:(uint8_t *)buffer maxLength:(NSUInteger)bufferLength);
struct _CFStream *stream = (struct _CFStream *)readStream;
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (status == kCFStreamStatusOpening) {
__CFBitSet(stream->flags, CALLING_CLIENT);
waitForOpen(stream);
__CFBitClear(stream->flags, CALLING_CLIENT);
status = _CFStreamGetStatus(stream);
}
if (status != kCFStreamStatusOpen && status != kCFStreamStatusReading && status != kCFStreamStatusAtEnd) {
return -1;
} else if (status == kCFStreamStatusAtEnd) {
return 0;
} else {
Boolean atEOF;
CFIndex bytesRead;
__CFBitSet(stream->flags, CALLING_CLIENT);
if (stream->client) {
stream->client->whatToSignal &= ~kCFStreamEventHasBytesAvailable;
}
_CFStreamSetStatusCode(stream, kCFStreamStatusReading);
if (cb->version < 2) {
CFStreamError err = {0, 0};
bytesRead = ((_CFStreamCBReadV1)(cb->read))((CFReadStreamRef)stream, buffer, bufferLength, &err, &atEOF, _CFStreamGetInfoPointer(stream));
if (err.error != 0) _CFStreamSetStreamError(stream, &err);
} else {
bytesRead = cb->read((CFReadStreamRef)stream, buffer, bufferLength, &(stream->error), &atEOF, _CFStreamGetInfoPointer(stream));
}
if (stream->error) {
bytesRead = -1;
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
} else if (atEOF) {
_CFStreamSetStatusCode(stream, kCFStreamStatusAtEnd);
_CFStreamScheduleEvent(stream, kCFStreamEventEndEncountered);
} else {
_CFStreamSetStatusCode(stream, kCFStreamStatusOpen);
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return bytesRead;
}
}
CF_EXPORT const UInt8 *CFReadStreamGetBuffer(CFReadStreamRef readStream, CFIndex maxBytesToRead, CFIndex *numBytesRead) {
if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, readStream)) {
uint8_t *bufPtr = NULL;
Boolean gotBytes = (Boolean) CF_OBJC_CALLV((NSInputStream *)readStream, getBuffer:&bufPtr length:(NSUInteger *)numBytesRead);
if(gotBytes) {
return (const UInt8 *)bufPtr;
} else {
return NULL;
}
}
struct _CFStream *stream = (struct _CFStream *)readStream;
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
const UInt8 *buffer;
if (status == kCFStreamStatusOpening) {
__CFBitSet(stream->flags, CALLING_CLIENT);
waitForOpen(stream);
__CFBitClear(stream->flags, CALLING_CLIENT);
status = _CFStreamGetStatus(stream);
}
if (status != kCFStreamStatusOpen && status != kCFStreamStatusReading && status != kCFStreamStatusAtEnd) {
*numBytesRead = -1;
buffer = NULL;
} else if (status == kCFStreamStatusAtEnd || cb->getBuffer == NULL) {
*numBytesRead = 0;
buffer = NULL;
} else {
Boolean atEOF;
Boolean hadBytes = stream->client && (stream->client->whatToSignal & kCFStreamEventHasBytesAvailable);
__CFBitSet(stream->flags, CALLING_CLIENT);
if (hadBytes) {
stream->client->whatToSignal &= ~kCFStreamEventHasBytesAvailable;
}
_CFStreamSetStatusCode(stream, kCFStreamStatusReading);
if (cb->version < 2) {
CFStreamError err = {0, 0};
buffer = ((_CFStreamCBGetBufferV1)(cb->getBuffer))((CFReadStreamRef)stream, maxBytesToRead, numBytesRead, &err, &atEOF, _CFStreamGetInfoPointer(stream));
if (err.error != 0) _CFStreamSetStreamError(stream, &err);
} else {
buffer = cb->getBuffer((CFReadStreamRef)stream, maxBytesToRead, numBytesRead, &(stream->error), &atEOF, _CFStreamGetInfoPointer(stream));
}
if (stream->error) {
*numBytesRead = -1;
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
buffer = NULL;
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
} else if (atEOF) {
_CFStreamSetStatusCode(stream, kCFStreamStatusAtEnd);
_CFStreamScheduleEvent(stream, kCFStreamEventEndEncountered);
} else {
if (!buffer && hadBytes) {
stream->client->whatToSignal |= kCFStreamEventHasBytesAvailable;
}
_CFStreamSetStatusCode(stream, kCFStreamStatusOpen);
}
__CFBitClear(stream->flags, CALLING_CLIENT);
}
return buffer;
}
CF_EXPORT Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef writeStream) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, Boolean, (NSOutputStream *)writeStream, hasSpaceAvailable);
struct _CFStream *stream = (struct _CFStream *)writeStream;
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb;
if (status != kCFStreamStatusOpen && status != kCFStreamStatusWriting) {
return FALSE;
}
cb = _CFStreamGetCallBackPtr(stream);
if (cb->canWrite == NULL) {
return TRUE; // No way to know without trying....
} else {
Boolean result;
__CFBitSet(stream->flags, CALLING_CLIENT);
if (cb->version < 2) {
result = ((_CFStreamCBCanWriteV1)(cb->canWrite))((CFWriteStreamRef)stream, _CFStreamGetInfoPointer(stream));
} else {
result = cb->canWrite((CFWriteStreamRef)stream, &(stream->error), _CFStreamGetInfoPointer(stream));
if (stream->error) {
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
}
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return result;
}
}
CF_EXPORT CFIndex CFWriteStreamWrite(CFWriteStreamRef writeStream, const UInt8 *buffer, CFIndex bufferLength) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFIndex, (NSOutputStream *)writeStream, write:(const uint8_t *)buffer maxLength:(NSUInteger)bufferLength);
struct _CFStream *stream = (struct _CFStream *)writeStream;
CFStreamStatus status = _CFStreamGetStatus(stream);
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (status == kCFStreamStatusOpening) {
__CFBitSet(stream->flags, CALLING_CLIENT);
waitForOpen(stream);
__CFBitClear(stream->flags, CALLING_CLIENT);
status = _CFStreamGetStatus(stream);
}
if (status != kCFStreamStatusOpen && status != kCFStreamStatusWriting) {
return -1;
} else {
CFIndex result;
__CFBitSet(stream->flags, CALLING_CLIENT);
_CFStreamSetStatusCode(stream, kCFStreamStatusWriting);
if (stream->client) {
stream->client->whatToSignal &= ~kCFStreamEventCanAcceptBytes;
}
if (cb->version < 2) {
CFStreamError err = {0, 0};
result = ((_CFStreamCBWriteV1)(cb->write))((CFWriteStreamRef)stream, buffer, bufferLength, &err, _CFStreamGetInfoPointer(stream));
if (err.error) _CFStreamSetStreamError(stream, &err);
} else {
result = cb->write((CFWriteStreamRef)stream, buffer, bufferLength, &(stream->error), _CFStreamGetInfoPointer(stream));
}
if (stream->error) {
_CFStreamSetStatusCode(stream, kCFStreamStatusError);
_CFStreamScheduleEvent(stream, kCFStreamEventErrorOccurred);
} else if (result == 0) {
_CFStreamSetStatusCode(stream, kCFStreamStatusAtEnd);
_CFStreamScheduleEvent(stream, kCFStreamEventEndEncountered);
} else {
_CFStreamSetStatusCode(stream, kCFStreamStatusOpen);
}
__CFBitClear(stream->flags, CALLING_CLIENT);
return result;
}
}
CF_PRIVATE CFTypeRef _CFStreamCopyProperty(struct _CFStream *stream, CFStringRef propertyName) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (cb->copyProperty == NULL) {
return NULL;
} else {
CFTypeRef result;
__CFBitSet(stream->flags, CALLING_CLIENT);
result = cb->copyProperty(stream, propertyName, _CFStreamGetInfoPointer(stream));
__CFBitClear(stream->flags, CALLING_CLIENT);
return result;
}
}
CF_EXPORT CFTypeRef CFReadStreamCopyProperty(CFReadStreamRef stream, CFStringRef propertyName) {
CF_OBJC_RETAINED_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFTypeRef, (NSInputStream *)stream, propertyForKey:(NSString *)propertyName);
return _CFStreamCopyProperty((struct _CFStream *)stream, propertyName);
}
CF_EXPORT CFTypeRef CFWriteStreamCopyProperty(CFWriteStreamRef stream, CFStringRef propertyName) {
CF_OBJC_RETAINED_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFTypeRef, (NSOutputStream *)stream, propertyForKey:(NSString *)propertyName);
return _CFStreamCopyProperty((struct _CFStream *)stream, propertyName);
}
CF_PRIVATE Boolean _CFStreamSetProperty(struct _CFStream *stream, CFStringRef prop, CFTypeRef val) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (cb->setProperty == NULL) {
return FALSE;
} else {
Boolean result;
__CFBitSet(stream->flags, CALLING_CLIENT);
result = cb->setProperty(stream, prop, val, _CFStreamGetInfoPointer(stream));
__CFBitClear(stream->flags, CALLING_CLIENT);
return result;
}
}
CF_EXPORT
Boolean CFReadStreamSetProperty(CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, Boolean, (NSInputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName);
return _CFStreamSetProperty((struct _CFStream *)stream, propertyName, propertyValue);
}
CF_EXPORT
Boolean CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) {
CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, Boolean, (NSOutputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName);
return _CFStreamSetProperty((struct _CFStream *)stream, propertyName, propertyValue);
}
static void _initializeClient(struct _CFStream *stream) {
stream->client = (struct _CFStreamClient *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(struct _CFStreamClient), 0);
memset(stream->client, 0, sizeof(struct _CFStreamClient));
}
/* If we add a setClient callback to the concrete stream callbacks, we must set/clear CALLING_CLIENT around it */
CF_PRIVATE Boolean _CFStreamSetClient(struct _CFStream *stream, CFOptionFlags streamEvents, void (*clientCB)(struct _CFStream *, CFStreamEventType, void *), CFStreamClientContext *clientCallBackContext) {
Boolean removingClient = (streamEvents == kCFStreamEventNone || clientCB == NULL || clientCallBackContext == NULL);
if (removingClient) {
clientCB = NULL;
streamEvents = kCFStreamEventNone;
clientCallBackContext = NULL;
}
if (!stream->client) {
if (removingClient) {
// We have no client now, and we've been asked to add none???
return TRUE;
}
_initializeClient(stream);
if (!stream->client) {
// Asynch not supported
return FALSE;
}
}
if (stream->client->cb && stream->client->cbContext.release) {
stream->client->cbContext.release(stream->client->cbContext.info);
}
stream->client->cb = clientCB;
if (clientCallBackContext) {
stream->client->cbContext.version = clientCallBackContext->version;
stream->client->cbContext.retain = clientCallBackContext->retain;
stream->client->cbContext.release = clientCallBackContext->release;
stream->client->cbContext.copyDescription = clientCallBackContext->copyDescription;
stream->client->cbContext.info = (clientCallBackContext->retain && clientCallBackContext->info) ? clientCallBackContext->retain(clientCallBackContext->info) : clientCallBackContext->info;
} else {
stream->client->cbContext.retain = NULL;
stream->client->cbContext.release = NULL;
stream->client->cbContext.copyDescription = NULL;
stream->client->cbContext.info = NULL;
}
if (stream->client->when != streamEvents) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
stream->client->when = streamEvents;
if (cb->requestEvents) {
cb->requestEvents(stream, streamEvents, _CFStreamGetInfoPointer(stream));
}
}
return TRUE;
}
CF_EXPORT void _CFReadStreamInitialize(CFReadStreamRef readStream) {
struct _CFStream *stream = (struct _CFStream *)readStream;
if (stream) {
stream->streamLock = CFLockInit;
}
}
CF_EXPORT void _CFWriteStreamInitialize(CFWriteStreamRef writeStream) {
struct _CFStream *stream = (struct _CFStream *)writeStream;
if (stream) {
stream->streamLock = CFLockInit;
}
}
CF_EXPORT void _CFReadStreamDeallocate(CFReadStreamRef readStream) {
__CFStreamDeallocate(readStream);
}
CF_EXPORT void _CFWriteStreamDeallocate(CFWriteStreamRef writeStream) {
__CFStreamDeallocate(writeStream);
}
CF_EXPORT Boolean CFReadStreamSetClient(CFReadStreamRef readStream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext *clientContext) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)readStream)) {
NSInputStream* is = (NSInputStream*) readStream;
if ([is respondsToSelector:@selector(_setCFClientFlags:callback:context:)])
return [is _setCFClientFlags:streamEvents callback:clientCB context:clientContext];
else {
if (clientCB == NULL)
[is setDelegate:nil];
else {
_CFStreamDelegate* d = [[_CFStreamDelegate alloc] initWithStreamEvents:streamEvents callback:(void*) clientCB context:clientContext];
[is setDelegate:d];
objc_setAssociatedObject(is, (void *)[_CFStreamDelegate class], d, OBJC_ASSOCIATION_RETAIN);
[d release];
}
return true;
}
}
#endif
streamEvents &= ~kCFStreamEventCanAcceptBytes;
return _CFStreamSetClient((struct _CFStream *)readStream, streamEvents, (void (*)(struct _CFStream *, CFStreamEventType, void *))clientCB, clientContext);
}
CF_EXPORT Boolean CFWriteStreamSetClient(CFWriteStreamRef writeStream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext *clientContext) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)writeStream)) {
NSOutputStream* os = (NSOutputStream*) writeStream;
if ([os respondsToSelector:@selector(_setCFClientFlags:callback:context:)])
return [os _setCFClientFlags:streamEvents callback:clientCB context:clientContext];
else {
if (clientCB == NULL)
[os setDelegate:nil];
else {
_CFStreamDelegate* d = [[_CFStreamDelegate alloc] initWithStreamEvents:streamEvents callback:(void*) clientCB context:clientContext];
[os setDelegate:d];
objc_setAssociatedObject(os, (void *)[_CFStreamDelegate class], d, OBJC_ASSOCIATION_RETAIN);
[d release];
}
return true;
}
}
#endif
streamEvents &= ~kCFStreamEventHasBytesAvailable;
return _CFStreamSetClient((struct _CFStream *)writeStream, streamEvents, (void (*)(struct _CFStream *, CFStreamEventType, void *))clientCB, clientContext);
}
CF_INLINE void *_CFStreamGetClient(struct _CFStream *stream) {
if (stream->client) return stream->client->cbContext.info;
else return NULL;
}
CF_EXPORT void *_CFReadStreamGetClient(CFReadStreamRef readStream) {
return _CFStreamGetClient((struct _CFStream *)readStream);
}
CF_EXPORT void *_CFWriteStreamGetClient(CFWriteStreamRef writeStream) {
return _CFStreamGetClient((struct _CFStream *)writeStream);
}
CF_PRIVATE void _CFStreamScheduleWithRunLoop(struct _CFStream *stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
#if __HAS_DISPATCH__
if (! stream->client) {
_initializeClient(stream);
if (!stream->client) return; // we don't support asynch.
}
if (! stream->client->rlSource) {
/* No source, so we join the shared source group */
CFTypeRef a[] = { runLoop, runLoopMode };
CFArrayRef runLoopAndSourceKey = CFArrayCreate(kCFAllocatorSystemDefault, a, sizeof(a) / sizeof(a[0]), &kCFTypeArrayCallBacks);
__CFLock(&sSourceLock);
if (!sSharedSources)
sSharedSources = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFMutableArrayRef listOfStreamsSharingASource = (CFMutableArrayRef)CFDictionaryGetValue(sSharedSources, runLoopAndSourceKey);
if (listOfStreamsSharingASource) {
struct _CFStream* aStream = (struct _CFStream*) CFArrayGetValueAtIndex(listOfStreamsSharingASource, 0);
CFRunLoopSourceRef source = _CFStreamCopySource(aStream);
if (source) {
_CFStreamSetSource(stream, source, FALSE);
CFRelease(source);
}
CFRetain(listOfStreamsSharingASource);
}
else {
CFRunLoopSourceContext ctxt = {
0,
NULL,
CFRetain,
CFRelease,
(CFStringRef(*)(const void *))CFCopyDescription,
NULL,
NULL,
NULL,
NULL,
(void(*)(void *))_cfstream_shared_signalEventSync
};
listOfStreamsSharingASource = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);
CFDictionaryAddValue(sSharedSources, runLoopAndSourceKey, listOfStreamsSharingASource);
ctxt.info = listOfStreamsSharingASource;
CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorSystemDefault, 0, &ctxt);
_CFStreamSetSource(stream, source, FALSE);
CFRunLoopAddSource(runLoop, source, runLoopMode);
CFRelease(source);
}
CFArrayAppendValue(listOfStreamsSharingASource, stream);
CFDictionaryAddValue(sSharedSources, stream, runLoopAndSourceKey);
CFRelease(runLoopAndSourceKey);
CFRelease(listOfStreamsSharingASource);
__CFBitSet(stream->flags, SHARED_SOURCE);
__CFUnlock(&sSourceLock);
}
else if (__CFBitIsSet(stream->flags, SHARED_SOURCE)) {
/* We were sharing, but now we'll get our own source */
CFArrayRef runLoopAndSourceKey;
CFMutableArrayRef listOfStreamsSharingASource;
CFIndex count, i;
CFAllocatorRef alloc = CFGetAllocator(stream);
CFRunLoopSourceContext ctxt = {
0,
(void *)stream,
NULL, // Do not use CFRetain/CFRelease callbacks here; that will cause a retain loop
NULL, // Do not use CFRetain/CFRelease callbacks here; that will cause a retain loop
(CFStringRef(*)(const void *))CFCopyDescription,
NULL,
NULL,
NULL,
NULL,
(void(*)(void *))_cfstream_solo_signalEventSync
};
__CFLock(&sSourceLock);
runLoopAndSourceKey = (CFArrayRef)CFRetain((CFTypeRef)CFDictionaryGetValue(sSharedSources, stream));
listOfStreamsSharingASource = (CFMutableArrayRef)CFDictionaryGetValue(sSharedSources, runLoopAndSourceKey);
count = CFArrayGetCount(listOfStreamsSharingASource);
i = CFArrayGetFirstIndexOfValue(listOfStreamsSharingASource, CFRangeMake(0, count), stream);
if (i != kCFNotFound) {
CFArrayRemoveValueAtIndex(listOfStreamsSharingASource, i);
count--;
}
#if __HAS_DISPATCH__
if (count == 0) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopRemoveSource((CFRunLoopRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 0), source, (CFStringRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 1));
CFRelease(source);
}
CFDictionaryRemoveValue(sSharedSources, runLoopAndSourceKey);
}
#endif
CFDictionaryRemoveValue(sSharedSources, stream);
_CFStreamSetSource(stream, NULL, count == 0);
__CFBitClear(stream->flags, SHARED_SOURCE);
__CFUnlock(&sSourceLock);
CFRunLoopSourceRef source = CFRunLoopSourceCreate(alloc, 0, &ctxt);
_CFStreamSetSource(stream, source, FALSE);
CFRunLoopAddSource((CFRunLoopRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 0), source, (CFStringRef)CFArrayGetValueAtIndex(runLoopAndSourceKey, 1));
CFRelease(runLoopAndSourceKey);
CFRunLoopAddSource(runLoop, source, runLoopMode);
CFRelease(source);
} else {
/* We're not sharing, so just add the source to the rl & mode */
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopAddSource(runLoop, source, runLoopMode);
CFRelease(source);
}
}
_CFStreamLock(stream);
if (!stream->client->runLoopsAndModes) {
stream->client->runLoopsAndModes = CFArrayCreateMutable(CFGetAllocator(stream), 0, &kCFTypeArrayCallBacks);
}
CFArrayAppendValue(stream->client->runLoopsAndModes, runLoop);
CFArrayAppendValue(stream->client->runLoopsAndModes, runLoopMode);
checkRLMArray(stream->client->runLoopsAndModes);
_CFStreamUnlock(stream);
if (cb && cb->schedule) {
__CFBitSet(stream->flags, CALLING_CLIENT);
cb->schedule(stream, runLoop, runLoopMode, _CFStreamGetInfoPointer(stream));
__CFBitClear(stream->flags, CALLING_CLIENT);
}
/*
* If we've got events pending, we need to wake up and signal
*/
if (stream->client && stream->client->whatToSignal != 0) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopSourceSignal(source);
CFRelease(source);
_wakeUpRunLoop(stream);
}
}
#endif
}
CF_EXPORT void CFReadStreamScheduleWithRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)stream)) {
NSInputStream* is = (NSInputStream*) stream;
if ([is respondsToSelector:@selector(_scheduleInCFRunLoop:forMode:)])
[is _scheduleInCFRunLoop:runLoop forMode:runLoopMode];
else
[is scheduleInRunLoop:cfToNSRL(runLoop) forMode:(id) runLoopMode];
return;
}
#endif
_CFStreamScheduleWithRunLoop((struct _CFStream *)stream, runLoop, runLoopMode);
}
CF_EXPORT void CFWriteStreamScheduleWithRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)stream)) {
NSOutputStream* os = (NSOutputStream*) stream;
if ([os respondsToSelector:@selector(_scheduleInCFRunLoop:forMode:)])
[os _scheduleInCFRunLoop:runLoop forMode:runLoopMode];
else
[os scheduleInRunLoop:cfToNSRL(runLoop) forMode:(id) runLoopMode];
return;
}
#endif
_CFStreamScheduleWithRunLoop((struct _CFStream *)stream, runLoop, runLoopMode);
}
CF_PRIVATE void _CFStreamUnscheduleFromRunLoop(struct _CFStream *stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream);
if (!stream->client) return;
if (!stream->client->rlSource) return;
if (!__CFBitIsSet(stream->flags, SHARED_SOURCE)) {
#if __HAS_DISPATCH__
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopRemoveSource(runLoop, source, runLoopMode);
CFRelease(source);
}
#endif
} else {
CFArrayRef runLoopAndSourceKey;
CFMutableArrayRef list;
CFIndex count, i;
__CFLock(&sSourceLock);
runLoopAndSourceKey = (CFArrayRef)CFDictionaryGetValue(sSharedSources, stream);
list = (CFMutableArrayRef)CFDictionaryGetValue(sSharedSources, runLoopAndSourceKey);
count = CFArrayGetCount(list);
i = CFArrayGetFirstIndexOfValue(list, CFRangeMake(0, count), stream);
if (i != kCFNotFound) {
CFArrayRemoveValueAtIndex(list, i);
count--;
}
#if __HAS_DISPATCH__
if (count == 0) {
CFRunLoopSourceRef source = _CFStreamCopySource(stream);
if (source) {
CFRunLoopRemoveSource(runLoop, source, runLoopMode);
CFRelease(source);
}
CFDictionaryRemoveValue(sSharedSources, runLoopAndSourceKey);
}
#endif
CFDictionaryRemoveValue(sSharedSources, stream);
_CFStreamSetSource(stream, NULL, count == 0);
__CFBitClear(stream->flags, SHARED_SOURCE);
__CFUnlock(&sSourceLock);
}
_CFStreamLock(stream);
_CFStreamRemoveRunLoopAndModeFromArray(stream->client->runLoopsAndModes, runLoop, runLoopMode);
checkRLMArray(stream->client->runLoopsAndModes);
_CFStreamUnlock(stream);
if (cb && cb->unschedule) {
cb->unschedule(stream, runLoop, runLoopMode, _CFStreamGetInfoPointer(stream));
}
}
CF_EXPORT void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)stream)) {
NSInputStream* is = (NSInputStream*) stream;
if ([is respondsToSelector:@selector(_unscheduleFromCFRunLoop:forMode:)])
[is _unscheduleFromCFRunLoop:runLoop forMode:runLoopMode];
else
[is removeFromRunLoop:cfToNSRL(runLoop) forMode:(id) runLoopMode];
return;
}
#endif
_CFStreamUnscheduleFromRunLoop((struct _CFStream *)stream, runLoop, runLoopMode);
}
void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) {
#if defined(CFSTREAM_SUPPORTS_BRIDGING)
if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)stream)) {
NSOutputStream* os = (NSOutputStream*) stream;
if ([os respondsToSelector:@selector(_unscheduleFromCFRunLoop:forMode:)])
[os _unscheduleFromCFRunLoop:runLoop forMode:runLoopMode];
else
[os removeFromRunLoop:cfToNSRL(runLoop) forMode:(id) runLoopMode];
return;
}
#endif
_CFStreamUnscheduleFromRunLoop((struct _CFStream *)stream, runLoop, runLoopMode);
}
#if __HAS_DISPATCH__
#if !DEPLOYMENT_RUNTIME_OBJC
typedef _Atomic(int64_t) _OSAtomic_int64_t;
#if __has_extension(c_alignof) && __has_attribute(aligned)
typedef int64_t __attribute__((__aligned__(_Alignof(_OSAtomic_int64_t))))
OSAtomic_int64_aligned64_t;
#elif __has_attribute(aligned)
typedef int64_t __attribute__((__aligned__((sizeof(_OSAtomic_int64_t)))))
OSAtomic_int64_aligned64_t;
#else
typedef int64_t OSAtomic_int64_aligned64_t;
#endif
#endif
static CFRunLoopRef sLegacyRL = NULL;
#if TARGET_OS_MAC
static volatile OSAtomic_int64_aligned64_t sPerformCount = 0;
#endif
extern _CFThreadRef _CFMainPThread;
static void _perform(void* info)
{
#if TARGET_OS_MAC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
OSAtomicAdd64(1, &sPerformCount);
#pragma GCC diagnostic pop
#endif
}
static void* _legacyStreamRunLoop_workThread(void* arg)
{
_CFThreadSetName(pthread_self(), "com.apple.CFStream.LegacyThread");
sLegacyRL = CFRunLoopGetCurrent();
#if defined(LOG_STREAM)
fprintf(stderr, "Creating Schedulingset emulation thread. Runloop: %p\n", sLegacyRL);
#endif
CFStringRef s = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<< CFStreamLegacySource for Runloop %p >>"), sLegacyRL);
CFRunLoopSourceContext ctxt = {
0,
(void*) s,
CFRetain,
CFRelease,
CFCopyDescription,
CFEqual,
CFHash,
NULL,
NULL,
_perform
};
CFRunLoopSourceRef rls = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &ctxt);
CFRelease(s);
CFRunLoopAddSource(sLegacyRL, rls, kCFRunLoopDefaultMode);
CFRelease(rls);
dispatch_semaphore_signal(*(dispatch_semaphore_t*) arg);
arg = NULL;
while (true) {
SInt32 why = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1E30, true);
(void) why;
#if defined(LOG_STREAM)
switch (why) {
case kCFRunLoopRunFinished:
fprintf(stderr, "WOKE: kCFRunLoopRunFinished\n");
break;
case kCFRunLoopRunStopped:
fprintf(stderr, "WOKE: kCFRunLoopRunStopped\n");
break;
case kCFRunLoopRunTimedOut:
fprintf(stderr, "WOKE: kCFRunLoopRunTimedOut\n");
break;
case kCFRunLoopRunHandledSource:
fprintf(stderr, "WOKE: kCFRunLoopRunHandledSource\n");
break;
}
#endif
}
return NULL;
}
static CFRunLoopRef _legacyStreamRunLoop()
{
static dispatch_once_t sOnce = 0;
dispatch_once(&sOnce, ^{
if (sLegacyRL == NULL) {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
#if TARGET_OS_WIN32
HANDLE hThread =
(HANDLE)_beginthreadex(NULL, 0,
(_beginthreadex_proc_type)_legacyStreamRunLoop_workThread,
&sem, 0, NULL);
CloseHandle(hThread);
#else
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if TARGET_OS_MAC
pthread_attr_set_qos_class_np(&attr, qos_class_main(), 0);
#endif
_CFThreadRef workThread;
(void) pthread_create(&workThread, &attr, _legacyStreamRunLoop_workThread, &sem);
pthread_attr_destroy(&attr);
#endif
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_release(sem);
}
});
return sLegacyRL;
}
static dispatch_queue_t _CFStreamCopyDispatchQueue(struct _CFStream* stream)
{
dispatch_queue_t result = NULL;
_CFStreamLock(stream);
if (stream->client) {
result = stream->queue;
if (result)
dispatch_retain(result);
}
_CFStreamUnlock(stream);
return result;
}
static void _CFStreamSetDispatchQueue(struct _CFStream* stream, dispatch_queue_t q)
{
CFArrayRef rlm = _CFStreamCopyRunLoopsAndModes(stream);
if (rlm) {
CFIndex count = CFArrayGetCount(rlm);
for (CFIndex i = 0; i < count; i += 2) {
CFRunLoopRef rl = (CFRunLoopRef) CFArrayGetValueAtIndex(rlm, i);
CFStringRef mode = (CFStringRef) CFArrayGetValueAtIndex(rlm, i + 1);
_CFStreamUnscheduleFromRunLoop(stream, rl, mode);
}
CFRelease(rlm);
}
if (q == NULL) {
_CFStreamLock(stream);
if (stream->client) {
if (stream->queue)
dispatch_release(stream->queue);
stream->queue = NULL;
}
_CFStreamUnlock(stream);
} else {
_CFStreamScheduleWithRunLoop(stream, _legacyStreamRunLoop(), kCFRunLoopDefaultMode);
_CFStreamLock(stream);
if (stream->client) {
if (stream->queue != q) {
if (stream->queue)
dispatch_release(stream->queue);
stream->queue = q;
if (stream->queue)
dispatch_retain(stream->queue);
}
}
_CFStreamUnlock(stream);
}
}
void CFReadStreamSetDispatchQueue(CFReadStreamRef stream, dispatch_queue_t q)
{
_CFStreamSetDispatchQueue((struct _CFStream*) stream, q);
}
void CFWriteStreamSetDispatchQueue(CFWriteStreamRef stream, dispatch_queue_t q)
{
_CFStreamSetDispatchQueue((struct _CFStream*) stream, q);
}
dispatch_queue_t CFReadStreamCopyDispatchQueue(CFReadStreamRef stream)
{
return _CFStreamCopyDispatchQueue((struct _CFStream*) stream);
}
dispatch_queue_t CFWriteStreamCopyDispatchQueue(CFWriteStreamRef stream)
{
return _CFStreamCopyDispatchQueue((struct _CFStream*) stream);
}
#endif
static void waitForOpen(struct _CFStream *stream) {
#if __HAS_DISPATCH__
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFStringRef privateMode = CFSTR("_kCFStreamBlockingOpenMode");
_CFStreamScheduleWithRunLoop(stream, runLoop, privateMode);
// We cannot call _CFStreamGetStatus, because that tries to set/clear CALLING_CLIENT, which should be set around this entire call (we're within a call from the client). This should be o.k., because we're running the run loop, so our status code should be being updated in a timely fashion....
while (__CFStreamGetStatus(stream) == kCFStreamStatusOpening) {
CFRunLoopRunInMode(privateMode, 1e+20, TRUE);
}
_CFStreamUnscheduleFromRunLoop(stream, runLoop, privateMode);
#endif
}
CF_PRIVATE CFArrayRef _CFReadStreamCopyRunLoopsAndModes(CFReadStreamRef readStream) {
return _CFStreamCopyRunLoopsAndModes((struct _CFStream *)readStream);
}
CF_PRIVATE CFArrayRef _CFWriteStreamCopyRunLoopsAndModes(CFWriteStreamRef writeStream) {
return _CFStreamCopyRunLoopsAndModes((struct _CFStream *)writeStream);
}
CF_EXPORT void CFReadStreamSignalEvent(CFReadStreamRef stream, CFStreamEventType event, const void *error) {
_CFStreamSignalEvent((struct _CFStream *)stream, event, (CFErrorRef)error, TRUE);
}
CF_EXPORT void CFWriteStreamSignalEvent(CFWriteStreamRef stream, CFStreamEventType event, const void *error) {
_CFStreamSignalEvent((struct _CFStream *)stream, event, (CFErrorRef)error, TRUE);
}
CF_EXPORT void _CFReadStreamSignalEventDelayed(CFReadStreamRef stream, CFStreamEventType event, const void *error) {
_CFStreamSignalEvent((struct _CFStream *)stream, event, (CFErrorRef)error, FALSE);
}
CF_EXPORT void _CFReadStreamClearEvent(CFReadStreamRef readStream, CFStreamEventType event) {
struct _CFStream *stream = (struct _CFStream *)readStream;
if (stream->client) {
stream->client->whatToSignal &= ~event;
}
}
CF_EXPORT void _CFWriteStreamSignalEventDelayed(CFWriteStreamRef stream, CFStreamEventType event, const void *error) {
_CFStreamSignalEvent((struct _CFStream *)stream, event, (CFErrorRef)error, FALSE);
}
CF_EXPORT void *CFReadStreamGetInfoPointer(CFReadStreamRef stream) {
return _CFStreamGetInfoPointer((struct _CFStream *)stream);
}
CF_EXPORT void *CFWriteStreamGetInfoPointer(CFWriteStreamRef stream) {
return _CFStreamGetInfoPointer((struct _CFStream *)stream);
}
static Boolean _CFStreamRemoveRunLoopAndModeFromArray(CFMutableArrayRef runLoopsAndModes, CFRunLoopRef rl, CFStringRef mode) {
CFIndex idx, cnt;
Boolean found = FALSE;
if (!runLoopsAndModes) return FALSE;
checkRLMArray(runLoopsAndModes);
cnt = CFArrayGetCount(runLoopsAndModes);
for (idx = 0; idx + 1 < cnt; idx += 2) {
if (CFEqual(CFArrayGetValueAtIndex(runLoopsAndModes, idx), rl) && CFEqual(CFArrayGetValueAtIndex(runLoopsAndModes, idx + 1), mode)) {
CFArrayRemoveValueAtIndex(runLoopsAndModes, idx);
CFArrayRemoveValueAtIndex(runLoopsAndModes, idx);
found = TRUE;
break;
}
}
return found;
}
// Used by NSStream to properly allocate the bridged objects
CF_EXPORT CFIndex _CFStreamInstanceSize(void) {
return _CFSTREAM_SIZE;
}
#if TARGET_OS_WIN32
void __CFStreamCleanup(void) {
__CFLock(&sSourceLock);
if (sSharedSources) {
CFIndex count = CFDictionaryGetCount(sSharedSources);
if (count == 0) {
// Only release if empty. If it's still holding streams (which would be a client
// bug leak), freeing this dict would free the streams, which then need to access the
// dict to remove themselves, which leads to a deadlock.
CFRelease(sSharedSources);
sSharedSources = NULL;
} else {
const void ** keys = (const void **)malloc(sizeof(const void *) * count);
#if defined(DEBUG)
int i;
#endif
CFDictionaryGetKeysAndValues(sSharedSources, keys, NULL);
fprintf(stderr, "*** CFNetwork is shutting down, but %lld streams are still scheduled.\n", (long long)count);
#if defined(DEBUG)
for (i = 0; i < count;i ++) {
if ((CFGetTypeID(keys[i]) == _kCFRuntimeIDCFReadStream) || (CFGetTypeID(keys[i]) == _kCFRuntimeIDCFWriteStream)) {
CFShow(keys[i]);
}
}
#endif
}
}
__CFUnlock(&sSourceLock);
}
#endif
|