开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 644

fate-intel/HP-Socket

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
HP-Socket
/
Linux
/
src
/
SocketHelper.cpp
HP-Socket
/
Linux
/
src
/
SocketHelper.cpp
SocketHelper.cpp 40.15 KB
一键复制 编辑 原始数据 按行查看 历史
伤神小怪兽 提交于 2024年01月24日 16:56 +08:00 . 20240124
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
/*
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
*
* Author : Bruce Liang
* Website : https://github.com/ldcsaa
* Project : https://github.com/ldcsaa/HP-Socket
* Blog : http://www.cnblogs.com/ldcsaa
* Wiki : http://www.oschina.net/p/hp-socket
* QQ Group : 44636872, 75375912
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SocketHelper.h"
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#ifdef _ICONV_SUPPORT
#include <iconv.h>
#endif
#ifndef SO_REUSEPORT
#define SO_REUSEPORT 15
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
static const BYTE s_szUdpCloseNotify[] = {0xBE, 0xB6, 0x1F, 0xEB, 0xDA, 0x52, 0x46, 0xBA, 0x92, 0x33, 0x59, 0xDB, 0xBF, 0xE6, 0xC8, 0xE4};
static const int s_iUdpCloseNotifySize = ARRAY_SIZE(s_szUdpCloseNotify);
const hp_addr hp_addr::ANY_ADDR4(AF_INET, TRUE);
const hp_addr hp_addr::ANY_ADDR6(AF_INET6, TRUE);
BOOL SetCurrentWorkerThreadName()
{
return SetWorkerThreadDefaultName(0);
}
BOOL SetWorkerThreadDefaultName(THR_ID tid)
{
static volatile UINT _s_uiSeq = MAXUINT;
return ::SetSequenceThreadName(tid, DEFAULT_WORKER_THREAD_PREFIX, _s_uiSeq);
}
LPCTSTR GetSocketErrorDesc(EnSocketError enCode)
{
switch(enCode)
{
case SE_OK: return _T("SUCCESS");
case SE_ILLEGAL_STATE: return _T("Illegal State");
case SE_INVALID_PARAM: return _T("Invalid Parameter");
case SE_SOCKET_CREATE: return _T("Create SOCKET Fail");
case SE_SOCKET_BIND: return _T("Bind SOCKET Fail");
case SE_SOCKET_PREPARE: return _T("Prepare SOCKET Fail");
case SE_SOCKET_LISTEN: return _T("Listen SOCKET Fail");
case SE_CP_CREATE: return _T("Create IOCP Fail");
case SE_WORKER_THREAD_CREATE: return _T("Create Worker Thread Fail");
case SE_DETECT_THREAD_CREATE: return _T("Create Detector Thread Fail");
case SE_SOCKE_ATTACH_TO_CP: return _T("Attach SOCKET to IOCP Fail");
case SE_CONNECT_SERVER: return _T("Connect to Server Fail");
case SE_NETWORK: return _T("Network Error");
case SE_DATA_PROC: return _T("Process Data Error");
case SE_DATA_SEND: return _T("Send Data Fail");
case SE_SSL_ENV_NOT_READY: return _T("SSL environment not ready");
default: ASSERT(FALSE); return _T("UNKNOWN ERROR");
}
}
ADDRESS_FAMILY DetermineAddrFamily(LPCTSTR lpszAddress)
{
if (!lpszAddress || lpszAddress[0] == 0)
return AF_UNSPEC;
if(::StrChr(lpszAddress, IPV6_ADDR_SEPARATOR_CHAR))
return AF_INET6;
TCHAR c;
int arr[4];
if(stscanf(lpszAddress, _T("%d.%d.%d.%d%c"), &arr[0], &arr[1], &arr[2], &arr[3], &c) != 4)
return AF_UNSPEC;
for(int i = 0; i < 4; i++)
{
if(arr[i] < 0 || arr[i] > 255)
return AF_UNSPEC;
}
return AF_INET;
}
BOOL GetInAddr(LPCTSTR lpszAddress, HP_ADDR& addr)
{
addr.family = DetermineAddrFamily(lpszAddress);
if (addr.family == AF_UNSPEC)
return FALSE;
return (::InetPton(addr.family, lpszAddress, addr.Addr()) == TRUE);
}
BOOL GetSockAddr(LPCTSTR lpszAddress, USHORT usPort, HP_SOCKADDR& addr)
{
if(addr.family != AF_INET && addr.family != AF_INET6)
{
::WSASetLastError(ERROR_ADDRNOTAVAIL);
return FALSE;
}
if(addr.family == AF_INET6 && StrChr(lpszAddress, IPV6_ZONE_INDEX_CHAR))
return GetSockAddrByHostNameDirectly(lpszAddress, usPort, addr);
addr.ZeroAddr();
int rs = ::InetPton(addr.family, lpszAddress, addr.SinAddr());
if(rs != 1)
{
if(rs == 0) ::WSASetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if(usPort != 0)
addr.SetPort(usPort);
return TRUE;
}
BOOL IsIPAddress(LPCTSTR lpszAddress, EnIPAddrType* penType)
{
HP_ADDR addr;
BOOL isOK = GetInAddr(lpszAddress, addr);
if(isOK && penType)
*penType = addr.IsIPv4() ? IPT_IPV4 : IPT_IPV6;
return isOK;
}
BOOL GetIPAddress(LPCTSTR lpszHost, LPTSTR lpszIP, int& iIPLen, EnIPAddrType& enType)
{
HP_SOCKADDR addr;
if(!GetSockAddrByHostName(lpszHost, 0, addr))
return FALSE;
enType = addr.IsIPv4() ? IPT_IPV4 : IPT_IPV6;
USHORT usPort;
ADDRESS_FAMILY usFamily;
return sockaddr_IN_2_A(addr, usFamily, lpszIP, iIPLen, usPort);
}
BOOL GetSockAddrByHostName(LPCTSTR lpszHost, USHORT usPort, HP_SOCKADDR& addr)
{
addr.family = DetermineAddrFamily(lpszHost);
if(addr.family != AF_UNSPEC)
return GetSockAddr(lpszHost, usPort, addr);
return GetSockAddrByHostNameDirectly(lpszHost, usPort, addr);
}
BOOL GetSockAddrByHostNameDirectly(LPCTSTR lpszHost, USHORT usPort, HP_SOCKADDR& addr)
{
addr.ZeroAddr();
addrinfo* pInfo = nullptr;
addrinfo hints = {0};
#if defined(__ANDROID__)
hints.ai_flags = 0;
#else
hints.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG);
#endif
hints.ai_family = addr.family;
hints.ai_socktype = SOCK_STREAM;
int rs = ::getaddrinfo(CT2A(lpszHost), nullptr, &hints, &pInfo);
if(!IS_NO_ERROR(rs))
{
::WSASetLastError(ERROR_HOSTUNREACH);
return FALSE;
}
BOOL isOK = FALSE;
for(addrinfo* pCur = pInfo; pCur != nullptr; pCur = pCur->ai_next)
{
if(pCur->ai_family == AF_INET || pCur->ai_family == AF_INET6)
{
memcpy(addr.Addr(), pCur->ai_addr, pCur->ai_addrlen);
isOK = TRUE;
break;
}
}
EXECUTE_RESTORE_ERROR(::freeaddrinfo(pInfo));
if(isOK)
addr.SetPort(usPort);
else
::WSASetLastError(ERROR_HOSTUNREACH);
return isOK;
}
BOOL EnumHostIPAddresses(LPCTSTR lpszHost, EnIPAddrType enType, LPTIPAddr** lpppIPAddr, int& iIPAddrCount)
{
*lpppIPAddr = nullptr;
iIPAddrCount = 0;
ADDRESS_FAMILY usFamily = (enType == IPT_ALL ?
AF_UNSPEC : (enType == IPT_IPV4 ?
AF_INET : (enType == IPT_IPV6 ?
AF_INET6 : 0xFF)));
if(usFamily == 0xFF)
{
::WSASetLastError(ERROR_AFNOSUPPORT);
return FALSE;
}
vector<HP_PSOCKADDR> vt;
ADDRESS_FAMILY usFamily2 = DetermineAddrFamily(lpszHost);
if(usFamily2 != AF_UNSPEC)
{
if(usFamily != AF_UNSPEC && usFamily != usFamily2)
{
::WSASetLastError(ERROR_HOSTUNREACH);
return FALSE;
}
HP_SOCKADDR addr(usFamily2);
if(!GetSockAddr(lpszHost, 0, addr))
return FALSE;
vt.emplace_back(&addr);
return RetrieveSockAddrIPAddresses(vt, lpppIPAddr, iIPAddrCount);
}
addrinfo* pInfo = nullptr;
addrinfo hints = {0};
#if defined(__ANDROID__)
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ALL;
#endif
hints.ai_family = usFamily;
hints.ai_socktype = SOCK_STREAM;
int rs = ::getaddrinfo(CT2A(lpszHost), nullptr, &hints, &pInfo);
if(rs != NO_ERROR)
{
::WSASetLastError(rs);
return FALSE;
}
for(addrinfo* pCur = pInfo; pCur != nullptr; pCur = pCur->ai_next)
{
if(pCur->ai_family == AF_INET || pCur->ai_family == AF_INET6)
vt.emplace_back((HP_PSOCKADDR)pCur->ai_addr);
}
BOOL isOK = RetrieveSockAddrIPAddresses(vt, lpppIPAddr, iIPAddrCount);
::freeaddrinfo(pInfo);
if(!isOK) ::WSASetLastError(EHOSTUNREACH);
return isOK;
}
BOOL RetrieveSockAddrIPAddresses(const vector<HP_PSOCKADDR>& vt, LPTIPAddr** lpppIPAddr, int& iIPAddrCount)
{
iIPAddrCount = (int)vt.size();
if(iIPAddrCount == 0) return FALSE;
HP_PSOCKADDR pSockAddr;
ADDRESS_FAMILY usFamily;
USHORT usPort;
int iAddrLength;
LPTSTR lpszAddr;
LPTIPAddr lpItem;
(*lpppIPAddr) = new LPTIPAddr[iIPAddrCount + 1];
(*lpppIPAddr)[iIPAddrCount] = nullptr;
for(int i = 0; i < iIPAddrCount; i++)
{
pSockAddr = vt[i];
iAddrLength = HP_SOCKADDR::AddrMinStrLength(pSockAddr->family);
lpszAddr = new TCHAR[iAddrLength];
VERIFY(sockaddr_IN_2_A(*vt[i], usFamily, lpszAddr, iAddrLength, usPort));
lpItem = new TIPAddr;
lpItem->type = pSockAddr->IsIPv4() ? IPT_IPV4 : IPT_IPV6;
lpItem->address = lpszAddr;
(*lpppIPAddr)[i] = lpItem;
}
return TRUE;
}
BOOL FreeHostIPAddresses(LPTIPAddr* lppIPAddr)
{
if(!lppIPAddr) return FALSE;
LPTIPAddr p;
LPTIPAddr* lppCur = lppIPAddr;
while((p = *lppCur++) != nullptr)
{
delete[] p->address;
delete p;
}
delete[] lppIPAddr;
return TRUE;
}
BOOL sockaddr_IN_2_A(const HP_SOCKADDR& addr, ADDRESS_FAMILY& usFamily, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
BOOL isOK = FALSE;
usFamily = addr.family;
usPort = addr.Port();
if(::InetNtop(addr.family, addr.SinAddr(), lpszAddress, iAddressLen))
{
iAddressLen = (int)lstrlen(lpszAddress) + 1;
isOK = TRUE;
}
else
{
if(::WSAGetLastError() == ENOSPC)
iAddressLen = HP_SOCKADDR::AddrMinStrLength(usFamily);
}
return isOK;
}
BOOL sockaddr_A_2_IN(LPCTSTR lpszAddress, USHORT usPort, HP_SOCKADDR& addr)
{
addr.family = DetermineAddrFamily(lpszAddress);
return GetSockAddr(lpszAddress, usPort, addr);
}
BOOL GetSocketAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort, BOOL bLocal)
{
HP_SOCKADDR addr;
int addr_len = addr.AddrSize();
int result = bLocal ? getsockname(socket, addr.Addr(), (socklen_t*)&addr_len) : getpeername(socket, addr.Addr(), (socklen_t*)&addr_len);
if(result != NO_ERROR)
return FALSE;
ADDRESS_FAMILY usFamily;
return sockaddr_IN_2_A(addr, usFamily, lpszAddress, iAddressLen, usPort);
}
BOOL GetSocketLocalAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
return GetSocketAddress(socket, lpszAddress, iAddressLen, usPort, TRUE);
}
BOOL GetSocketRemoteAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
return GetSocketAddress(socket, lpszAddress, iAddressLen, usPort, FALSE);
}
BOOL SetMultiCastSocketOptions(SOCKET sock, const HP_SOCKADDR& bindAddr, const HP_SOCKADDR& castAddr, int iMCTtl, BOOL bMCLoop)
{
if(castAddr.IsIPv4())
{
BYTE ttl = (BYTE)iMCTtl;
BYTE loop = (BYTE)bMCLoop;
VERIFY(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) != SOCKET_ERROR);
VERIFY(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) != SOCKET_ERROR);
ip_mreq mcast;
::ZeroMemory(&mcast, sizeof(mcast));
mcast.imr_multiaddr = castAddr.addr4.sin_addr;
mcast.imr_interface = bindAddr.addr4.sin_addr;
if(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast)) == SOCKET_ERROR)
return FALSE;
if(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_MULTICAST_IF, bindAddr.SinAddr(), sizeof(IN_ADDR)) == SOCKET_ERROR)
return FALSE;
}
else
{
INT ttl = (INT)iMCTtl;
UINT loop = (UINT)bMCLoop;
VERIFY(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) != SOCKET_ERROR);
VERIFY(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop)) != SOCKET_ERROR);
ipv6_mreq mcast;
::ZeroMemory(&mcast, sizeof(mcast));
mcast.ipv6mr_multiaddr = castAddr.addr6.sin6_addr;
mcast.ipv6mr_interface = bindAddr.addr6.sin6_scope_id;
if(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mcast, sizeof(mcast)) == SOCKET_ERROR)
return FALSE;
if(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, (PVOID)(&bindAddr.addr6.sin6_scope_id), sizeof(UINT)) == SOCKET_ERROR)
return FALSE;
}
return TRUE;
}
int WaitForSocketWrite(SOCKET sock, DWORD dwTimeout)
{
timeval tv = {(__time_t)(dwTimeout / 1000), (__suseconds_t)((dwTimeout % 1000) * 1000)};
fd_set wfds, efds;
FD_ZERO(&wfds);
FD_ZERO(&efds);
FD_SET(sock, &wfds);
FD_SET(sock, &efds);
int rs = NO_EINTR_INT(select(sock + 1, nullptr, &wfds, &efds, &tv));
if(rs <= 0) return ((rs == 0) ? ERROR_TIMEOUT : ENSURE_ERROR(ERROR_CANT_WAIT));
if(FD_ISSET(sock, &efds))
{
rs = SSO_GetError(sock);
return ((rs != NO_ERROR && rs != SOCKET_ERROR) ? rs : ENSURE_ERROR(ERROR_CANT_WAIT));
}
VERIFY(FD_ISSET(sock, &wfds));
rs = SSO_GetError(sock);
if(!IS_NO_ERROR(rs))
return ((rs != SOCKET_ERROR) ? rs : ENSURE_ERROR(ERROR_CANT_WAIT));
return NO_ERROR;
}
ULONGLONG NToH64(ULONGLONG value)
{
return (((ULONGLONG)ntohl((UINT)((value << 32) >> 32))) << 32) | ntohl((UINT)(value >> 32));
}
ULONGLONG HToN64(ULONGLONG value)
{
return (((ULONGLONG)htonl((UINT)((value << 32) >> 32))) << 32) | htonl((UINT)(value >> 32));
}
BOOL IsLittleEndian()
{
static const USHORT _s_endian_test_value = 0x0102;
static const BOOL _s_bLE = (*((BYTE*)&_s_endian_test_value) == 0x02);
return _s_bLE;
}
USHORT HToLE16(USHORT value)
{
return IsLittleEndian() ? value : ENDIAN_SWAP_16(value);
}
USHORT HToBE16(USHORT value)
{
return IsLittleEndian() ? ENDIAN_SWAP_16(value) : value;
}
DWORD HToLE32(DWORD value)
{
return IsLittleEndian() ? value : ENDIAN_SWAP_32(value);
}
DWORD HToBE32(DWORD value)
{
return IsLittleEndian() ? ENDIAN_SWAP_32(value) : value;
}
HRESULT ReadSmallFile(LPCTSTR lpszFileName, CFile& file, CFileMapping& fmap, DWORD dwMaxFileSize)
{
ASSERT(lpszFileName != nullptr);
if(file.Open(lpszFileName, O_RDONLY))
{
SIZE_T dwSize;
if(file.GetSize(dwSize))
{
if(dwSize > 0 && dwSize <= dwMaxFileSize)
{
if(fmap.Map(file, dwSize))
return NO_ERROR;
}
else if(dwSize == 0)
::SetLastError(ERROR_EMPTY);
else
::SetLastError(ERROR_FILE_TOO_LARGE);
}
}
HRESULT rs = ::GetLastError();
return (!IS_NO_ERROR(rs) ? rs : ERROR_UNKNOWN);
}
HRESULT MakeSmallFilePackage(LPCTSTR lpszFileName, CFile& file, CFileMapping& fmap, WSABUF szBuf[3], const LPWSABUF pHead, const LPWSABUF pTail)
{
DWORD dwMaxFileSize = MAX_SMALL_FILE_SIZE - (pHead ? pHead->len : 0) - (pTail ? pTail->len : 0);
ASSERT(dwMaxFileSize <= MAX_SMALL_FILE_SIZE);
HRESULT hr = ReadSmallFile(lpszFileName, file, fmap, dwMaxFileSize);
if(IS_NO_ERROR(hr))
{
szBuf[1].len = (UINT)fmap.Size();
szBuf[1].buf = fmap;
if(pHead) memcpy(&szBuf[0], pHead, sizeof(WSABUF));
else memset(&szBuf[0], 0, sizeof(WSABUF));
if(pTail) memcpy(&szBuf[2], pTail, sizeof(WSABUF));
else memset(&szBuf[2], 0, sizeof(WSABUF));
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
int SSO_SetSocketOption(SOCKET sock, int level, int name, LPVOID val, int len)
{
return setsockopt(sock, level, name, val, (socklen_t)len);
}
int SSO_GetSocketOption(SOCKET sock, int level, int name, LPVOID val, int* len)
{
return getsockopt(sock, level, name, val, (socklen_t*)len);
}
int SSO_IoctlSocket(SOCKET sock, long cmd, PVOID arg)
{
return ioctl(sock, cmd, arg);
}
int SSO_NoBlock(SOCKET sock, BOOL bNoBlock)
{
return fcntl_SETFL(sock, O_NONBLOCK, bNoBlock) ? NO_ERROR : SOCKET_ERROR;
}
int SSO_NoDelay(SOCKET sock, BOOL bNoDelay)
{
int val = bNoDelay ? 1 : 0;
return setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int));
}
int SSO_DontLinger(SOCKET sock, BOOL bDont)
{
return SSO_Linger(sock, 0, 0);
}
int SSO_Linger(SOCKET sock, int l_onoff, int l_linger)
{
linger ln = {l_onoff, l_linger};
return setsockopt(sock, SOL_SOCKET, SO_LINGER, &ln, sizeof(linger));
}
int SSO_KeepAlive(SOCKET sock, BOOL bKeepAlive)
{
int val = bKeepAlive ? 1 : 0;
return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(int));
}
int SSO_KeepAliveVals(SOCKET sock, BOOL bOnOff, DWORD dwIdle, DWORD dwInterval, DWORD dwCount)
{
if(bOnOff)
{
dwIdle /= 1000;
dwInterval /= 1000;
if(dwIdle == 0 || dwInterval == 0 || dwCount == 0)
{
::WSASetLastError(ERROR_INVALID_PARAMETER);
return SOCKET_ERROR;
}
}
BOOL isOK = IS_NO_ERROR(SSO_KeepAlive(sock, bOnOff));
if(isOK && bOnOff)
{
isOK &= IS_NO_ERROR(setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &dwIdle, sizeof(DWORD)));
isOK &= IS_NO_ERROR(setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &dwInterval, sizeof(DWORD)));
isOK &= IS_NO_ERROR(setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &dwCount, sizeof(DWORD)));
}
return isOK ? NO_ERROR : SOCKET_ERROR;
}
int SSO_ReuseAddress(SOCKET sock, EnReuseAddressPolicy opt)
{
int iSet = 1;
int iUnSet = 0;
int rs = NO_ERROR;
BOOL bReusePortSupported =
#if defined(__linux) || defined(__linux__)
::IsKernelVersionAbove(2, 6, 32);
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__APPLE__) || defined(__MACH__)
TRUE;
#else
FALSE;
#endif
if(opt == RAP_NONE)
{
rs = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &iUnSet, sizeof(int));
if(bReusePortSupported)
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &iUnSet, sizeof(int));
}
else if(opt == RAP_ADDR_ONLY)
{
rs = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &iSet, sizeof(int));
if(bReusePortSupported)
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &iUnSet, sizeof(int));
}
else if(opt == RAP_ADDR_AND_PORT)
{
rs = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &iSet, sizeof(int));
if(bReusePortSupported)
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &iSet, sizeof(int));
}
else
{
::SetLastError(ERROR_INVALID_PARAMETER);
rs = -1;
}
return rs;
}
int SSO_RecvBuffSize(SOCKET sock, int size)
{
return setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int));
}
int SSO_SendBuffSize(SOCKET sock, int size)
{
return setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int));
}
int SSO_RecvTimeOut(SOCKET sock, int ms)
{
timeval tv;
::MillisecondToTimeval(ms, tv);
return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
}
int SSO_SendTimeOut(SOCKET sock, int ms)
{
timeval tv;
::MillisecondToTimeval(ms, tv);
return setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
}
int SSO_GetError(SOCKET sock)
{
int e;
socklen_t len = sizeof(e);
if(IS_NO_ERROR(getsockopt(sock, SOL_SOCKET, SO_ERROR, &e, &len)))
return e;
return SOCKET_ERROR;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
CONNID GenerateConnectionID()
{
static volatile CONNID s_dwConnID = 0;
CONNID dwConnID = ::InterlockedIncrement(&s_dwConnID);
if(dwConnID == 0)
dwConnID = ::InterlockedIncrement(&s_dwConnID);
return dwConnID;
}
int IsUdpCloseNotify(const BYTE* pData, int iLength)
{
return (iLength == s_iUdpCloseNotifySize &&
memcmp(pData, s_szUdpCloseNotify, s_iUdpCloseNotifySize) == 0) ;
}
int SendUdpCloseNotify(SOCKET sock)
{
return (int)send(sock, (LPCSTR)s_szUdpCloseNotify, s_iUdpCloseNotifySize, 0);
}
int SendUdpCloseNotify(SOCKET sock, const HP_SOCKADDR& remoteAddr)
{
return (int)sendto(sock, (LPCSTR)s_szUdpCloseNotify, s_iUdpCloseNotifySize, 0, remoteAddr.Addr(), remoteAddr.AddrSize());
}
int ManualCloseSocket(SOCKET sock, int iShutdownFlag, BOOL bGraceful)
{
if(!bGraceful)
SSO_Linger(sock, 1, 0);
if(iShutdownFlag != 0xFF)
shutdown(sock, iShutdownFlag);
return closesocket(sock);
}
DWORD GuessBase64EncodeBound(DWORD dwSrcLen)
{
return 4 * ((dwSrcLen + 2) / 3);
}
DWORD GuessBase64DecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
if(dwSrcLen < 2)
return 0;
if(lpszSrc[dwSrcLen - 2] == '=')
dwSrcLen -= 2;
else if(lpszSrc[dwSrcLen - 1] == '=')
--dwSrcLen;
DWORD dwMod = dwSrcLen % 4;
DWORD dwAdd = dwMod == 2 ? 1 : (dwMod == 3 ? 2 : 0);
return 3 * (dwSrcLen / 4) + dwAdd;
}
int Base64Encode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
static const BYTE CODES[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
DWORD dwRealLen = GuessBase64EncodeBound(dwSrcLen);
if(lpszDest == nullptr || dwDestLen < dwRealLen)
{
dwDestLen = dwRealLen;
return -5;
}
BYTE* p = lpszDest;
DWORD leven = 3 * (dwSrcLen / 3);
DWORD i = 0;
for (; i < leven; i += 3)
{
*p++ = CODES[lpszSrc[0] >> 2];
*p++ = CODES[((lpszSrc[0] & 3) << 4) + (lpszSrc[1] >> 4)];
*p++ = CODES[((lpszSrc[1] & 0xf) << 2) + (lpszSrc[2] >> 6)];
*p++ = CODES[lpszSrc[2] & 0x3f];
lpszSrc += 3;
}
if(i < dwSrcLen)
{
BYTE a = lpszSrc[0];
BYTE b = (i + 1 < dwSrcLen) ? lpszSrc[1] : 0;
*p++ = CODES[a >> 2];
*p++ = CODES[((a & 3) << 4) + (b >> 4)];
*p++ = (i + 1 < dwSrcLen) ? CODES[((b & 0xf) << 2)] : '=';
*p++ = '=';
}
ASSERT(dwRealLen == (DWORD)(p - lpszDest));
if(dwDestLen > dwRealLen)
{
*p = 0;
dwDestLen = dwRealLen;
}
return 0;
}
int Base64Decode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
static const BYTE MAP[256] =
{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255,
255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
255, 254, 255, 255, 255, 0, 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, 255, 255, 255, 255, 255,
255, 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, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255
};
DWORD dwRealLen = GuessBase64DecodeBound(lpszSrc, dwSrcLen);
if(lpszDest == nullptr || dwDestLen < dwRealLen)
{
dwDestLen = dwRealLen;
return -5;
}
BYTE c;
int g = 3;
DWORD i, x, y, z;
for(i = x = y = z = 0; i < dwSrcLen || x != 0;)
{
c = i < dwSrcLen ? MAP[lpszSrc[i++]] : 254;
if(c == 255) {dwDestLen = 0; return -3;}
else if(c == 254) {c = 0; g--;}
else if(c == 253) continue;
z = (z << 6) | c;
if(++x == 4)
{
lpszDest[y++] = (BYTE)((z >> 16) & 255);
if (g > 1) lpszDest[y++] = (BYTE)((z >> 8) & 255);
if (g > 2) lpszDest[y++] = (BYTE)(z & 255);
x = z = 0;
}
}
BOOL isOK = (y == dwRealLen);
if(!isOK)
dwDestLen = 0;
else
{
if(dwDestLen > dwRealLen)
{
lpszDest[dwRealLen] = 0;
dwDestLen = dwRealLen;
}
}
return isOK ? 0 : -3;
}
DWORD GuessUrlEncodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
DWORD dwAdd = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
BYTE c = lpszSrc[i];
if(!(isalnum(c) || c == ' ' || c == '.' || c == '-' || c == '_' || c == '*'))
dwAdd += 2;
}
return dwSrcLen + dwAdd;
}
DWORD GuessUrlDecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
DWORD dwPercent = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(lpszSrc[i] == '%')
{
++dwPercent;
i += 2;
}
}
DWORD dwSub = dwPercent * 2;
if(dwSrcLen < dwSub)
return 0;
return dwSrcLen - dwSub;
}
int UrlEncode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
BYTE c;
DWORD j = 0;
if(lpszDest == nullptr || dwDestLen == 0)
goto ERROR_DEST_LEN;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(j >= dwDestLen)
goto ERROR_DEST_LEN;
c = lpszSrc[i];
if (isalnum(c) || c == '.' || c == '-' || c == '_' || c == '*')
lpszDest[j++] = c;
else if(c == ' ')
lpszDest[j++] = '+';
else
{
if(j + 3 >= dwDestLen)
goto ERROR_DEST_LEN;
lpszDest[j++] = '%';
HEX_VALUE_TO_DOUBLE_CHAR(lpszDest + j, c);
j += 2;
}
}
if(dwDestLen > j)
{
lpszDest[j] = 0;
dwDestLen = j;
}
return 0;
ERROR_DEST_LEN:
dwDestLen = GuessUrlEncodeBound(lpszSrc, dwSrcLen);
return -5;
}
int UrlDecode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
char c;
DWORD j = 0;
if(lpszDest == nullptr || dwDestLen == 0)
goto ERROR_DEST_LEN;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(j >= dwDestLen)
goto ERROR_DEST_LEN;
c = lpszSrc[i];
if(c == '+')
lpszDest[j++] = ' ';
else if(c != '%')
lpszDest[j++] = c;
else
{
if(i + 2 >= dwSrcLen)
goto ERROR_SRC_DATA;
lpszDest[j++] = HEX_DOUBLE_CHAR_TO_VALUE(lpszSrc + i + 1);
i += 2;
}
}
if(dwDestLen > j)
{
lpszDest[j] = 0;
dwDestLen = j;
}
return 0;
ERROR_SRC_DATA:
dwDestLen = 0;
return -3;
ERROR_DEST_LEN:
dwDestLen = GuessUrlDecodeBound(lpszSrc, dwSrcLen);
return -5;
}
void DestroyCompressor(IHPCompressor* pCompressor)
{
delete pCompressor;
}
void DestroyDecompressor(IHPDecompressor* pDecompressor)
{
delete pDecompressor;
}
#ifdef _ZLIB_SUPPORT
CHPZLibCompressor::CHPZLibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits, int iLevel, int iMethod, int iMemLevel, int iStrategy, DWORD dwBuffSize)
: m_fnCallback (fnCallback)
, m_dwBuffSize (dwBuffSize)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
::ZeroObject(m_Stream);
m_bValid = (::deflateInit2(&m_Stream, iLevel, iMethod, iWindowBits, iMemLevel, iStrategy) == Z_OK);
}
CHPZLibCompressor::~CHPZLibCompressor()
{
if(m_bValid) ::deflateEnd(&m_Stream);
}
BOOL CHPZLibCompressor::Reset()
{
return (m_bValid = (::deflateReset(&m_Stream) == Z_OK));
}
BOOL CHPZLibCompressor::Process(const BYTE* pData, int iLength, BOOL bLast, PVOID pContext)
{
return ProcessEx(pData, iLength, bLast, FALSE, pContext);
}
BOOL CHPZLibCompressor::ProcessEx(const BYTE* pData, int iLength, BOOL bLast, BOOL bFlush, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
unique_ptr<BYTE[]> szBuff = make_unique<BYTE[]>(m_dwBuffSize);
m_Stream.next_in = (z_const Bytef*)pData;
m_Stream.avail_in = iLength;
BOOL isOK = TRUE;
int rs = Z_OK;
int flush = bLast ? Z_FINISH : (bFlush ? Z_SYNC_FLUSH : Z_NO_FLUSH);
while(m_Stream.avail_in > 0)
{
do
{
m_Stream.next_out = szBuff.get();
m_Stream.avail_out = m_dwBuffSize;
rs = ::deflate(&m_Stream, flush);
if(rs == Z_STREAM_ERROR)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto ZLIB_COMPRESS_END;
}
int iRead = (int)(m_dwBuffSize - m_Stream.avail_out);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff.get(), iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto ZLIB_COMPRESS_END;
}
} while(m_Stream.avail_out == 0);
}
ZLIB_COMPRESS_END:
ASSERT(!isOK || (rs == Z_OK && !bLast) || (rs == Z_STREAM_END && bLast));
if(!isOK || bLast) Reset();
return isOK;
}
CHPZLibDecompressor::CHPZLibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits, DWORD dwBuffSize)
: m_fnCallback (fnCallback)
, m_dwBuffSize (dwBuffSize)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
::ZeroObject(m_Stream);
m_bValid = (::inflateInit2(&m_Stream, iWindowBits) == Z_OK);
}
CHPZLibDecompressor::~CHPZLibDecompressor()
{
if(m_bValid) ::inflateEnd(&m_Stream);
}
BOOL CHPZLibDecompressor::Reset()
{
return (m_bValid = (::inflateReset(&m_Stream) == Z_OK));
}
BOOL CHPZLibDecompressor::Process(const BYTE* pData, int iLength, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
unique_ptr<BYTE[]> szBuff = make_unique<BYTE[]>(m_dwBuffSize);
m_Stream.next_in = (z_const Bytef*)pData;
m_Stream.avail_in = iLength;
BOOL isOK = TRUE;
int rs = Z_OK;
while(m_Stream.avail_in > 0)
{
do
{
m_Stream.next_out = szBuff.get();
m_Stream.avail_out = m_dwBuffSize;
rs = ::inflate(&m_Stream, Z_NO_FLUSH);
if(rs != Z_OK && rs != Z_STREAM_END)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto ZLIB_DECOMPRESS_END;
}
int iRead = (int)(m_dwBuffSize - m_Stream.avail_out);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff.get(), iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto ZLIB_DECOMPRESS_END;
}
} while(m_Stream.avail_out == 0);
if(rs == Z_STREAM_END)
break;
}
ZLIB_DECOMPRESS_END:
ASSERT(!isOK || rs == Z_OK || rs == Z_STREAM_END);
if(!isOK || rs == Z_STREAM_END) Reset();
return isOK;
}
IHPCompressor* CreateZLibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits, int iLevel, int iMethod, int iMemLevel, int iStrategy, DWORD dwBuffSize)
{
return new CHPZLibCompressor(fnCallback, iWindowBits, iLevel, iMethod, iMemLevel, iStrategy, dwBuffSize);
}
IHPCompressor* CreateGZipCompressor(Fn_CompressDataCallback fnCallback, int iLevel, int iMethod, int iMemLevel, int iStrategy, DWORD dwBuffSize)
{
return new CHPZLibCompressor(fnCallback, MAX_WBITS + 16, iLevel, iMethod, iMemLevel, iStrategy, dwBuffSize);
}
IHPDecompressor* CreateZLibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits, DWORD dwBuffSize)
{
return new CHPZLibDecompressor(fnCallback, iWindowBits, dwBuffSize);
}
IHPDecompressor* CreateGZipDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize)
{
return new CHPZLibDecompressor(fnCallback, MAX_WBITS + 32, dwBuffSize);
}
int Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
}
int CompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iLevel, int iMethod, int iWindowBits, int iMemLevel, int iStrategy)
{
z_stream stream;
stream.next_in = (z_const Bytef*)lpszSrc;
stream.avail_in = dwSrcLen;
stream.next_out = lpszDest;
stream.avail_out = dwDestLen;
stream.zalloc = nullptr;
stream.zfree = nullptr;
stream.opaque = nullptr;
int err = ::deflateInit2(&stream, iLevel, iMethod, iWindowBits, iMemLevel, iStrategy);
if(err != Z_OK) return err;
err = ::deflate(&stream, Z_FINISH);
if(err != Z_STREAM_END)
{
::deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
if(dwDestLen > stream.total_out)
{
lpszDest[stream.total_out] = 0;
dwDestLen = (DWORD)stream.total_out;
}
return ::deflateEnd(&stream);
}
int Uncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
}
int UncompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iWindowBits)
{
z_stream stream;
stream.next_in = (z_const Bytef*)lpszSrc;
stream.avail_in = (uInt)dwSrcLen;
stream.next_out = lpszDest;
stream.avail_out = dwDestLen;
stream.zalloc = nullptr;
stream.zfree = nullptr;
int err = ::inflateInit2(&stream, iWindowBits);
if(err != Z_OK) return err;
err = ::inflate(&stream, Z_FINISH);
if(err != Z_STREAM_END)
{
::inflateEnd(&stream);
return (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) ? Z_DATA_ERROR : err;
}
if(dwDestLen > stream.total_out)
{
lpszDest[stream.total_out] = 0;
dwDestLen = (DWORD)stream.total_out;
}
return inflateEnd(&stream);
}
DWORD GuessCompressBound(DWORD dwSrcLen, BOOL bGZip)
{
DWORD dwBound = (DWORD)::compressBound(dwSrcLen);
if(bGZip) dwBound += 16;
return dwBound;
}
int GZipCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16);
}
int GZipUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, MAX_WBITS + 32);
}
DWORD GZipGuessUncompressBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
if(dwSrcLen < 20 || *(USHORT*)lpszSrc != 0x8B1F)
return 0;
return *(DWORD*)(lpszSrc + dwSrcLen - 4);
}
#endif
#ifdef _BROTLI_SUPPORT
CHPBrotliCompressor::CHPBrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality, int iWindow, int iMode, DWORD dwBuffSize)
: m_fnCallback (fnCallback)
, m_iQuality (iQuality)
, m_iWindow (iWindow)
, m_iMode (iMode)
, m_dwBuffSize (dwBuffSize)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
Reset();
}
CHPBrotliCompressor::~CHPBrotliCompressor()
{
if(m_bValid) ::BrotliEncoderDestroyInstance(m_pState);
}
BOOL CHPBrotliCompressor::Reset()
{
if(m_bValid) ::BrotliEncoderDestroyInstance(m_pState);
m_pState = ::BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
if(m_pState != nullptr)
{
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_QUALITY , (UINT)m_iQuality);
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_LGWIN , (UINT)m_iWindow);
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_MODE , (UINT)m_iMode);
if (m_iWindow > BROTLI_MAX_WINDOW_BITS)
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_LARGE_WINDOW, BROTLI_TRUE);
}
return (m_bValid = (m_pState != nullptr));
}
BOOL CHPBrotliCompressor::Process(const BYTE* pData, int iLength, BOOL bLast, PVOID pContext)
{
return ProcessEx(pData, iLength, bLast, FALSE, pContext);
}
BOOL CHPBrotliCompressor::ProcessEx(const BYTE* pData, int iLength, BOOL bLast, BOOL bFlush, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
unique_ptr<BYTE[]> szBuff = make_unique<BYTE[]>(m_dwBuffSize);
const BYTE* pNextInData = pData;
size_t iAvlInLen = (SIZE_T)iLength;
BYTE* pNextOutData = nullptr;
size_t iAvlOutLen = 0;
BOOL isOK = TRUE;
BrotliEncoderOperation op = bLast ? BROTLI_OPERATION_FINISH : (bFlush ? BROTLI_OPERATION_FLUSH : BROTLI_OPERATION_PROCESS);
while(iAvlInLen > 0)
{
do
{
pNextOutData = szBuff.get();
iAvlOutLen = m_dwBuffSize;
if(!::BrotliEncoderCompressStream(m_pState, op, &iAvlInLen, &pNextInData, &iAvlOutLen, &pNextOutData, nullptr))
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto BROTLI_COMPRESS_END;
}
int iRead = (int)(m_dwBuffSize - iAvlOutLen);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff.get(), iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto BROTLI_COMPRESS_END;
}
} while (iAvlOutLen == 0);
}
BROTLI_COMPRESS_END:
if(!isOK || bLast) Reset();
return isOK;
}
CHPBrotliDecompressor::CHPBrotliDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize)
: m_fnCallback (fnCallback)
, m_dwBuffSize (dwBuffSize)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
Reset();
}
CHPBrotliDecompressor::~CHPBrotliDecompressor()
{
if(m_bValid) ::BrotliDecoderDestroyInstance(m_pState);
}
BOOL CHPBrotliDecompressor::Reset()
{
if(m_bValid) ::BrotliDecoderDestroyInstance(m_pState);
m_pState = ::BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
return (m_bValid = (m_pState != nullptr));
}
BOOL CHPBrotliDecompressor::Process(const BYTE* pData, int iLength, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
unique_ptr<BYTE[]> szBuff = make_unique<BYTE[]>(m_dwBuffSize);
const BYTE* pNextInData = pData;
size_t iAvlInLen = (SIZE_T)iLength;
BYTE* pNextOutData = nullptr;
size_t iAvlOutLen = 0;
BOOL isOK = TRUE;
BrotliDecoderResult rs = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
do
{
do
{
pNextOutData = szBuff.get();
iAvlOutLen = m_dwBuffSize;
rs = ::BrotliDecoderDecompressStream(m_pState, &iAvlInLen, &pNextInData, &iAvlOutLen, &pNextOutData, nullptr);
if(rs == BROTLI_DECODER_RESULT_ERROR)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto BROTLI_DECOMPRESS_END;
}
int iRead = (int)(m_dwBuffSize - iAvlOutLen);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff.get(), iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto BROTLI_DECOMPRESS_END;
}
} while (iAvlOutLen == 0);
if(rs == BROTLI_DECODER_RESULT_SUCCESS)
break;
} while(rs == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT);
BROTLI_DECOMPRESS_END:
if(!isOK || rs == BROTLI_DECODER_RESULT_SUCCESS) Reset();
return isOK;
}
IHPCompressor* CreateBrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality, int iWindow, int iMode, DWORD dwBuffSize)
{
return new CHPBrotliCompressor(fnCallback, iQuality, iWindow, iMode, dwBuffSize);
}
IHPDecompressor* CreateBrotliDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize)
{
return new CHPBrotliDecompressor(fnCallback, dwBuffSize);
}
int BrotliCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return BrotliCompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE);
}
int BrotliCompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iQuality, int iWindow, int iMode)
{
size_t stDestLen = (size_t)dwDestLen;
int rs = ::BrotliEncoderCompress(iQuality, iWindow, (BrotliEncoderMode)iMode, (size_t)dwSrcLen, lpszSrc, &stDestLen, lpszDest);
dwDestLen = (DWORD)stDestLen;
return (rs == 1) ? 0 : ((rs == 3) ? -5 : -3);
}
int BrotliUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
size_t stDestLen = (size_t)dwDestLen;
BrotliDecoderResult rs = ::BrotliDecoderDecompress((size_t)dwSrcLen, lpszSrc, &stDestLen, lpszDest);
dwDestLen = (DWORD)stDestLen;
return (rs == BROTLI_DECODER_RESULT_SUCCESS) ? 0 : ((rs == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) ? -5 : -3);
}
DWORD BrotliGuessCompressBound(DWORD dwSrcLen)
{
return (DWORD)::BrotliEncoderMaxCompressedSize((size_t)dwSrcLen);
}
#endif
#ifdef _ICONV_SUPPORT
BOOL CharsetConvert(LPCSTR lpszFromCharset, LPCSTR lpszToCharset, LPCSTR lpszInBuf, int iInBufLen, LPSTR lpszOutBuf, int& iOutBufLen)
{
ASSERT(lpszInBuf != nullptr);
SIZE_T nInBufLeft = iInBufLen;
SIZE_T nOutBufLeft = iOutBufLen;
int iOutBufSize = iOutBufLen;
iOutBufLen = 0;
if(lpszInBuf == nullptr)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
iconv_t ic = iconv_open(lpszToCharset, lpszFromCharset);
if(IS_INVALID_PVOID(ic))
return FALSE;
SIZE_T rs = iconv(ic, (LPSTR*)&lpszInBuf, &nInBufLeft, &lpszOutBuf, &nOutBufLeft);
iOutBufLen = iOutBufSize - (int)nOutBufLeft;
EXECUTE_RESTORE_ERROR(iconv_close(ic));
return !IS_HAS_ERROR(rs);
}
BOOL GbkToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength)
{
int iInBufLen = (int)((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? strlen(szSrc) + 1 : 0));
int iOutBufLen = (int)(iDestLength * sizeof(WCHAR));
BOOL isOK = CharsetConvert(CHARSET_GBK, SYSTEM_CHARSET_UNICODE, szSrc, iInBufLen, (char*)szDest, iOutBufLen);
iDestLength = (int)(iOutBufLen / sizeof(WCHAR));
return isOK;
}
BOOL UnicodeToGbkEx(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength)
{
int iInBufLen = (int)(((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? wcslen(szSrc) + 1 : 0)) * sizeof(WCHAR));
return CharsetConvert(SYSTEM_CHARSET_UNICODE, CHARSET_GBK, (LPCSTR)szSrc, iInBufLen, szDest, iDestLength);
}
BOOL Utf8ToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength)
{
int iInBufLen = (int)((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? strlen(szSrc) + 1 : 0));
int iOutBufLen = (int)(iDestLength * sizeof(WCHAR));
BOOL isOK = CharsetConvert(CHARSET_UTF_8, SYSTEM_CHARSET_UNICODE, szSrc, iInBufLen, (char*)szDest, iOutBufLen);
iDestLength = (int)(iOutBufLen / sizeof(WCHAR));
return isOK;
}
BOOL UnicodeToUtf8Ex(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength)
{
int iInBufLen = (int)(((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? wcslen(szSrc) + 1 : 0)) * sizeof(WCHAR));
return CharsetConvert(SYSTEM_CHARSET_UNICODE, CHARSET_UTF_8, (LPCSTR)szSrc, iInBufLen, szDest, iDestLength);
}
BOOL GbkToUtf8Ex(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength)
{
int iInBufLen = (int)((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? strlen(szSrc) + 1 : 0));
return CharsetConvert(CHARSET_GBK, CHARSET_UTF_8, szSrc, iInBufLen, szDest, iDestLength);
}
BOOL Utf8ToGbkEx(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength)
{
int iInBufLen = (int)((iSrcLength > 0) ? iSrcLength : ((szSrc != nullptr) ? strlen(szSrc) + 1 : 0));
return CharsetConvert(CHARSET_UTF_8, CHARSET_GBK, szSrc, iInBufLen, szDest, iDestLength);
}
BOOL GbkToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
{
return GbkToUnicodeEx(szSrc, -1, szDest, iDestLength);
}
BOOL UnicodeToGbk(const WCHAR szSrc[], char szDest[], int& iDestLength)
{
return UnicodeToGbkEx(szSrc, -1, szDest, iDestLength);
}
BOOL Utf8ToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
{
return Utf8ToUnicodeEx(szSrc, -1, szDest, iDestLength);
}
BOOL UnicodeToUtf8(const WCHAR szSrc[], char szDest[], int& iDestLength)
{
return UnicodeToUtf8Ex(szSrc, -1, szDest, iDestLength);
}
BOOL GbkToUtf8(const char szSrc[], char szDest[], int& iDestLength)
{
return GbkToUtf8Ex(szSrc, -1, szDest, iDestLength);
}
BOOL Utf8ToGbk(const char szSrc[], char szDest[], int& iDestLength)
{
return Utf8ToGbkEx(szSrc, -1, szDest, iDestLength);
}
#endif
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

HP-Socket 是一套通用的高性能 TCP/UDP/HTTP 通信框架,包含服务端组件、客户端组件和Agent组件,广泛适用于各种不同应用场景的 TCP/UDP/HTTP 通信系统,提供 C/C++、C#、Delphi、E(易语言)、Java、Python 等编程语言接口。HP-Socket 对通信层实现完全封装,应用程序不必关注通信层的任何细节;HP-Socket 提供基于事件通知模型的 API 接口,能非常简单高效地整合到新旧应用程序中。
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/githubdby/HP-Socket.git
git@gitee.com:githubdby/HP-Socket.git
githubdby
HP-Socket
HP-Socket
dev
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /