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 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
|
/* sqUnixSocket.c -- Unix socket support
*
* Copyright (C) 1996-2007 by Ian Piumarta and other authors/contributors
* listed elsewhere in this file.
* All rights reserved.
*
* This file is part of Unix Squeak.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* Author: Ian.Piumarta@inria.fr
*
* Last edited: 2007-06-11 10:56:14 by piumarta on vps2.piumarta.com
*
* Support for BSD-style "accept" primitives contributed by:
* Lex Spoon <lex@cc.gatech.edu>
*
* Notes:
* Sockets are completely asynchronous, but the resolver is still
* synchronous.
*
* BUGS:
* Now that the image has real UDP primitives, the TCP/UDP duality in
* many of the connection-oriented functions should be removed and
* cremated.
*/
#include "sq.h"
#include "SocketPlugin.h"
#include "sqaio.h"
#undef AIO_DEBUG
#undef DEBUG
#ifdef ACORN
# include <time.h>
# define __time_t
# include <signal.h>
# include "inetlib.h"
# include "socklib.h"
# include "netdb.h"
# include "unixlib.h"
# include "sys/ioctl.h"
# include "sys/errno.h"
# define h_errno errno
# define MAXHOSTNAMELEN 256
# define socklen_t int
# define strncpy(dst, src, len) copyNCharsFromTo(len, src, dst)
#else /* !ACORN */
# ifdef NEED_GETHOSTNAME_P
extern int gethostname();
# endif
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
# include <sys/param.h>
# include <sys/stat.h>
# include <sys/socket.h>
# include <sys/un.h>
# include <netinet/in.h>
# include <netinet/udp.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <netdb.h>
# include <errno.h>
# include <unistd.h>
#endif /* !ACORN */
/* Solaris sometimes fails to define this in netdb.h */
#ifndef MAXHOSTNAMELEN
# define MAXHOSTNAMELEN 256
#endif
/* debugging stuff. can probably be deleted */
#ifdef DEBUG
# ifdef ACORN
# define FPRINTF(s) \
{ \
extern os_error privateErr; \
extern void platReportError(os_error *e); \
privateErr.errnum = (bits)0; \
sprintf s; \
platReportError((os_error *)&privateErr); \
};
# else /* !ACORN */
extern int aioLastTick, aioThisTick;
# define FPRINTF(X) { aioThisTick= ioLowResMSecs(); fprintf(stderr, "%8d %8d ", aioThisTick, aioThisTick - aioLastTick); aioLastTick= aioThisTick; fprintf X; }
# endif
#else /* !DEBUG */
# define FPRINTF(X)
#endif
/*** Socket types ***/
#define TCPSocketType 0
#define UDPSocketType 1
/*** Resolver states ***/
#define ResolverUninitialised 0
#define ResolverSuccess 1
#define ResolverBusy 2
#define ResolverError 3
/*** TCP Socket states ***/
#define Invalid -1
#define Unconnected 0
#define WaitingForConnection 1
#define Connected 2
#define OtherEndClosed 3
#define ThisEndClosed 4
#define LINGER_SECS 1
static int thisNetSession= 0;
static int one= 1;
static char localHostName[MAXHOSTNAMELEN];
static u_long localHostAddress; /* GROSS IPv4 ASSUMPTION! */
union sockaddr_any
{
struct sockaddr sa;
struct sockaddr_un saun;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
};
typedef struct privateSocketStruct
{
int s; /* Unix socket */
int connSema; /* connection io notification semaphore */
int readSema; /* read io notification semaphore */
int writeSema; /* write io notification semaphore */
int sockState; /* connection + data state */
int sockError; /* errno after socket error */
union sockaddr_any peer; /* default send/recv address for UDP */
socklen_t peerSize; /* dynamic sizeof(peer) */
union sockaddr_any sender; /* sender address for last UDP receive */
socklen_t senderSize; /* dynamic sizeof(sender) */
int multiListen; /* whether to listen for multiple connections */
int acceptedSock; /* a connection that has been accepted */
} privateSocketStruct;
#define CONN_NOTIFY (1<<0)
#define READ_NOTIFY (1<<1)
#define WRITE_NOTIFY (1<<2)
#define PING(S,EVT) \
{ \
interpreterProxy->signalSemaphoreWithIndex((S)->EVT##Sema); \
FPRINTF((stderr, "notify %d %s\n", (S)->s, #EVT)); \
}
#define notify(SOCK,MASK) \
{ \
if ((MASK) & CONN_NOTIFY) PING(SOCK,conn); \
if ((MASK) & READ_NOTIFY) PING(SOCK,read); \
if ((MASK) & WRITE_NOTIFY) PING(SOCK,write); \
}
/*** Accessors for private socket members from a Squeak socket pointer ***/
#define _PSP(S) (((S)->privateSocketPtr))
#define PSP(S) ((privateSocketStruct *)((S)->privateSocketPtr))
#define SOCKET(S) (PSP(S)->s)
#define SOCKETSTATE(S) (PSP(S)->sockState)
#define SOCKETERROR(S) (PSP(S)->sockError)
#define SOCKETPEER(S) (PSP(S)->peer)
#define SOCKETPEERSIZE(S) (PSP(S)->peerSize)
/*** Resolver state ***/
static char lastName[MAXHOSTNAMELEN+1];
static int lastAddr= 0;
static int lastError= 0;
static int resolverSema= 0;
/*** Variables ***/
extern struct VirtualMachine *interpreterProxy;
int setHookFn;
static void acceptHandler(int, void *, int);
static void connectHandler(int, void *, int);
static void dataHandler(int, void *, int);
static void closeHandler(int, void *, int);
/* this MUST be turned on if DEBUG is turned on in aio.c */
#ifdef AIO_DEBUG
char *socketHandlerName(aioHandler h)
{
if (h == acceptHandler) return "acceptHandler";
if (h == connectHandler) return "connectHandler";
if (h == dataHandler) return "dataHandler";
if (h == closeHandler) return "closeHandler";
return "***unknownHandler***";
}
#endif
/*** module initialisation/shutdown ***/
sqInt socketInit(void)
{
return 1;
}
sqInt socketShutdown(void)
{
/* shutdown the network */
sqNetworkShutdown();
return 1;
}
/*** miscellaneous sundries ***/
/* set linger on a connected stream */
static void setLinger(int fd, int flag)
{
struct linger linger= { flag, flag * LINGER_SECS };
setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof(linger));
}
/* answer the hostname for the given IP address */
static const char *addrToName(int netAddress)
{
u_long nAddr;
struct hostent *he;
lastError= 0; /* for the resolver */
nAddr= htonl(netAddress);
if ((he= gethostbyaddr((char *)&nAddr, sizeof(nAddr), AF_INET)))
return he->h_name;
lastError= h_errno; /* ditto */
return "";
}
/* answer the IP address for the given hostname */
static int nameToAddr(char *hostName)
{
struct hostent *he;
lastError= 0; /* ditto */
if ((he= gethostbyname(hostName)))
return ntohl(*(long *)(he->h_addr_list[0]));
lastError= h_errno; /* and one more ditto */
return 0;
}
/* answer whether the given socket is valid in this net session */
static int socketValid(SocketPtr s)
{
if (s && s->privateSocketPtr && thisNetSession && (s->sessionID == thisNetSession))
return true;
interpreterProxy->success(false);
return false;
}
/* answer 1 if the given socket is readable,
0 if read would block, or
-1 if the socket is no longer connected */
static int socketReadable(int s)
{
char buf[1];
int n= recv(s, (void *)buf, 1, MSG_PEEK);
if (n > 0) return 1;
if ((n < 0) && (errno == EWOULDBLOCK)) return 0;
return -1; /* EOF */
}
/* answer whether the socket can be written without blocking */
static int socketWritable(int s)
{
struct timeval tv= { 0, 0 };
fd_set fds;
FD_ZERO(&fds);
FD_SET(s, &fds);
return select(s+1, 0, &fds, 0, &tv) > 0;
}
/* answer the error condition on the given socket */
static int socketError(int s)
{
int error= 0;
socklen_t errsz= sizeof(error);
/* Solaris helpfuly returns -1 if there is an error on the socket, so
we can't check the success of the getsockopt call itself. Ho hum. */
getsockopt(s, SOL_SOCKET, SO_ERROR, (void *)&error, &errsz);
return error;
}
/*** asynchronous io handlers ***/
/* accept() can now be performed for the socket: call accept(),
and replace the server socket with the new client socket
leaving the client socket unhandled
*/
static void acceptHandler(int fd, void *data, int flags)
{
privateSocketStruct *pss= (privateSocketStruct *)data;
FPRINTF((stderr, "acceptHandler(%d, %p ,%d)\n", fd, data, flags));
if (flags & AIO_X) /* -- exception */
{
/* error during listen() */
aioDisable(fd);
pss->sockError= socketError(fd);
pss->sockState= Invalid;
pss->s= -1;
close(fd);
fprintf(stderr, "acceptHandler: aborting server %d pss=%p\n", fd, pss);
}
else /* (flags & AIO_R) -- accept() is ready */
{
int newSock= accept(fd, 0, 0);
if (newSock < 0)
{
if (errno == ECONNABORTED)
{
/* let's just pretend this never happened */
aioHandle(fd, acceptHandler, AIO_RX);
return;
}
/* something really went wrong */
pss->sockError= errno;
pss->sockState= Invalid;
perror("acceptHandler");
aioDisable(fd);
close(fd);
fprintf(stderr, "acceptHandler: aborting server %d pss=%p\n", fd, pss);
}
else /* newSock >= 0 -- connection accepted */
{
pss->sockState= Connected;
setLinger(newSock, 1);
if (pss->multiListen)
{
pss->acceptedSock= newSock;
}
else /* traditional listen -- replace server with client in-place */
{
aioDisable(fd);
close(fd);
pss->s= newSock;
aioEnable(newSock, pss, 0);
}
}
}
notify(pss, CONN_NOTIFY);
}
/* connect() has completed: check errors, leaving the socket unhandled */
static void connectHandler(int fd, void *data, int flags)
{
privateSocketStruct *pss= (privateSocketStruct *)data;
FPRINTF((stderr, "connectHandler(%d, %p, %d)\n", fd, data, flags));
if (flags & AIO_X) /* -- exception */
{
/* error during asynchronous connect() */
aioDisable(fd);
pss->sockError= socketError(fd);
pss->sockState= Unconnected;
perror("connectHandler");
}
else /* (flags & AIO_W) -- connect completed */
{
/* connect() has completed */
int error= socketError(fd);
if (error)
{
FPRINTF((stderr, "connectHandler: error %d (%s)\n", error, strerror(error)));
pss->sockError= error;
pss->sockState= Unconnected;
}
else
{
pss->sockState= Connected;
setLinger(pss->s, 1);
}
}
notify(pss, CONN_NOTIFY);
}
/* read or write data transfer is now possible for the socket. */
static void dataHandler(int fd, void *data, int flags)
{
privateSocketStruct *pss= (privateSocketStruct *)data;
FPRINTF((stderr, "dataHandler(%d=%d, %p, %d)\n", fd, pss->s, data, flags));
if (pss == NULL)
{
fprintf(stderr, "dataHandler: pss is NULL fd=%d data=%p flags=0x%x\n", fd, data, flags);
return;
}
if (flags & AIO_R)
{
int n= socketReadable(fd);
if (n == 0)
{
fprintf(stderr, "dataHandler: selected socket fd=%d flags=0x%x would block (why?)\n", fd, flags);
}
if (n != 1)
{
pss->sockError= socketError(fd);
pss->sockState= OtherEndClosed;
}
}
if (flags & AIO_X)
{
/* assume out-of-band data has arrived */
/* NOTE: Squeak's socket interface is currently incapable of reading
* OOB data. We have no choice but to discard it. Ho hum. */
char buf[1];
int n= recv(fd, (void *)buf, 1, MSG_OOB);
if (n == 1) fprintf(stderr, "socket: received OOB data: %02x\n", buf[0]);
}
if (flags & AIO_R) notify(pss, READ_NOTIFY);
if (flags & AIO_W) notify(pss, WRITE_NOTIFY);
}
/* a non-blocking close() has completed -- finish tidying up */
static void closeHandler(int fd, void *data, int flags)
{
privateSocketStruct *pss= (privateSocketStruct *)data;
aioDisable(fd);
FPRINTF((stderr, "closeHandler(%d, %p, %d)\n", fd, data, flags));
pss->sockState= Unconnected;
pss->s= -1;
notify(pss, CONN_NOTIFY);
}
/*** Squeak network functions ***/
/* start a new network session */
sqInt sqNetworkInit(sqInt resolverSemaIndex)
{
if (0 != thisNetSession)
return 0; /* already initialised */
gethostname(localHostName, MAXHOSTNAMELEN);
localHostAddress= nameToAddr(localHostName);
thisNetSession= clock() + time(0);
if (0 == thisNetSession)
thisNetSession= 1; /* 0 => uninitialised */
resolverSema= resolverSemaIndex;
return 0;
}
/* terminate the current network session (invalidates all open sockets) */
void sqNetworkShutdown(void)
{
thisNetSession= 0;
resolverSema= 0;
aioFini();
}
/*** Squeak Generic Socket Functions ***/
/* create a new socket */
void sqSocketCreateNetTypeSocketTypeRecvBytesSendBytesSemaID(SocketPtr s, sqInt domain, sqInt socketType, sqInt recvBufSize, sqInt sendBufSize, sqInt semaIndex)
{
sqSocketCreateNetTypeSocketTypeRecvBytesSendBytesSemaIDReadSemaIDWriteSemaID(s, domain, socketType,recvBufSize, sendBufSize, semaIndex, semaIndex, semaIndex);
}
void sqSocketCreateNetTypeSocketTypeRecvBytesSendBytesSemaIDReadSemaIDWriteSemaID(SocketPtr s, sqInt domain, sqInt socketType, sqInt recvBufSize, sqInt sendBufSize, sqInt semaIndex, sqInt readSemaIndex, sqInt writeSemaIndex)
{
int newSocket= -1;
privateSocketStruct *pss;
switch (domain)
{
case 0: domain= AF_INET; break; /* SQ_SOCKET_DOMAIN_UNSPECIFIED */
case 1: domain= AF_UNIX; break; /* SQ_SOCKET_DOMAIN_LOCAL */
case 2: domain= AF_INET; break; /* SQ_SOCKET_DOMAIN_INET4 */
case 3: domain= AF_INET6; break; /* SQ_SOCKET_DOMAIN_INET6 */
}
s->sessionID= 0;
if (TCPSocketType == socketType)
{
/* --- TCP --- */
newSocket= socket(domain, SOCK_STREAM, 0);
}
else if (UDPSocketType == socketType)
{
/* --- UDP --- */
newSocket= socket(domain, SOCK_DGRAM, 0);
}
if (-1 == newSocket)
{
/* socket() failed, or incorrect socketType */
interpreterProxy->success(false);
return;
}
setsockopt(newSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
/* private socket structure */
pss= (privateSocketStruct *)calloc(1, sizeof(privateSocketStruct));
if (pss == NULL)
{
fprintf(stderr, "acceptFrom: out of memory\n");
interpreterProxy->success(false);
return;
}
pss->s= newSocket;
pss->connSema= semaIndex;
pss->readSema= readSemaIndex;
pss->writeSema= writeSemaIndex;
/* UDP sockets are born "connected" */
if (UDPSocketType == socketType)
{
pss->sockState= Connected;
aioEnable(pss->s, pss, 0);
}
else
{
pss->sockState= Unconnected;
}
pss->sockError= 0;
/* initial UDP peer := wildcard */
memset(&pss->peer, 0, sizeof(pss->peer));
pss->peer.sin.sin_family= AF_INET;
pss->peer.sin.sin_port= 0;
pss->peer.sin.sin_addr.s_addr= INADDR_ANY;
/* Squeak socket */
s->sessionID= thisNetSession;
s->socketType= socketType;
s->privateSocketPtr= pss;
FPRINTF((stderr, "create(%d) -> %lx\n", SOCKET(s), (unsigned long)PSP(s)));
/* Note: socket is in BLOCKING mode until aioEnable is called for it! */
}
/* return the state of a socket */
sqInt sqSocketConnectionStatus(SocketPtr s)
{
if (!socketValid(s))
return Invalid;
/* we now know that the net session is valid, so if state is Invalid... */
if (SOCKETSTATE(s) == Invalid) /* see acceptHandler() */
{
fprintf(stderr, "socketStatus: freeing invalidated pss=%p\n", PSP(s));
/*free(PSP(s));*/ /* this almost never happens -- safer not to free()?? */
_PSP(s)= 0;
interpreterProxy->success(false);
return Invalid;
}
#if 0
/* check for connection closed by peer */
if (SOCKETSTATE(s) == Connected)
{
int fd= SOCKET(s);
int n= socketReadable(fd);
if (n < 0)
{
FPRINTF((stderr, "socketStatus(%d): detected other end closed\n", fd));
SOCKETSTATE(s)= OtherEndClosed;
}
}
#endif
FPRINTF((stderr, "socketStatus(%d) -> %d\n", SOCKET(s), SOCKETSTATE(s)));
return SOCKETSTATE(s);
}
/* TCP => start listening for incoming connections.
* UDP => associate the local port number with the socket.
*/
void sqSocketListenOnPort(SocketPtr s, sqInt port)
{
sqSocketListenOnPortBacklogSize(s, port, 1);
}
void sqSocketListenOnPortBacklogSizeInterface(SocketPtr s, sqInt port, sqInt backlogSize, sqInt addr)
{
struct sockaddr_in saddr;
if (!socketValid(s))
return;
/* only TCP sockets have a backlog */
if ((backlogSize > 1) && (s->socketType != TCPSocketType))
{
interpreterProxy->success(false);
return;
}
PSP(s)->multiListen= (backlogSize > 1);
FPRINTF((stderr, "listenOnPortBacklogSize(%d, %d)\n", SOCKET(s), backlogSize));
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family= AF_INET;
saddr.sin_port= htons((short)port);
saddr.sin_addr.s_addr= htonl(addr);
bind(SOCKET(s), (struct sockaddr*) &saddr, sizeof(saddr));
if (TCPSocketType == s->socketType)
{
/* --- TCP --- */
listen(SOCKET(s), backlogSize);
SOCKETSTATE(s)= WaitingForConnection;
aioEnable(SOCKET(s), PSP(s), 0);
aioHandle(SOCKET(s), acceptHandler, AIO_RX); /* R => accept() */
}
else
{
/* --- UDP --- */
}
}
void sqSocketListenOnPortBacklogSize(SocketPtr s, sqInt port, sqInt backlogSize)
{
sqSocketListenOnPortBacklogSizeInterface(s, port, backlogSize, INADDR_ANY);
}
/* TCP => open a connection.
* UDP => set remote address.
*/
void sqSocketConnectToPort(SocketPtr s, sqInt addr, sqInt port)
{
struct sockaddr_in saddr;
if (!socketValid(s))
return;
FPRINTF((stderr, "connectTo(%d)\n", SOCKET(s)));
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family= AF_INET;
saddr.sin_port= htons((short)port);
saddr.sin_addr.s_addr= htonl(addr);
if (UDPSocketType == s->socketType)
{
/* --- UDP --- */
if (SOCKET(s) >= 0)
{
memcpy((void *)&SOCKETPEER(s), (void *)&saddr, sizeof(saddr));
SOCKETPEERSIZE(s)= sizeof(struct sockaddr_in);
SOCKETSTATE(s)= Connected;
}
}
else
{
/* --- TCP --- */
int result;
aioEnable(SOCKET(s), PSP(s), 0);
result= connect(SOCKET(s), (struct sockaddr *)&saddr, sizeof(saddr));
FPRINTF((stderr, "connect() => %d\n", result));
if (result == 0)
{
/* connection completed synchronously */
SOCKETSTATE(s)= Connected;
notify(PSP(s), CONN_NOTIFY);
setLinger(SOCKET(s), 1);
}
else
{
if (errno == EINPROGRESS || errno == EWOULDBLOCK)
{
/* asynchronous connection in progress */
SOCKETSTATE(s)= WaitingForConnection;
aioHandle(SOCKET(s), connectHandler, AIO_WX); /* W => connect() */
}
else
{
/* connection error */
perror("sqConnectToPort");
SOCKETSTATE(s)= Unconnected;
SOCKETERROR(s)= errno;
notify(PSP(s), CONN_NOTIFY);
}
}
}
}
void sqSocketAcceptFromRecvBytesSendBytesSemaID(SocketPtr s, SocketPtr serverSocket, sqInt recvBufSize, sqInt sendBufSize, sqInt semaIndex)
{
sqSocketAcceptFromRecvBytesSendBytesSemaIDReadSemaIDWriteSemaID(s, serverSocket, recvBufSize, sendBufSize, semaIndex, semaIndex, semaIndex);
}
void sqSocketAcceptFromRecvBytesSendBytesSemaIDReadSemaIDWriteSemaID(SocketPtr s, SocketPtr serverSocket, sqInt recvBufSize, sqInt sendBufSize, sqInt semaIndex, sqInt readSemaIndex, sqInt writeSemaIndex)
{
/* The image has already called waitForConnection, so there is no
need to signal the server's connection semaphore again. */
struct privateSocketStruct *pss;
FPRINTF((stderr, "acceptFrom(%p, %d)\n", s, SOCKET(serverSocket)));
/* sanity checks */
if (!socketValid(serverSocket) || !PSP(serverSocket)->multiListen)
{
FPRINTF((stderr, "accept failed: (multi->%d)\n", PSP(serverSocket)->multiListen));
interpreterProxy->success(false);
return;
}
/* check that a connection is there */
if (PSP(serverSocket)->acceptedSock < 0)
{
fprintf(stderr, "acceptFrom: no socket available\n");
interpreterProxy->success(false);
return;
}
/* got connection -- fill in the structure */
s->sessionID= 0;
pss= (privateSocketStruct *)calloc(1, sizeof(privateSocketStruct));
if (pss == NULL)
{
fprintf(stderr, "acceptFrom: out of memory\n");
interpreterProxy->success(false);
return;
}
_PSP(s)= pss;
pss->s= PSP(serverSocket)->acceptedSock;
PSP(serverSocket)->acceptedSock= -1;
SOCKETSTATE(serverSocket)= WaitingForConnection;
aioHandle(SOCKET(serverSocket), acceptHandler, AIO_RX);
s->sessionID= thisNetSession;
pss->connSema= semaIndex;
pss->readSema= readSemaIndex;
pss->writeSema= writeSemaIndex;
pss->sockState= Connected;
pss->sockError= 0;
aioEnable(SOCKET(s), PSP(s), 0);
}
/* close the socket */
void sqSocketCloseConnection(SocketPtr s)
{
int result= 0;
if (!socketValid(s))
return;
FPRINTF((stderr, "closeConnection(%d)\n", SOCKET(s)));
if (SOCKET(s) < 0)
return; /* already closed */
aioDisable(SOCKET(s));
SOCKETSTATE(s)= ThisEndClosed;
result= close(SOCKET(s));
if ((result == -1) && (errno != EWOULDBLOCK))
{
/* error */
SOCKETSTATE(s)= Unconnected;
SOCKETERROR(s)= errno;
notify(PSP(s), CONN_NOTIFY);
perror("closeConnection");
}
else if (0 == result)
{
/* close completed synchronously */
SOCKETSTATE(s)= Unconnected;
FPRINTF((stderr, "closeConnection: disconnected\n"));
SOCKET(s)= -1;
}
else
{
/* asynchronous close in progress */
SOCKETSTATE(s)= ThisEndClosed;
aioHandle(SOCKET(s), closeHandler, AIO_RWX); /* => close() done */
FPRINTF((stderr, "closeConnection: deferred [aioHandle is set]\n"));
}
}
/* close the socket without lingering */
void sqSocketAbortConnection(SocketPtr s)
{
FPRINTF((stderr, "abortConnection(%d)\n", SOCKET(s)));
if (!socketValid(s))
return;
setLinger(SOCKET(s), 0);
sqSocketCloseConnection(s);
}
/* Release the resources associated with this socket.
If a connection is open, abort it. */
void sqSocketDestroy(SocketPtr s)
{
if (!socketValid(s))
return;
FPRINTF((stderr, "destroy(%d)\n", SOCKET(s)));
if (SOCKET(s))
sqSocketAbortConnection(s); /* close if necessary */
if (PSP(s))
free(PSP(s)); /* release private struct */
_PSP(s)= 0;
}
/* answer the OS error code for the last socket operation */
sqInt sqSocketError(SocketPtr s)
{
if (!socketValid(s))
return -1;
return SOCKETERROR(s);
}
/* return the local IP address bound to a socket */
sqInt sqSocketLocalAddress(SocketPtr s)
{
struct sockaddr_in saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (getsockname(SOCKET(s), (struct sockaddr *)&saddr, &saddrSize)
|| (AF_INET != saddr.sin_family))
return 0;
return ntohl(saddr.sin_addr.s_addr);
}
/* return the peer's IP address */
sqInt sqSocketRemoteAddress(SocketPtr s)
{
struct sockaddr_in saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (TCPSocketType == s->socketType)
{
/* --- TCP --- */
if (getpeername(SOCKET(s), (struct sockaddr *)&saddr, &saddrSize)
|| (AF_INET != saddr.sin_family))
return 0;
return ntohl(saddr.sin_addr.s_addr);
}
/* --- UDP --- */
return ntohl(SOCKETPEER(s).sin.sin_addr.s_addr);
}
/* return the local port number of a socket */
sqInt sqSocketLocalPort(SocketPtr s)
{
struct sockaddr_in saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (getsockname(SOCKET(s), (struct sockaddr *)&saddr, &saddrSize)
|| (AF_INET != saddr.sin_family))
return 0;
return ntohs(saddr.sin_port);
}
/* return the peer's port number */
sqInt sqSocketRemotePort(SocketPtr s)
{
struct sockaddr_in saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (TCPSocketType == s->socketType)
{
/* --- TCP --- */
if (getpeername(SOCKET(s), (struct sockaddr *)&saddr, &saddrSize)
|| (AF_INET != saddr.sin_family))
return 0;
return ntohs(saddr.sin_port);
}
/* --- UDP --- */
return ntohs(SOCKETPEER(s).sin.sin_port);
}
/* answer whether the socket has data available for reading:
if the socket is not connected, answer "false";
if the socket is open and data can be read, answer "true".
if the socket is open and no data is currently readable, answer "false";
if the socket is closed by peer, change the state to OtherEndClosed
and answer "false";
*/
sqInt sqSocketReceiveDataAvailable(SocketPtr s)
{
if (!socketValid(s)) return false;
if (SOCKETSTATE(s) == Connected)
{
int fd= SOCKET(s);
int n= socketReadable(fd);
if (n > 0)
{
FPRINTF((stderr, "receiveDataAvailable(%d) -> true\n", fd));
return true;
}
else if (n < 0)
{
FPRINTF((stderr, "receiveDataAvailable(%d): other end closed\n", fd));
SOCKETSTATE(s)= OtherEndClosed;
}
}
else /* (SOCKETSTATE(s) != Connected) */
{
FPRINTF((stderr, "receiveDataAvailable(%d): socket not connected\n", SOCKET(s)));
}
aioHandle(SOCKET(s), dataHandler, AIO_RX);
FPRINTF((stderr, "receiveDataAvailable(%d) -> false [aioHandle is set]\n", SOCKET(s)));
return false;
}
/* answer whether the socket has space to receive more data */
sqInt sqSocketSendDone(SocketPtr s)
{
if (!socketValid(s))
return false;
if (SOCKETSTATE(s) == Connected)
{
if (socketWritable(SOCKET(s))) return true;
aioHandle(SOCKET(s), dataHandler, AIO_WX);
}
return false;
}
/* read data from the socket s into buf for at most bufSize bytes.
answer the number actually read. For UDP, fill in the peer's address
with the approriate value.
*/
sqInt sqSocketReceiveDataBufCount(SocketPtr s, char *buf, sqInt bufSize)
{
int nread= 0;
if (!socketValid(s))
return -1;
SOCKETPEERSIZE(s)= 0;
if (UDPSocketType == s->socketType)
{
/* --- UDP --- */
socklen_t addrSize= sizeof(SOCKETPEER(s));
if ((nread= recvfrom(SOCKET(s), buf, bufSize, 0, (struct sockaddr *)&SOCKETPEER(s), &addrSize)) <= 0)
{
if ((nread == -1) && (errno == EWOULDBLOCK))
{
FPRINTF((stderr, "UDP receiveData(%d) < 1 [blocked]\n", SOCKET(s)));
return 0;
}
SOCKETERROR(s)= errno;
FPRINTF((stderr, "UDP receiveData(%d) < 1 [a:%d]\n", SOCKET(s), errno));
return 0;
}
SOCKETPEERSIZE(s)= addrSize;
}
else
{
/* --- TCP --- */
if ((nread= read(SOCKET(s), buf, bufSize)) <= 0)
{
if ((nread == -1) && (errno == EWOULDBLOCK))
{
FPRINTF((stderr, "TCP receiveData(%d) < 1 [blocked]\n", SOCKET(s)));
return 0;
}
/* connection reset */
SOCKETSTATE(s)= OtherEndClosed;
SOCKETERROR(s)= errno;
FPRINTF((stderr, "TCP receiveData(%d) < 1 [b:%d]\n", SOCKET(s), errno));
notify(PSP(s), CONN_NOTIFY);
return 0;
}
}
/* read completed synchronously */
FPRINTF((stderr, "receiveData(%d) done = %d\n", SOCKET(s), nread));
return nread;
}
/* write data to the socket s from buf for at most bufSize bytes.
answer the number of bytes actually written.
*/
sqInt sqSocketSendDataBufCount(SocketPtr s, char *buf, sqInt bufSize)
{
int nsent= 0;
if (!socketValid(s))
return -1;
if (UDPSocketType == s->socketType)
{
/* --- UDP --- */
FPRINTF((stderr, "UDP sendData(%d, %d)\n", SOCKET(s), bufSize));
if ((nsent= sendto(SOCKET(s), buf, bufSize, 0, (struct sockaddr *)&SOCKETPEER(s), sizeof(SOCKETPEER(s)))) <= 0)
{
if (errno == EWOULDBLOCK) /* asynchronous write in progress */
return 0;
FPRINTF((stderr, "UDP send failed\n"));
SOCKETERROR(s)= errno;
return 0;
}
}
else
{
/* --- TCP --- */
FPRINTF((stderr, "TCP sendData(%d, %d)\n", SOCKET(s), bufSize));
if ((nsent= write(SOCKET(s), buf, bufSize)) <= 0)
{
if ((nsent == -1) && (errno == EWOULDBLOCK))
{
FPRINTF((stderr, "TCP sendData(%d, %d) -> %d [blocked]",
SOCKET(s), bufSize, nsent));
return 0;
}
else
{
/* error: most likely "connection closed by peer" */
SOCKETSTATE(s)= OtherEndClosed;
SOCKETERROR(s)= errno;
FPRINTF((stderr, "TCP write failed -> %d", errno));
return 0;
}
}
}
/* write completed synchronously */
FPRINTF((stderr, "sendData(%d) done = %d\n", SOCKET(s), nsent));
return nsent;
}
/* read data from the UDP socket s into buf for at most bufSize bytes.
answer the number of bytes actually read.
*/
sqInt sqSocketReceiveUDPDataBufCountaddressportmoreFlag(SocketPtr s, char *buf, sqInt bufSize, sqInt *address, sqInt *port, sqInt *moreFlag)
{
if (socketValid(s) && (UDPSocketType == s->socketType))
{
struct sockaddr_in saddr;
socklen_t addrSize= sizeof(saddr);
FPRINTF((stderr, "recvFrom(%d)\n", SOCKET(s)));
memset(&saddr, 0, sizeof(saddr));
{
int nread= recvfrom(SOCKET(s), buf, bufSize, 0, (struct sockaddr *)&saddr, &addrSize);
if (nread >= 0)
{
*address= ntohl(saddr.sin_addr.s_addr);
*port= ntohs(saddr.sin_port);
return nread;
}
if (errno == EWOULDBLOCK) /* asynchronous read in progress */
return 0;
SOCKETERROR(s)= errno;
FPRINTF((stderr, "receiveData(%d)= %da\n", SOCKET(s), 0));
}
}
interpreterProxy->success(false);
return 0;
}
/* write data to the UDP socket s from buf for at most bufSize bytes.
* answer the number of bytes actually written.
*/
sqInt sqSockettoHostportSendDataBufCount(SocketPtr s, sqInt address, sqInt port, char *buf, sqInt bufSize)
{
if (socketValid(s) && (UDPSocketType == s->socketType))
{
struct sockaddr_in saddr;
FPRINTF((stderr, "sendTo(%d)\n", SOCKET(s)));
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family= AF_INET;
saddr.sin_port= htons((short)port);
saddr.sin_addr.s_addr= htonl(address);
{
int nsent= sendto(SOCKET(s), buf, bufSize, 0, (struct sockaddr *)&saddr, sizeof(saddr));
if (nsent >= 0)
return nsent;
if (errno == EWOULDBLOCK) /* asynchronous write in progress */
return 0;
FPRINTF((stderr, "UDP send failed\n"));
SOCKETERROR(s)= errno;
}
}
interpreterProxy->success(false);
return 0;
}
/*** socket options ***/
/* NOTE: we only support the portable options here as an incentive for
people to write portable Squeak programs. If you need
non-portable socket options then go write yourself a plugin
specific to your platform. This decision is unilateral and
non-negotiable. - ikp
NOTE: we only support the integer-valued options because the code
in SocketPlugin doesn't seem able to cope with the others.
(Personally I think that things like SO_SNDTIMEO et al would
by far more interesting than the majority of things on this
list, but there you go...)
NOTE: if your build fails because of a missing option in this list,
simply DELETE THE OPTION (or comment it out) and then send
me mail (ian.piumarta@inria.fr) to let me know about it.
*/
typedef struct
{
char *name; /* name as known to Squeak */
int optlevel; /* protocol level */
int optname; /* name as known to Unix */
} socketOption;
#ifndef SOL_IP
# define SOL_IP IPPROTO_IP
#endif
#ifndef SOL_UDP
# define SOL_UDP IPPROTO_UDP
#endif
#ifndef SOL_TCP
# define SOL_TCP IPPROTO_TCP
#endif
static socketOption socketOptions[]= {
{ "SO_DEBUG", SOL_SOCKET, SO_DEBUG },
{ "SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR },
{ "SO_DONTROUTE", SOL_SOCKET, SO_DONTROUTE },
{ "SO_BROADCAST", SOL_SOCKET, SO_BROADCAST },
{ "SO_SNDBUF", SOL_SOCKET, SO_SNDBUF },
{ "SO_RCVBUF", SOL_SOCKET, SO_RCVBUF },
{ "SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE },
{ "SO_OOBINLINE", SOL_SOCKET, SO_OOBINLINE },
{ "SO_LINGER", SOL_SOCKET, SO_LINGER },
{ "IP_TTL", SOL_IP, IP_TTL },
{ "IP_HDRINCL", SOL_IP, IP_HDRINCL },
{ "IP_MULTICAST_IF", SOL_IP, IP_MULTICAST_IF },
{ "IP_MULTICAST_TTL", SOL_IP, IP_MULTICAST_TTL },
{ "IP_MULTICAST_LOOP", SOL_IP, IP_MULTICAST_LOOP },
#ifdef IP_ADD_MEMBERSHIP
{ "IP_ADD_MEMBERSHIP", SOL_IP, IP_ADD_MEMBERSHIP },
{ "IP_DROP_MEMBERSHIP", SOL_IP, IP_DROP_MEMBERSHIP },
#endif
{ "TCP_MAXSEG", SOL_TCP, TCP_MAXSEG },
{ "TCP_NODELAY", SOL_TCP, TCP_NODELAY },
#ifdef SO_REUSEPORT
{ "SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT },
#endif
#if 0 /*** deliberately unsupported options -- do NOT enable these! ***/
{ "SO_PRIORITY", SOL_SOCKET, SO_PRIORITY },
{ "SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT },
{ "SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT },
{ "IP_RCVOPTS", SOL_IP, IP_RCVOPTS },
{ "IP_RCVDSTADDR", SOL_IP, IP_RCVDSTADDR },
{ "UDP_CHECKSUM", SOL_UDP, UDP_CHECKSUM },
{ "TCP_ABORT_THRESHOLD", SOL_TCP, TCP_ABORT_THRESHOLD },
{ "TCP_CONN_NOTIFY_THRESHOLD", SOL_TCP, TCP_CONN_NOTIFY_THRESHOLD },
{ "TCP_CONN_ABORT_THRESHOLD", SOL_TCP, TCP_CONN_ABORT_THRESHOLD },
{ "TCP_NOTIFY_THRESHOLD", SOL_TCP, TCP_NOTIFY_THRESHOLD },
{ "TCP_URGENT_PTR_TYPE", SOL_TCP, TCP_URGENT_PTR_TYPE },
#endif
{ (char *)0, 0, 0 }
};
static socketOption *findOption(char *name, size_t nameSize)
{
if (nameSize < 32)
{
socketOption *opt= 0;
char buf[32];
buf[nameSize]= '\0';
strncpy(buf, name, nameSize);
for (opt= socketOptions; opt->name != 0; ++opt)
if (!strcmp(buf, opt->name))
return opt;
fprintf(stderr, "SocketPlugin: ignoring unknown option '%s'\n", buf);
}
return 0;
}
/* set the given option for the socket. the option comes in as a
* String. (why on earth we might think this a good idea eludes me
* ENTIRELY, so... if the string doesn't smell like an integer then we
* copy it verbatim, assuming it's really a ByteArray pretending to be
* a struct. caveat hackor.)
*/
sqInt sqSocketSetOptionsoptionNameStartoptionNameSizeoptionValueStartoptionValueSizereturnedValue(SocketPtr s, char *optionName, sqInt optionNameSize, char *optionValue, sqInt optionValueSize, sqInt *result)
{
if (socketValid(s))
{
socketOption *opt= findOption(optionName, (size_t)optionNameSize);
if (opt != 0)
{
int val= 0;
char buf[32];
char *endptr;
/* this is JUST PLAIN WRONG (I mean the design in the image rather
than the implementation here, which is probably correct
w.r.t. the broken design) */
if (optionValueSize > sizeof(buf) - 1)
goto barf;
memset((void *)buf, 0, sizeof(buf));
memcpy((void *)buf, optionValue, optionValueSize);
if (optionValueSize == 1) /* character `1' or `0' */
{
val= strtol(buf, &endptr, 0);
if (endptr != buf)
{
memcpy((void *)buf, (void *)&val, sizeof(val));
optionValueSize= sizeof(val);
}
}
if ((setsockopt(PSP(s)->s, opt->optlevel, opt->optname,
(const void *)buf, optionValueSize)) < 0)
{
perror("setsockopt");
goto barf;
}
/* it isn't clear what we're supposed to return here, since
setsockopt isn't supposed to have any value-result parameters
(go grok that `const' on the buffer argument if you don't
believe me). the image says "the result of the negotiated
value". what the fuck is there to negotiate? either
setsockopt sets the value or it barfs. and i'm not about to go
calling getsockopt just to see if the value got changed or not
(the image should send getOption: to the Socket if it really
wants to know). if the following is wrong then I could
probably care (a lot) less... fix the logic in the image and
then maybe i'll care about fixing the logic in here. (i know
that isn't very helpful, but it's 05:47 in the morning and i'm
severely grumpy after fixing several very unpleasant bugs that
somebody introduced into this file while i wasn't looking.) */
*result= val;
return 0;
}
}
barf:
interpreterProxy->success(false);
return false;
}
/* query the socket for the given option. */
sqInt sqSocketGetOptionsoptionNameStartoptionNameSizereturnedValue(SocketPtr s, char *optionName, sqInt optionNameSize, sqInt *result)
{
if (socketValid(s))
{
socketOption *opt= findOption(optionName, (size_t)optionNameSize);
if (opt != 0)
{
int optval; /* NOT sqInt */
socklen_t optlen= sizeof(optval);
if ((getsockopt(PSP(s)->s, opt->optlevel, opt->optname, (void *)&optval, &optlen)) < 0)
goto barf;
if (optlen != sizeof(optval))
goto barf;
*result= optval;
return 0;
}
}
barf:
interpreterProxy->success(false);
return errno;
}
void sqSocketBindToPort(SocketPtr s, int addr, int port)
{
int result;
struct sockaddr_in inaddr;
privateSocketStruct *pss= PSP(s);
if (!socketValid(s)) return;
/* bind the socket */
memset(&inaddr, 0, sizeof(inaddr));
inaddr.sin_family= AF_INET;
inaddr.sin_port= htons(port);
inaddr.sin_addr.s_addr= htonl(addr);
if (bind(SOCKET(s), (struct sockaddr *)&inaddr, sizeof(struct sockaddr_in)) < 0)
{
pss->sockError= errno;
interpreterProxy->success(false);
return;
}
}
void sqSocketSetReusable(SocketPtr s)
{
char optionValue[256];
size_t bufSize;
unsigned char buf[4];
int err;
if (!socketValid(s)) return;
*(int *)buf= 1;
bufSize= 4;
if (setsockopt(SOCKET(s), SOL_SOCKET, SO_REUSEADDR, buf, bufSize) < 0)
{
PSP(s)->sockError= errno;
interpreterProxy->success(false);
return;
}
}
/*** Resolver functions ***/
/* Note: the Mac and Win32 implementations implement asynchronous lookups
* in the DNS. I can't think of an easy way to do this in Unix without
* going totally ott with threads or somesuch. If anyone knows differently,
* please tell me about it. - Ian
*/
/*** irrelevancies ***/
void sqResolverAbort(void) {}
void sqResolverStartAddrLookup(sqInt address)
{
const char *res;
res= addrToName(address);
strncpy(lastName, res, MAXHOSTNAMELEN);
FPRINTF((stderr, "startAddrLookup %s\n", lastName));
}
sqInt sqResolverStatus(void)
{
if (!thisNetSession)
return ResolverUninitialised;
if (lastError != 0)
return ResolverError;
return ResolverSuccess;
}
/*** trivialities ***/
sqInt sqResolverAddrLookupResultSize(void) { return strlen(lastName); }
sqInt sqResolverError(void) { return lastError; }
sqInt sqResolverLocalAddress(void) { return nameToAddr(localHostName); }
sqInt sqResolverNameLookupResult(void) { return lastAddr; }
void sqResolverAddrLookupResult(char *nameForAddress, sqInt nameSize)
{
memcpy(nameForAddress, lastName, nameSize);
}
/*** name resolution ***/
void sqResolverStartNameLookup(char *hostName, sqInt nameSize)
{
int len= (nameSize < MAXHOSTNAMELEN) ? nameSize : MAXHOSTNAMELEN;
memcpy(lastName, hostName, len);
lastName[len]= lastError= 0;
FPRINTF((stderr, "name lookup %s\n", lastName));
lastAddr= nameToAddr(lastName);
/* we're done before we even started */
interpreterProxy->signalSemaphoreWithIndex(resolverSema);
}
/* ikp 2007-06-07: Generalised primitives for IPv6, &c. */
/* flags */
#define SQ_SOCKET_NUMERIC (1<<0)
#define SQ_SOCKET_PASSIVE (1<<1)
/* family */
#define SQ_SOCKET_FAMILY_UNSPECIFIED 0
#define SQ_SOCKET_FAMILY_LOCAL 1
#define SQ_SOCKET_FAMILY_INET4 2
#define SQ_SOCKET_FAMILY_INET6 3
#define SQ_SOCKET_FAMILY_MAX 4
/* type */
#define SQ_SOCKET_TYPE_UNSPECIFIED 0
#define SQ_SOCKET_TYPE_STREAM 1
#define SQ_SOCKET_TYPE_DGRAM 2
#define SQ_SOCKET_TYPE_MAX 3
/* protocol */
#define SQ_SOCKET_PROTOCOL_UNSPECIFIED 0
#define SQ_SOCKET_PROTOCOL_TCP 1
#define SQ_SOCKET_PROTOCOL_UDP 2
#define SQ_SOCKET_PROTOCOL_MAX 3
void sqResolverGetAddressInfoHostSizeServiceSizeFlagsFamilyTypeProtocol(char *hostName, sqInt hostSize, char *servName, sqInt servSize,
sqInt flags, sqInt family, sqInt type, sqInt protocol);
sqInt sqResolverGetAddressInfoSize(void);
void sqResolverGetAddressInfoResultSize(char *addr, sqInt addrSize);
sqInt sqResolverGetAddressInfoFamily(void);
sqInt sqResolverGetAddressInfoType(void);
sqInt sqResolverGetAddressInfoProtocol(void);
sqInt sqResolverGetAddressInfoNext(void);
sqInt sqSocketAddressSizeGetPort(char *addr, sqInt addrSize);
void sqSocketAddressSizeSetPort(char *addr, sqInt addrSize, sqInt port);
void sqResolverGetNameInfoSizeFlags(char *addr, sqInt addrSize, sqInt flags);
sqInt sqResolverGetNameInfoHostSize(void);
void sqResolverGetNameInfoHostResultSize(char *name, sqInt nameSize);
sqInt sqResolverGetNameInfoServiceSize(void);
void sqResolverGetNameInfoServiceResultSize(char *name, sqInt nameSize);
sqInt sqResolverHostNameSize(void);
void sqResolverHostNameResultSize(char *name, sqInt nameSize);
void sqSocketBindToAddressSize(SocketPtr s, char *addr, sqInt addrSize);
void sqSocketListenBacklog(SocketPtr s, sqInt backlogSize);
void sqSocketConnectToAddressSize(SocketPtr s, char *addr, sqInt addrSize);
sqInt sqSocketLocalAddressSize(SocketPtr s);
void sqSocketLocalAddressResultSize(SocketPtr s, char *addr, int addrSize);
sqInt sqSocketRemoteAddressSize(SocketPtr s);
void sqSocketRemoteAddressResultSize(SocketPtr s, char *addr, int addrSize);
sqInt sqSocketSendUDPToSizeDataBufCount(SocketPtr s, char *addr, sqInt addrSize, char *buf, sqInt bufSize);
sqInt sqSocketReceiveUDPDataBufCount(SocketPtr s, char *buf, sqInt bufSize);
/* ---- address and service lookup ---- */
static struct addrinfo *addrList= 0;
static struct addrinfo *addrInfo= 0;
static struct addrinfo *localInfo= 0;
void sqResolverGetAddressInfoHostSizeServiceSizeFlagsFamilyTypeProtocol(char *hostName, sqInt hostSize, char *servName, sqInt servSize,
sqInt flags, sqInt family, sqInt type, sqInt protocol)
{
char host[MAXHOSTNAMELEN+1], serv[MAXHOSTNAMELEN+1];
struct addrinfo request;
int gaiError= 0;
FPRINTF((stderr, "GetAddressInfo %d %d %d %d %d %d\n", hostSize, servSize, flags, family, type, protocol));
if (addrList)
{
freeaddrinfo(addrList);
addrList= addrInfo= 0;
}
if (localInfo)
{
free(localInfo->ai_addr);
free(localInfo);
localInfo= addrInfo= 0;
}
if ((!thisNetSession)
|| (hostSize < 0) || (hostSize > MAXHOSTNAMELEN)
|| (servSize < 0) || (servSize > MAXHOSTNAMELEN)
|| (family < 0) || (family >= SQ_SOCKET_FAMILY_MAX)
|| (type < 0) || (type >= SQ_SOCKET_TYPE_MAX)
|| (protocol < 0) || (protocol >= SQ_SOCKET_PROTOCOL_MAX))
goto fail;
if (hostSize)
memcpy(host, hostName, hostSize);
host[hostSize]= '\0';
if (servSize)
memcpy(serv, servName, servSize);
serv[servSize]= '\0';
FPRINTF((stderr, " -> GetAddressInfo %s %s\n", host, serv));
if (servSize && (family == SQ_SOCKET_FAMILY_LOCAL) && (servSize < sizeof(((struct sockaddr_un *)0)->sun_path)) && !(flags & SQ_SOCKET_NUMERIC))
{
struct stat st;
if ((0 == stat(servName, &st)) && (st.st_mode & S_IFSOCK))
{
struct sockaddr_un *saun= calloc(1, sizeof(struct sockaddr_un));
localInfo= (struct addrinfo *)calloc(1, sizeof(struct addrinfo));
localInfo->ai_family= AF_UNIX;
localInfo->ai_socktype= SOCK_STREAM;
localInfo->ai_addrlen= sizeof(struct sockaddr_un);
localInfo->ai_addr= (struct sockaddr *)saun;
/*saun->sun_len= sizeof(struct sockaddr_un);*/
saun->sun_family= AF_UNIX;
memcpy(saun->sun_path, servName, servSize);
saun->sun_path[servSize]= '\0';
addrInfo= localInfo;
interpreterProxy->signalSemaphoreWithIndex(resolverSema);
return;
}
}
memset(&request, 0, sizeof(request));
if (flags & SQ_SOCKET_NUMERIC) request.ai_flags |= AI_NUMERICHOST;
if (flags & SQ_SOCKET_PASSIVE) request.ai_flags |= AI_PASSIVE;
switch (family)
{
case SQ_SOCKET_FAMILY_LOCAL: request.ai_family= AF_UNIX; break;
case SQ_SOCKET_FAMILY_INET4: request.ai_family= AF_INET; break;
case SQ_SOCKET_FAMILY_INET6: request.ai_family= AF_INET6; break;
}
switch (type)
{
case SQ_SOCKET_TYPE_STREAM: request.ai_socktype= SOCK_STREAM; break;
case SQ_SOCKET_TYPE_DGRAM: request.ai_socktype= SOCK_DGRAM; break;
}
switch (protocol)
{
case SQ_SOCKET_PROTOCOL_TCP: request.ai_protocol= IPPROTO_TCP; break;
case SQ_SOCKET_PROTOCOL_UDP: request.ai_protocol= IPPROTO_UDP; break;
}
gaiError= getaddrinfo(hostSize ? host : 0, servSize ? serv : 0, &request, &addrList);
if (gaiError)
{
/* Linux gives you either <netdb.h> with correct NI_* bit definitions and no EAI_* definitions at all
or <bind/netdb.h> with incorrect NI_* bit definitions and the EAI_* definitions we need.
We cannot distinguish between impossible constraints and genuine lookup failure, so err conservatively. */
# if defined(EAI_BADHINTS)
if (EAI_BADHINTS != gaiError)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gaiError));
lastError= gaiError;
goto fail;
}
# else
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gaiError));
# endif
addrList= 0; /* succeed with zero results for impossible constraints */
}
addrInfo= addrList;
interpreterProxy->signalSemaphoreWithIndex(resolverSema);
return;
fail:
interpreterProxy->success(false);
return;
}
struct addressHeader
{
int sessionID;
int size;
};
#define AddressHeaderSize sizeof(struct addressHeader)
#define addressHeader(A) ((struct addressHeader *)(A))
#define socketAddress(A) ((struct sockaddr *)((char *)(A) + AddressHeaderSize))
#define addressValid(A, S) (thisNetSession && (thisNetSession == addressHeader(A)->sessionID) && (addressHeader(A)->size == (S) - AddressHeaderSize))
#define addressSize(A) (addressHeader(A)->size)
#if 0
static void dumpAddr(struct sockaddr *addr, int addrSize)
{
int i;
for (i= 0; i < addrSize; ++i)
fprintf(stderr, "%02x ", ((unsigned char *)addr)[i]);
fprintf(stderr, " ");
switch (addr->sa_family)
{
case AF_UNIX: fprintf(stderr, "local\n"); break;
case AF_INET: fprintf(stderr, "inet\n"); break;
case AF_INET6: fprintf(stderr, "inet6\n"); break;
default: fprintf(stderr, "?\n"); break;
}
}
#endif
sqInt sqResolverGetAddressInfoSize(void)
{
if (!addrInfo)
return -1;
return AddressHeaderSize + addrInfo->ai_addrlen;
}
void sqResolverGetAddressInfoResultSize(char *addr, sqInt addrSize)
{
if ((!addrInfo) || (addrSize < AddressHeaderSize + addrInfo->ai_addrlen))
{
interpreterProxy->success(false);
return;
}
addressHeader(addr)->sessionID= thisNetSession;
addressHeader(addr)->size= addrInfo->ai_addrlen;
memcpy(socketAddress(addr), addrInfo->ai_addr, addrInfo->ai_addrlen);
/*dumpAddr(socketAddress(addr), addrSize - AddressHeaderSize);*/
}
sqInt sqResolverGetAddressInfoFamily(void)
{
if (!addrInfo)
{
interpreterProxy->success(false);
return 0;
}
switch (addrInfo->ai_family)
{
case AF_UNIX: return SQ_SOCKET_FAMILY_LOCAL;
case AF_INET: return SQ_SOCKET_FAMILY_INET4;
case AF_INET6: return SQ_SOCKET_FAMILY_INET6;
}
return SQ_SOCKET_FAMILY_UNSPECIFIED;
}
sqInt sqResolverGetAddressInfoType(void)
{
if (!addrInfo)
{
interpreterProxy->success(false);
return 0;
}
switch (addrInfo->ai_socktype)
{
case SOCK_STREAM: return SQ_SOCKET_TYPE_STREAM;
case SOCK_DGRAM: return SQ_SOCKET_TYPE_DGRAM;
}
return SQ_SOCKET_TYPE_UNSPECIFIED;
}
sqInt sqResolverGetAddressInfoProtocol(void)
{
if (!addrInfo)
{
interpreterProxy->success(false);
return 0;
}
switch (addrInfo->ai_protocol)
{
case IPPROTO_TCP: return SQ_SOCKET_PROTOCOL_TCP;
case IPPROTO_UDP: return SQ_SOCKET_PROTOCOL_UDP;
}
return SQ_SOCKET_PROTOCOL_UNSPECIFIED;
}
sqInt sqResolverGetAddressInfoNext(void)
{
return (addrInfo && (addrInfo= addrInfo->ai_next)) ? true : false;
}
/* ---- address manipulation ---- */
sqInt sqSocketAddressSizeGetPort(char *addr, sqInt addrSize)
{
if (addressValid(addr, addrSize))
switch (socketAddress(addr)->sa_family)
{
case AF_INET: return ntohs(((struct sockaddr_in *)socketAddress(addr))->sin_port);
case AF_INET6: return ntohs(((struct sockaddr_in6 *)socketAddress(addr))->sin6_port);
}
interpreterProxy->success(false);
return 0;
}
void sqSocketAddressSizeSetPort(char *addr, sqInt addrSize, sqInt port)
{
if (addressValid(addr, addrSize))
switch (socketAddress(addr)->sa_family)
{
case AF_INET: ((struct sockaddr_in *)socketAddress(addr))->sin_port= htons(port); return;
case AF_INET6: ((struct sockaddr_in6 *)socketAddress(addr))->sin6_port= htons(port); return;
}
interpreterProxy->success(false);
}
/* ---- host name lookup ---- */
static char hostNameInfo[MAXHOSTNAMELEN+1];
static char servNameInfo[MAXHOSTNAMELEN+1];
static int nameInfoValid= 0;
void sqResolverGetNameInfoSizeFlags(char *addr, sqInt addrSize, sqInt flags)
{
int niFlags= 0;
int gaiError= 0;
FPRINTF((stderr, "GetNameInfoSizeFlags %p %d %d\n", addr, addrSize, flags));
nameInfoValid= 0;
if (!addressValid(addr, addrSize))
goto fail;
niFlags |= NI_NOFQDN;
if (flags & SQ_SOCKET_NUMERIC) niFlags |= (NI_NUMERICHOST | NI_NUMERICSERV);
/*dumpAddr(socketAddress(addr), addrSize - AddressHeaderSize); fprintf(stderr, "%02x\n", niFlags);*/
gaiError= getnameinfo(socketAddress(addr), addrSize - AddressHeaderSize,
hostNameInfo, sizeof(hostNameInfo),
servNameInfo, sizeof(servNameInfo),
niFlags);
if (gaiError)
{
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(gaiError));
lastError= gaiError;
goto fail;
}
nameInfoValid= 1;
interpreterProxy->signalSemaphoreWithIndex(resolverSema);
return;
fail:
interpreterProxy->success(false);
}
sqInt sqResolverGetNameInfoHostSize(void)
{
if (!nameInfoValid)
{
interpreterProxy->success(false);
return 0;
}
return strlen(hostNameInfo);
}
void sqResolverGetNameInfoHostResultSize(char *name, sqInt nameSize)
{
int len;
if (!nameInfoValid)
goto fail;
len= strlen(hostNameInfo);
if (nameSize < len)
goto fail;
memcpy(name, hostNameInfo, len);
return;
fail:
interpreterProxy->success(false);
}
sqInt sqResolverGetNameInfoServiceSize(void)
{
if (!nameInfoValid)
{
interpreterProxy->success(false);
return 0;
}
return strlen(servNameInfo);
}
void sqResolverGetNameInfoServiceResultSize(char *name, sqInt nameSize)
{
int len;
if (!nameInfoValid)
goto fail;
len= strlen(servNameInfo);
if (nameSize < len)
goto fail;
memcpy(name, servNameInfo, len);
return;
fail:
interpreterProxy->success(false);
}
sqInt sqResolverHostNameSize(void)
{
char buf[MAXHOSTNAMELEN+1];
if (gethostname(buf, sizeof(buf)))
{
interpreterProxy->success(false);
return 0;
}
return strlen(buf);
}
void sqResolverHostNameResultSize(char *name, sqInt nameSize)
{
char buf[MAXHOSTNAMELEN+1];
int len;
if (gethostname(buf, sizeof(buf)) || (nameSize < (len= strlen(buf))))
{
interpreterProxy->success(false);
return;
}
memcpy(name, buf, len);
}
/* ---- circuit setup ---- */
void sqSocketBindToAddressSize(SocketPtr s, char *addr, sqInt addrSize)
{
int result;
privateSocketStruct *pss= PSP(s);
if (!(socketValid(s) && addressValid(addr, addrSize)))
goto fail;
if (bind(SOCKET(s), socketAddress(addr), addressSize(addr)) == 0)
return;
pss->sockError= errno;
fail:
interpreterProxy->success(false);
}
void sqSocketListenBacklog(SocketPtr s, sqInt backlogSize)
{
if (!socketValid(s))
goto fail;
if ((backlogSize > 1) && (s->socketType != TCPSocketType))
goto fail;
PSP(s)->multiListen= (backlogSize > 1);
FPRINTF((stderr, "listenBacklog(%d, %d)\n", SOCKET(s), backlogSize));
if (TCPSocketType == s->socketType)
{
listen(SOCKET(s), backlogSize); /* acceptHandler catches errors */
SOCKETSTATE(s)= WaitingForConnection;
aioEnable(SOCKET(s), PSP(s), 0);
aioHandle(SOCKET(s), acceptHandler, AIO_RX); /* R => accept() */
}
return;
fail:
interpreterProxy->success(false);
return;
}
void sqSocketConnectToAddressSize(SocketPtr s, char *addr, sqInt addrSize)
{
/* TCP => open a connection.
* UDP => set remote address.
*/
if (!(socketValid(s) && addressValid(addr, addrSize)))
{
interpreterProxy->success(false);
return;
}
FPRINTF((stderr, "connectToAddressSize(%d)\n", SOCKET(s)));
if (UDPSocketType == s->socketType) /* --- UDP --- */
{
if (SOCKET(s) >= 0)
{
memcpy((void *)&SOCKETPEER(s), socketAddress(addr), addressSize(addr));
SOCKETPEERSIZE(s)= addressSize(addr);
SOCKETSTATE(s)= Connected;
}
}
else /* --- TCP --- */
{
int result;
aioEnable(SOCKET(s), PSP(s), 0);
result= connect(SOCKET(s), socketAddress(addr), addressSize(addr));
FPRINTF((stderr, "connect() => %d\n", result));
if (result == 0)
{
/* connection completed synchronously */
SOCKETSTATE(s)= Connected;
notify(PSP(s), CONN_NOTIFY);
setLinger(SOCKET(s), 1);
}
else
{
if (errno == EINPROGRESS || errno == EWOULDBLOCK)
{
/* asynchronous connection in progress */
SOCKETSTATE(s)= WaitingForConnection;
aioHandle(SOCKET(s), connectHandler, AIO_WX); /* W => connect() */
}
else
{
/* connection error */
perror("sqConnectToAddressSize");
SOCKETSTATE(s)= Unconnected;
SOCKETERROR(s)= errno;
notify(PSP(s), CONN_NOTIFY);
}
}
}
}
sqInt sqSocketLocalAddressSize(SocketPtr s)
{
union sockaddr_any saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (getsockname(SOCKET(s), &saddr.sa, &saddrSize))
return 0;
return AddressHeaderSize + saddrSize;
}
void sqSocketLocalAddressResultSize(SocketPtr s, char *addr, int addrSize)
{
union sockaddr_any saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
goto fail;
if (getsockname(SOCKET(s), &saddr.sa, &saddrSize))
goto fail;
if (addrSize != AddressHeaderSize + saddrSize)
goto fail;
addressHeader(addr)->sessionID= thisNetSession;
addressHeader(addr)->size= saddrSize;
memcpy(socketAddress(addr), &saddr.sa, saddrSize);
return;
fail:
interpreterProxy->success(false);
return;
}
sqInt sqSocketRemoteAddressSize(SocketPtr s)
{
union sockaddr_any saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
return -1;
if (TCPSocketType == s->socketType) /* --- TCP --- */
{
if (0 == getpeername(SOCKET(s), &saddr.sa, &saddrSize))
{
if (saddrSize < sizeof(SOCKETPEER(s)))
{
memcpy(&SOCKETPEER(s), &saddr.sa, saddrSize);
return AddressHeaderSize + (SOCKETPEERSIZE(s)= saddrSize);
}
}
}
else if (SOCKETPEERSIZE(s)) /* --- UDP --- */
{
return AddressHeaderSize + SOCKETPEERSIZE(s);
}
return -1;
}
void sqSocketRemoteAddressResultSize(SocketPtr s, char *addr, int addrSize)
{
union sockaddr_any saddr;
socklen_t saddrSize= sizeof(saddr);
if (!socketValid(s))
goto fail;
if ((!SOCKETPEERSIZE(s)) || (addrSize != AddressHeaderSize + SOCKETPEERSIZE(s)))
goto fail;
addressHeader(addr)->sessionID= thisNetSession;
addressHeader(addr)->size= SOCKETPEERSIZE(s);
memcpy(socketAddress(addr), &SOCKETPEER(s), SOCKETPEERSIZE(s));
SOCKETPEERSIZE(s)= 0;
return;
fail:
interpreterProxy->success(false);
return;
}
/* ---- communication ---- */
sqInt sqSocketSendUDPToSizeDataBufCount(SocketPtr s, char *addr, sqInt addrSize, char *buf, sqInt bufSize)
{
FPRINTF((stderr, "sendTo(%d)\n", SOCKET(s)));
if (socketValid(s) && addressValid(addr, addrSize) && (UDPSocketType == s->socketType))
{
int nsent= sendto(SOCKET(s), buf, bufSize, 0, socketAddress(addr), addrSize - AddressHeaderSize);
if (nsent >= 0)
return nsent;
if (errno == EWOULDBLOCK) /* asynchronous write in progress */
return 0;
FPRINTF((stderr, "UDP send failed\n"));
SOCKETERROR(s)= errno;
}
interpreterProxy->success(false);
return 0;
}
sqInt sqSocketReceiveUDPDataBufCount(SocketPtr s, char *buf, sqInt bufSize)
{
FPRINTF((stderr, "recvFrom(%d)\n", SOCKET(s)));
if (socketValid(s) && (UDPSocketType == s->socketType))
{
socklen_t saddrSize= sizeof(SOCKETPEER(s));
int nread= recvfrom(SOCKET(s), buf, bufSize, 0, &SOCKETPEER(s).sa, &saddrSize);
if (nread >= 0)
{
SOCKETPEERSIZE(s)= saddrSize;
return nread;
}
SOCKETPEERSIZE(s)= 0;
if (errno == EWOULDBLOCK) /* asynchronous read in progress */
return 0;
SOCKETERROR(s)= errno;
FPRINTF((stderr, "receiveData(%d)= %da\n", SOCKET(s), 0));
}
interpreterProxy->success(false);
return 0;
}
|