aboutsummaryrefslogtreecommitdiff
path: root/dep/src
diff options
context:
space:
mode:
authorParadox <none@none>2009-02-09 08:16:34 -0500
committerParadox <none@none>2009-02-09 08:16:34 -0500
commitd230302b16474ff22a35243ffed6236ef4fc7fb9 (patch)
treee3679ad841a47b275756f2721f9aa24a3ee548a6 /dep/src
parentb0694d7e5e794b361fa178d55fefdb98cf47e9ca (diff)
Replace tabs with spaces in more files.
--HG-- branch : trunk
Diffstat (limited to 'dep/src')
-rw-r--r--dep/src/g3dlite/AABox.cpp136
-rw-r--r--dep/src/g3dlite/Crypto.cpp194
-rw-r--r--dep/src/g3dlite/Matrix3.cpp24
-rw-r--r--dep/src/g3dlite/Plane.cpp10
-rw-r--r--dep/src/g3dlite/System.cpp48
-rw-r--r--dep/src/g3dlite/Triangle.cpp10
-rw-r--r--dep/src/g3dlite/Vector3.cpp26
-rw-r--r--dep/src/g3dlite/Vector4.cpp10
-rw-r--r--dep/src/g3dlite/format.cpp10
-rw-r--r--dep/src/sockets/Base64.cpp378
-rw-r--r--dep/src/sockets/Exception.cpp8
-rw-r--r--dep/src/sockets/Ipv4Address.cpp154
-rw-r--r--dep/src/sockets/Ipv6Address.cpp226
-rw-r--r--dep/src/sockets/Lock.cpp10
-rw-r--r--dep/src/sockets/Mutex.cpp24
-rw-r--r--dep/src/sockets/Parse.cpp316
-rw-r--r--dep/src/sockets/ResolvServer.cpp42
-rw-r--r--dep/src/sockets/ResolvSocket.cpp528
-rw-r--r--dep/src/sockets/Socket.cpp1464
-rw-r--r--dep/src/sockets/SocketHandler.cpp2028
-rw-r--r--dep/src/sockets/StdoutLog.cpp86
-rw-r--r--dep/src/sockets/StreamSocket.cpp70
-rw-r--r--dep/src/sockets/TcpSocket.cpp2314
-rw-r--r--dep/src/sockets/Thread.cpp98
-rw-r--r--dep/src/sockets/UdpSocket.cpp980
-rw-r--r--dep/src/sockets/Utility.cpp1336
-rw-r--r--dep/src/sockets/socket_include.cpp110
-rw-r--r--dep/src/zthread/ConditionImpl.h116
-rw-r--r--dep/src/zthread/Debug.h2
-rw-r--r--dep/src/zthread/DeferredInterruptionScope.h8
-rw-r--r--dep/src/zthread/FastRecursiveLock.h6
-rw-r--r--dep/src/zthread/IntrusivePtr.h14
-rw-r--r--dep/src/zthread/Monitor.h2
-rw-r--r--dep/src/zthread/MutexImpl.h148
-rw-r--r--dep/src/zthread/RecursiveMutexImpl.h26
-rw-r--r--dep/src/zthread/Scheduling.h10
-rw-r--r--dep/src/zthread/SemaphoreImpl.h122
-rw-r--r--dep/src/zthread/State.h4
-rw-r--r--dep/src/zthread/Status.h56
-rw-r--r--dep/src/zthread/ThreadImpl.h20
-rw-r--r--dep/src/zthread/ThreadOps.h6
-rw-r--r--dep/src/zthread/ThreadQueue.h26
-rw-r--r--dep/src/zthread/TimeStrategy.h2
-rw-r--r--dep/src/zthread/config.h10
-rw-r--r--dep/src/zthread/linux/AtomicFastLock.h26
-rw-r--r--dep/src/zthread/linux/FastRecursiveLock.h26
-rw-r--r--dep/src/zthread/macos/FastLock.h40
-rw-r--r--dep/src/zthread/macos/Monitor.h28
-rw-r--r--dep/src/zthread/macos/TSS.h26
-rw-r--r--dep/src/zthread/macos/ThreadOps.h22
-rw-r--r--dep/src/zthread/macos/UpTimeStrategy.h6
-rw-r--r--dep/src/zthread/posix/ConditionRecursiveLock.h36
-rw-r--r--dep/src/zthread/posix/FastLock.h26
-rw-r--r--dep/src/zthread/posix/FtimeStrategy.h4
-rw-r--r--dep/src/zthread/posix/Monitor.h18
-rw-r--r--dep/src/zthread/posix/PriorityOps.h6
-rw-r--r--dep/src/zthread/posix/TSS.h24
-rw-r--r--dep/src/zthread/posix/ThreadOps.h24
-rw-r--r--dep/src/zthread/solaris/FastRecursiveLock.h34
-rw-r--r--dep/src/zthread/vanilla/DualMutexRecursiveLock.h62
-rw-r--r--dep/src/zthread/vanilla/SimpleRecursiveLock.h42
-rw-r--r--dep/src/zthread/win32/AtomicFastLock.h30
-rw-r--r--dep/src/zthread/win32/AtomicFastRecursiveLock.h50
-rw-r--r--dep/src/zthread/win32/FastLock.h16
-rw-r--r--dep/src/zthread/win32/FastRecursiveLock.h12
-rw-r--r--dep/src/zthread/win32/Monitor.h24
-rw-r--r--dep/src/zthread/win32/PerformanceCounterStrategy.h18
-rw-r--r--dep/src/zthread/win32/TSS.h18
-rw-r--r--dep/src/zthread/win32/ThreadOps.h20
-rw-r--r--dep/src/zthread/win9x/AtomicFastLock.h22
70 files changed, 5939 insertions, 5939 deletions
diff --git a/dep/src/g3dlite/AABox.cpp b/dep/src/g3dlite/AABox.cpp
index d147a1080e8..0baa1a07419 100644
--- a/dep/src/g3dlite/AABox.cpp
+++ b/dep/src/g3dlite/AABox.cpp
@@ -59,22 +59,22 @@ Vector3 AABox::randomSurfacePoint() const {
// The probability of choosing a given face is proportional to
// its area.
if (r < aXY) {
- return
- lo +
+ return
+ lo +
Vector3(
(float)random(0, extent.x),
(float)random(0, extent.y),
d * extent.z);
} else if (r < aYZ) {
- return
- lo +
+ return
+ lo +
Vector3(
d * extent.x,
(float)random(0, extent.y),
(float)random(0, extent.z));
} else {
- return
- lo +
+ return
+ lo +
Vector3(
(float)random(0, extent.x),
d * extent.y,
@@ -85,8 +85,8 @@ Vector3 AABox::randomSurfacePoint() const {
Vector3 AABox::randomInteriorPoint() const {
return Vector3(
- (float)random(lo.x, hi.x),
- (float)random(lo.y, hi.y),
+ (float)random(lo.x, hi.x),
+ (float)random(lo.y, hi.y),
(float)random(lo.z, hi.z));
}
#endif
@@ -112,21 +112,21 @@ bool AABox::intersects(const AABox& other) const {
bool AABox::culledBy(
- const Array<Plane>& plane,
- int& cullingPlaneIndex,
- const uint32 inMask,
- uint32& outMask) const {
+ const Array<Plane>& plane,
+ int& cullingPlaneIndex,
+ const uint32 inMask,
+ uint32& outMask) const {
- return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask, outMask);
+ return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask, outMask);
}
bool AABox::culledBy(
- const Array<Plane>& plane,
- int& cullingPlaneIndex,
- const uint32 inMask) const {
+ const Array<Plane>& plane,
+ int& cullingPlaneIndex,
+ const uint32 inMask) const {
- return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask);
+ return culledBy(plane.getCArray(), plane.size(), cullingPlaneIndex, inMask);
}
@@ -136,16 +136,16 @@ int AABox::dummy = 0;
bool AABox::culledBy(
const class Plane* plane,
int numPlanes,
- int& cullingPlane,
- const uint32 _inMask,
+ int& cullingPlane,
+ const uint32 _inMask,
uint32& childMask) const {
- uint32 inMask = _inMask;
- assert(numPlanes < 31);
+ uint32 inMask = _inMask;
+ assert(numPlanes < 31);
childMask = 0;
- const bool finite =
+ const bool finite =
(abs(lo.x) < G3D::inf()) &&
(abs(hi.x) < G3D::inf()) &&
(abs(lo.y) < G3D::inf()) &&
@@ -154,13 +154,13 @@ bool AABox::culledBy(
(abs(hi.z) < G3D::inf());
// See if there is one plane for which all of the
- // vertices are in the negative half space.
+ // vertices are in the negative half space.
for (int p = 0; p < numPlanes; p++) {
- // Only test planes that are not masked
- if ((inMask & 1) != 0) {
-
- Vector3 corner;
+ // Only test planes that are not masked
+ if ((inMask & 1) != 0) {
+
+ Vector3 corner;
int numContained = 0;
int v = 0;
@@ -168,13 +168,13 @@ bool AABox::culledBy(
// We can early-out only if we have found one point on each
// side of the plane (i.e. if we are straddling). That
// occurs when (numContained < v) && (numContained > 0)
- for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) {
+ for (v = 0; (v < 8) && ((numContained == v) || (numContained == 0)); ++v) {
// Unrolling these 3 if's into a switch decreases performance
// by about 2x
- corner.x = (v & 1) ? hi.x : lo.x;
- corner.y = (v & 2) ? hi.y : lo.y;
- corner.z = (v & 4) ? hi.z : lo.z;
-
+ corner.x = (v & 1) ? hi.x : lo.x;
+ corner.y = (v & 2) ? hi.y : lo.y;
+ corner.z = (v & 4) ? hi.z : lo.z;
+
if (finite) { // this branch is highly predictable
if (plane[p].halfSpaceContainsFinite(corner)) {
++numContained;
@@ -184,32 +184,32 @@ bool AABox::culledBy(
++numContained;
}
}
- }
+ }
- if (numContained == 0) {
- // Plane p culled the box
- cullingPlane = p;
+ if (numContained == 0) {
+ // Plane p culled the box
+ cullingPlane = p;
// The caller should not recurse into the children,
// since the parent is culled. If they do recurse,
// make them only test against this one plane, which
// will immediately cull the volume.
childMask = 1 << p;
- return true;
+ return true;
} else if (numContained < v) {
// The bounding volume straddled the plane; we have
// to keep testing against this plane
childMask |= (1 << p);
}
- }
+ }
// Move on to the next bit.
- inMask = inMask >> 1;
+ inMask = inMask >> 1;
}
// None of the planes could cull this box
- cullingPlane = -1;
+ cullingPlane = -1;
return false;
}
@@ -217,13 +217,13 @@ bool AABox::culledBy(
bool AABox::culledBy(
const class Plane* plane,
int numPlanes,
- int& cullingPlane,
- const uint32 _inMask) const {
+ int& cullingPlane,
+ const uint32 _inMask) const {
+
+ uint32 inMask = _inMask;
+ assert(numPlanes < 31);
- uint32 inMask = _inMask;
- assert(numPlanes < 31);
-
- const bool finite =
+ const bool finite =
(abs(lo.x) < G3D::inf()) &&
(abs(hi.x) < G3D::inf()) &&
(abs(lo.y) < G3D::inf()) &&
@@ -232,55 +232,55 @@ bool AABox::culledBy(
(abs(hi.z) < G3D::inf());
// See if there is one plane for which all of the
- // vertices are in the negative half space.
+ // vertices are in the negative half space.
for (int p = 0; p < numPlanes; p++) {
- // Only test planes that are not masked
- if ((inMask & 1) != 0) {
-
- bool culled = true;
- Vector3 corner;
+ // Only test planes that are not masked
+ if ((inMask & 1) != 0) {
+
+ bool culled = true;
+ Vector3 corner;
int v;
- // Assume this plane culls all points. See if there is a point
- // not culled by the plane... early out when at least one point
+ // Assume this plane culls all points. See if there is a point
+ // not culled by the plane... early out when at least one point
// is in the positive half space.
- for (v = 0; (v < 8) && culled; ++v) {
+ for (v = 0; (v < 8) && culled; ++v) {
// Unrolling these 3 if's into a switch decreases performance
// by about 2x
- corner.x = (v & 1) ? hi.x : lo.x;
- corner.y = (v & 2) ? hi.y : lo.y;
- corner.z = (v & 4) ? hi.z : lo.z;
-
+ corner.x = (v & 1) ? hi.x : lo.x;
+ corner.y = (v & 2) ? hi.y : lo.y;
+ corner.z = (v & 4) ? hi.z : lo.z;
+
if (finite) { // this branch is highly predictable
culled = ! plane[p].halfSpaceContainsFinite(corner);
} else {
culled = ! plane[p].halfSpaceContains(corner);
}
- }
+ }
- if (culled) {
- // Plane p culled the box
- cullingPlane = p;
+ if (culled) {
+ // Plane p culled the box
+ cullingPlane = p;
- return true;
+ return true;
}
- }
+ }
// Move on to the next bit.
- inMask = inMask >> 1;
+ inMask = inMask >> 1;
}
// None of the planes could cull this box
- cullingPlane = -1;
+ cullingPlane = -1;
return false;
}
bool AABox::intersects(const class Sphere& sphere) const {
- double d = 0;
+ double d = 0;
//find the square of the distance
//from the sphere to the box
diff --git a/dep/src/g3dlite/Crypto.cpp b/dep/src/g3dlite/Crypto.cpp
index c07e5da3c70..763c2fefd4b 100644
--- a/dep/src/g3dlite/Crypto.cpp
+++ b/dep/src/g3dlite/Crypto.cpp
@@ -13,7 +13,7 @@
#include "G3D/g3dmath.h"
namespace G3D {
-
+
int Crypto::smallPrime(int n) {
debugAssert(n < numSmallPrimes() && n >= 0);
@@ -22,36 +22,36 @@ int Crypto::smallPrime(int n) {
// http://primes.utm.edu/lists/small/1000.txt
static const int table[] = {
- 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
- 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
- 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
- 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
- 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
- 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
- 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
- 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
- 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
- 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
- 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
- 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
- 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
- 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
- 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
- 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
- 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
- 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
- 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
- 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
- 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
- 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
- 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
- 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
- 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
- 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
- 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
+ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
+ 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
+ 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
+ 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
+ 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
+ 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
+ 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
+ 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
+ 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
+ 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
+ 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
+ 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
+ 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
+ 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
+ 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
+ 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
+ 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
+ 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
+ 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
+ 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
+ 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
+ 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
+ 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
+ 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
+ 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
+ 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
+ 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
- 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
- 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
+ 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
+ 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999};
return table[n];
@@ -64,73 +64,73 @@ int Crypto::numSmallPrimes() {
uint32 Crypto::crc32(const void* byte, size_t numBytes) {
static const uint32 crc32Table[256] = {
- 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
- 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
- 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
- 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
- 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
- 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
- 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
- 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
- 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
- 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
- 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
- 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
- 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
- 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
- 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
- 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
-
- 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
- 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
- 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
- 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
- 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
- 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
- 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
- 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
- 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
- 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
- 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
- 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
- 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
- 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
- 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
- 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
-
- 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
- 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
- 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
- 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
- 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
- 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
- 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
- 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
- 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
- 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
- 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
- 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
- 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
- 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
- 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
- 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
-
- 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
- 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
- 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
- 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
- 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
- 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
- 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
- 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
- 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
- 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
- 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
- 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
- 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
- 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
- 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
- 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
+ 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+ 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
+ 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+ 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+ 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
+ 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
+ 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+ 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
+ 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
+ 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+ 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+ 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
+ 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+ 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
+ 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
+ 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+ 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
+ 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
+ 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+ 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
+ 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
+ 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+ 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
+ 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
+ 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+ 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
+ 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+ 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+ 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
+ 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
+ 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+ 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
};
// By definition, initialize to all binary 1's
diff --git a/dep/src/g3dlite/Matrix3.cpp b/dep/src/g3dlite/Matrix3.cpp
index 1d6df3ff7d7..c6fc9729b34 100644
--- a/dep/src/g3dlite/Matrix3.cpp
+++ b/dep/src/g3dlite/Matrix3.cpp
@@ -55,7 +55,7 @@ bool Matrix3::isOrthonormal() const {
Vector3 Y = getColumn(1);
Vector3 Z = getColumn(2);
- return
+ return
(G3D::fuzzyEq(X.dot(Y), 0.0f) &&
G3D::fuzzyEq(Y.dot(Z), 0.0f) &&
G3D::fuzzyEq(X.dot(Z), 0.0f) &&
@@ -67,7 +67,7 @@ bool Matrix3::isOrthonormal() const {
//----------------------------------------------------------------------------
Matrix3::Matrix3(const Quat& _q) {
// Implementation from Watt and Watt, pg 362
- // See also http://www.flipcode.com/documents/matrfaq.html#Q54
+ // See also http://www.flipcode.com/documents/matrfaq.html#Q54
Quat q = _q.unitize();
float xx = 2.0f * q.x * q.x;
float xy = 2.0f * q.x * q.y;
@@ -109,7 +109,7 @@ Matrix3::Matrix3(
void Matrix3::set(
float fEntry00, float fEntry01, float fEntry02,
- float fEntry10, float fEntry11, float fEntry12,
+ float fEntry10, float fEntry11, float fEntry12,
float fEntry20, float fEntry21, float fEntry22) {
elt[0][0] = fEntry00;
@@ -1340,10 +1340,10 @@ Matrix3 Matrix3::fromEulerAnglesXZY (float fYAngle, float fPAngle,
//----------------------------------------------------------------------------
Matrix3 Matrix3::fromEulerAnglesYXZ(
- float fYAngle,
+ float fYAngle,
float fPAngle,
float fRAngle) {
-
+
float fCos, fSin;
fCos = cos(fYAngle);
@@ -1363,7 +1363,7 @@ Matrix3 Matrix3::fromEulerAnglesYXZ(
//----------------------------------------------------------------------------
Matrix3 Matrix3::fromEulerAnglesYZX(
- float fYAngle,
+ float fYAngle,
float fPAngle,
float fRAngle) {
@@ -1605,9 +1605,9 @@ void Matrix3::tensorProduct (const Vector3& rkU, const Vector3& rkV,
// Runs in 52 cycles on AMD, 76 cycles on Intel Centrino
//
-// The loop unrolling is necessary for performance.
+// The loop unrolling is necessary for performance.
// I was unable to improve performance further by flattening the matrices
-// into float*'s instead of 2D arrays.
+// into float*'s instead of 2D arrays.
//
// -morgan
void Matrix3::_mul(const Matrix3& A, const Matrix3& B, Matrix3& out) {
@@ -1674,10 +1674,10 @@ void Matrix3::_transpose(const Matrix3& A, Matrix3& out) {
//-----------------------------------------------------------------------------
std::string Matrix3::toString() const {
- return G3D::format("[%g, %g, %g; %g, %g, %g; %g, %g, %g]",
- elt[0][0], elt[0][1], elt[0][2],
- elt[1][0], elt[1][1], elt[1][2],
- elt[2][0], elt[2][1], elt[2][2]);
+ return G3D::format("[%g, %g, %g; %g, %g, %g; %g, %g, %g]",
+ elt[0][0], elt[0][1], elt[0][2],
+ elt[1][0], elt[1][1], elt[1][2],
+ elt[2][0], elt[2][1], elt[2][2]);
}
diff --git a/dep/src/g3dlite/Plane.cpp b/dep/src/g3dlite/Plane.cpp
index c958a10a710..5265ef8f670 100644
--- a/dep/src/g3dlite/Plane.cpp
+++ b/dep/src/g3dlite/Plane.cpp
@@ -1,8 +1,8 @@
/**
@file Plane.cpp
-
+
@maintainer Morgan McGuire, matrix@graphics3d.com
-
+
@created 2003-02-06
@edited 2006-01-29
*/
@@ -20,14 +20,14 @@ Plane::Plane(
Vector4 point2) {
debugAssertM(
- point0.w != 0 ||
- point1.w != 0 ||
+ point0.w != 0 ||
+ point1.w != 0 ||
point2.w != 0,
"At least one point must be finite.");
// Rotate the points around so that the finite points come first.
- while ((point0.w == 0) &&
+ while ((point0.w == 0) &&
((point1.w == 0) || (point2.w != 0))) {
Vector4 temp = point0;
point0 = point1;
diff --git a/dep/src/g3dlite/System.cpp b/dep/src/g3dlite/System.cpp
index 06be7cd25e0..f28c9d62a9a 100644
--- a/dep/src/g3dlite/System.cpp
+++ b/dep/src/g3dlite/System.cpp
@@ -1,6 +1,6 @@
-/**
+/**
@file System.cpp
-
+
@maintainer Morgan McGuire, matrix@graphics3d.com
Note: every routine must call init() first.
@@ -29,7 +29,7 @@
#include <sys/timeb.h>
#include "G3D/RegistryUtil.h"
-#elif defined(G3D_LINUX)
+#elif defined(G3D_LINUX)
#include <stdlib.h>
#include <stdio.h>
@@ -125,7 +125,7 @@ public:
*/
enum {tinyBufferSize = 128, smallBufferSize = 1024, medBufferSize = 4096};
- /**
+ /**
Most buffers we're allowed to store.
64000 * 128 = 8 MB (preallocated)
1024 * 1024 = 1 MB (allocated on demand)
@@ -183,7 +183,7 @@ private:
# endif
}
- /**
+ /**
Malloc out of the tiny heap.
*/
inline void* tinyMalloc(size_t bytes) {
@@ -205,7 +205,7 @@ private:
/** Returns true if this is a pointer into the tiny heap. */
bool inTinyHeap(void* ptr) {
- return (ptr >= tinyHeap) &&
+ return (ptr >= tinyHeap) &&
(ptr < (uint8*)tinyHeap + maxTinyBuffers * tinyBufferSize);
}
@@ -228,9 +228,9 @@ private:
}
- /** Allocate out of a specific pool-> Return NULL if no suitable
- memory was found.
-
+ /** Allocate out of a specific pool-> Return NULL if no suitable
+ memory was found.
+
*/
void* malloc(MemBlock* pool, int& poolSize, size_t bytes) {
@@ -264,7 +264,7 @@ public:
int mallocsFromSmallPool;
int mallocsFromMedPool;
- /** Amount of memory currently allocated (according to the application).
+ /** Amount of memory currently allocated (according to the application).
This does not count the memory still remaining in the buffer pool,
but does count extra memory required for rounding off to the size
of a buffer.
@@ -314,7 +314,7 @@ public:
# endif
}
-
+
void* realloc(void* ptr, size_t bytes) {
if (ptr == NULL) {
return malloc(bytes);
@@ -326,7 +326,7 @@ public:
return ptr;
} else {
// Free the old pointer and malloc
-
+
void* newPtr = malloc(bytes);
System::memcpy(newPtr, ptr, tinyBufferSize);
tinyFree(ptr);
@@ -366,12 +366,12 @@ public:
return ptr;
}
- }
-
+ }
+
// Failure to allocate a tiny buffer is allowed to flow
// through to a small buffer
if (bytes <= smallBufferSize) {
-
+
void* ptr = malloc(smallPool, smallPoolSize, bytes);
if (ptr) {
@@ -476,7 +476,7 @@ public:
std::string performance() const {
if (totalMallocs > 0) {
int pooled = mallocsFromTinyPool +
- mallocsFromSmallPool +
+ mallocsFromSmallPool +
mallocsFromMedPool;
int total = totalMallocs;
@@ -503,23 +503,23 @@ public:
};
// Dynamically allocated because we need to ensure that
-// the buffer pool is still around when the last global variable
+// the buffer pool is still around when the last global variable
// is deallocated.
static BufferPool* bufferpool = NULL;
-std::string System::mallocPerformance() {
+std::string System::mallocPerformance() {
#ifndef NO_BUFFERPOOL
return bufferpool->performance();
#else
- return "NO_BUFFERPOOL";
+ return "NO_BUFFERPOOL";
#endif
}
-std::string System::mallocStatus() {
+std::string System::mallocStatus() {
#ifndef NO_BUFFERPOOL
return bufferpool->status();
#else
- return "NO_BUFFERPOOL";
+ return "NO_BUFFERPOOL";
#endif
}
@@ -572,7 +572,7 @@ void* System::realloc(void* block, size_t bytes) {
initMem();
return bufferpool->realloc(block, bytes);
#else
- return ::realloc(block, bytes);
+ return ::realloc(block, bytes);
#endif
}
@@ -581,7 +581,7 @@ void System::free(void* p) {
#ifndef NO_BUFFERPOOL
bufferpool->free(p);
#else
- return ::free(p);
+ return ::free(p);
#endif
}
@@ -606,7 +606,7 @@ void* System::alignedMalloc(size_t bytes, size_t alignment) {
debugAssert(isValidHeapPointer(truePtr));
#ifdef G3D_WIN32
// The blocks we return will not be valid Win32 debug heap
- // pointers because they are offset
+ // pointers because they are offset
// debugAssert(_CrtIsValidPointer(truePtr, totalBytes, TRUE) );
#endif
diff --git a/dep/src/g3dlite/Triangle.cpp b/dep/src/g3dlite/Triangle.cpp
index adb815e1602..d3fa835c7c8 100644
--- a/dep/src/g3dlite/Triangle.cpp
+++ b/dep/src/g3dlite/Triangle.cpp
@@ -1,8 +1,8 @@
/**
@file Triangle.cpp
-
+
@maintainer Morgan McGuire, graphics3d.com
-
+
@created 2001-04-06
@edited 2006-01-20
@@ -17,7 +17,7 @@
namespace G3D {
-
+
void Triangle::init(const Vector3& v0, const Vector3& v1, const Vector3& v2) {
_plane = Plane(v0, v1, v2);
@@ -50,13 +50,13 @@ void Triangle::init(const Vector3& v0, const Vector3& v1, const Vector3& v2) {
Triangle::Triangle() {
init(Vector3::zero(), Vector3::zero(), Vector3::zero());
}
-
+
Triangle::Triangle(const Vector3& v0, const Vector3& v1, const Vector3& v2) {
init(v0, v1, v2);
}
-
+
Triangle::~Triangle() {
}
diff --git a/dep/src/g3dlite/Vector3.cpp b/dep/src/g3dlite/Vector3.cpp
index 57ee76d1eb1..274769a1e0b 100644
--- a/dep/src/g3dlite/Vector3.cpp
+++ b/dep/src/g3dlite/Vector3.cpp
@@ -1,12 +1,12 @@
/**
@file Vector3.cpp
-
+
3D vector class
-
+
@maintainer Morgan McGuire, matrix@graphics3d.com
-
+
@cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com
-
+
@created 2001-06-02
@edited 2006-01-30
*/
@@ -20,7 +20,7 @@
#include "G3D/Vector3int16.h"
#include "G3D/Matrix3.h"
#include "G3D/Vector2.h"
-
+
namespace G3D {
Vector3 Vector3::dummy;
@@ -38,7 +38,7 @@ Vector3::Vector3(const class Vector2& v, float _z) : x(v.x), y(v.y), z(_z) {
}
Vector3::Axis Vector3::primaryAxis() const {
-
+
Axis a = X_AXIS;
double nx = abs(x);
@@ -94,7 +94,7 @@ Vector3 Vector3::random() {
Vector3 result;
do {
- result = Vector3(uniformRandom(-1.0, 1.0),
+ result = Vector3(uniformRandom(-1.0, 1.0),
uniformRandom(-1.0, 1.0),
uniformRandom(-1.0, 1.0));
} while (result.squaredMagnitude() >= 1.0f);
@@ -109,7 +109,7 @@ Vector3 Vector3::operator/ (float fScalar) const {
Vector3 kQuot;
if ( fScalar != 0.0 ) {
- float fInvScalar = 1.0f / fScalar;
+ float fInvScalar = 1.0f / fScalar;
kQuot.x = fInvScalar * x;
kQuot.y = fInvScalar * y;
kQuot.z = fInvScalar * z;
@@ -122,7 +122,7 @@ Vector3 Vector3::operator/ (float fScalar) const {
//----------------------------------------------------------------------------
Vector3& Vector3::operator/= (float fScalar) {
if (fScalar != 0.0) {
- float fInvScalar = 1.0f / fScalar;
+ float fInvScalar = 1.0f / fScalar;
x *= fInvScalar;
y *= fInvScalar;
z *= fInvScalar;
@@ -137,10 +137,10 @@ Vector3& Vector3::operator/= (float fScalar) {
//----------------------------------------------------------------------------
float Vector3::unitize (float fTolerance) {
- float fMagnitude = magnitude();
+ float fMagnitude = magnitude();
if (fMagnitude > fTolerance) {
- float fInvMagnitude = 1.0f / fMagnitude;
+ float fInvMagnitude = 1.0f / fMagnitude;
x *= fInvMagnitude;
y *= fInvMagnitude;
z *= fInvMagnitude;
@@ -260,12 +260,12 @@ void Vector3::orthonormalize (Vector3 akVector[3]) {
akVector[0].unitize();
// compute u1
- float fDot0 = akVector[0].dot(akVector[1]);
+ float fDot0 = akVector[0].dot(akVector[1]);
akVector[1] -= akVector[0] * fDot0;
akVector[1].unitize();
// compute u2
- float fDot1 = akVector[1].dot(akVector[2]);
+ float fDot1 = akVector[1].dot(akVector[2]);
fDot0 = akVector[0].dot(akVector[2]);
akVector[2] -= akVector[0] * fDot0 + akVector[1] * fDot1;
akVector[2].unitize();
diff --git a/dep/src/g3dlite/Vector4.cpp b/dep/src/g3dlite/Vector4.cpp
index bfea20202c4..2a597df65ed 100644
--- a/dep/src/g3dlite/Vector4.cpp
+++ b/dep/src/g3dlite/Vector4.cpp
@@ -1,8 +1,8 @@
/**
@file Vector4.cpp
-
+
@maintainer Morgan McGuire, matrix@graphics3d.com
-
+
@created 2001-07-09
@edited 2003-09-29
*/
@@ -57,7 +57,7 @@ Vector4 Vector4::operator/ (float fScalar) const {
Vector4 kQuot;
if ( fScalar != 0.0 ) {
- float fInvScalar = 1.0f / fScalar;
+ float fInvScalar = 1.0f / fScalar;
kQuot.x = fInvScalar * x;
kQuot.y = fInvScalar * y;
kQuot.z = fInvScalar * z;
@@ -71,13 +71,13 @@ Vector4 Vector4::operator/ (float fScalar) const {
//----------------------------------------------------------------------------
Vector4& Vector4::operator/= (float fScalar) {
if (fScalar != 0.0f) {
- float fInvScalar = 1.0f / fScalar;
+ float fInvScalar = 1.0f / fScalar;
x *= fInvScalar;
y *= fInvScalar;
z *= fInvScalar;
w *= fInvScalar;
} else {
- *this = Vector4::inf();
+ *this = Vector4::inf();
}
return *this;
diff --git a/dep/src/g3dlite/format.cpp b/dep/src/g3dlite/format.cpp
index 6def987c21b..8737128a0f8 100644
--- a/dep/src/g3dlite/format.cpp
+++ b/dep/src/g3dlite/format.cpp
@@ -52,7 +52,7 @@ std::string vformat(const char *fmt, va_list argPtr) {
// allocate it on the stack because this saves
// the malloc/free time.
const int bufSize = 161;
- char stackBuffer[bufSize];
+ char stackBuffer[bufSize];
int actualSize = _vscprintf(fmt, argPtr) + 1;
@@ -68,7 +68,7 @@ std::string vformat(const char *fmt, va_list argPtr) {
heapBuffer[maxSize] = '\0';
} else {
heapBuffer = (char*)System::malloc(actualSize);
- vsprintf(heapBuffer, fmt, argPtr);
+ vsprintf(heapBuffer, fmt, argPtr);
}
std::string formattedString(heapBuffer);
@@ -91,7 +91,7 @@ std::string vformat(const char *fmt, va_list argPtr) {
// allocate it on the stack because this saves
// the malloc/free time.
const int bufSize = 161;
- char stackBuffer[bufSize];
+ char stackBuffer[bufSize];
int actualWritten = vsnprintf(stackBuffer, bufSize, fmt, argPtr);
@@ -101,7 +101,7 @@ std::string vformat(const char *fmt, va_list argPtr) {
int heapSize = 512;
double powSize = 1.0;
char* heapBuffer = (char*)System::malloc(heapSize);
-
+
while ((vsnprintf(heapBuffer, heapSize, fmt, argPtr) == -1) &&
(heapSize < maxSize)) {
@@ -144,7 +144,7 @@ std::string vformat(const char* fmt, va_list argPtr) {
assert(numChars2 == numChars);
std::string result(heapBuffer);
-
+
System::free(heapBuffer);
return result;
diff --git a/dep/src/sockets/Base64.cpp b/dep/src/sockets/Base64.cpp
index b8cf1237175..95b91555beb 100644
--- a/dep/src/sockets/Base64.cpp
+++ b/dep/src/sockets/Base64.cpp
@@ -1,6 +1,6 @@
/** \file Base64.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -35,20 +35,20 @@ namespace SOCKETS_NAMESPACE {
const char *Base64::bstr =
- "ABCDEFGHIJKLMNOPQ"
- "RSTUVWXYZabcdefgh"
- "ijklmnopqrstuvwxy"
- "z0123456789+/";
+ "ABCDEFGHIJKLMNOPQ"
+ "RSTUVWXYZabcdefgh"
+ "ijklmnopqrstuvwxy"
+ "z0123456789+/";
const char Base64::rstr[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
- 0, 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, 0, 0, 0, 0, 0,
- 0, 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, 0, 0, 0, 0, 0};
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
+ 0, 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, 0, 0, 0, 0, 0,
+ 0, 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, 0, 0, 0, 0, 0};
Base64::Base64()
@@ -58,210 +58,210 @@ Base64::Base64()
void Base64::encode(FILE *fil, std::string& output, bool add_crlf)
{
- size_t remain;
- size_t i = 0;
- size_t o = 0;
- char input[4];
-
- output = "";
- remain = fread(input,1,3,fil);
- while (remain > 0)
- {
- if (add_crlf && o && o % 76 == 0)
- output += "\n";
- switch (remain)
- {
- case 1:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) ];
- output += "==";
- break;
- case 2:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
- output += "=";
- break;
- default:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
- output += bstr[ (input[i + 2] & 0x3f) ];
- }
- o += 4;
- //
- remain = fread(input,1,3,fil);
- }
+ size_t remain;
+ size_t i = 0;
+ size_t o = 0;
+ char input[4];
+
+ output = "";
+ remain = fread(input,1,3,fil);
+ while (remain > 0)
+ {
+ if (add_crlf && o && o % 76 == 0)
+ output += "\n";
+ switch (remain)
+ {
+ case 1:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) ];
+ output += "==";
+ break;
+ case 2:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
+ output += "=";
+ break;
+ default:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
+ output += bstr[ (input[i + 2] & 0x3f) ];
+ }
+ o += 4;
+ //
+ remain = fread(input,1,3,fil);
+ }
}
void Base64::encode(const std::string& str_in, std::string& str_out, bool add_crlf)
{
- encode(str_in.c_str(), str_in.size(), str_out, add_crlf);
+ encode(str_in.c_str(), str_in.size(), str_out, add_crlf);
}
void Base64::encode(const char* input,size_t l,std::string& output, bool add_crlf)
{
- size_t i = 0;
- size_t o = 0;
-
- output = "";
- while (i < l)
- {
- size_t remain = l - i;
- if (add_crlf && o && o % 76 == 0)
- output += "\n";
- switch (remain)
- {
- case 1:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) ];
- output += "==";
- break;
- case 2:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
- output += "=";
- break;
- default:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
- output += bstr[ (input[i + 2] & 0x3f) ];
- }
- o += 4;
- i += 3;
- }
+ size_t i = 0;
+ size_t o = 0;
+
+ output = "";
+ while (i < l)
+ {
+ size_t remain = l - i;
+ if (add_crlf && o && o % 76 == 0)
+ output += "\n";
+ switch (remain)
+ {
+ case 1:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) ];
+ output += "==";
+ break;
+ case 2:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
+ output += "=";
+ break;
+ default:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
+ output += bstr[ (input[i + 2] & 0x3f) ];
+ }
+ o += 4;
+ i += 3;
+ }
}
void Base64::encode(const unsigned char* input,size_t l,std::string& output,bool add_crlf)
{
- size_t i = 0;
- size_t o = 0;
-
- output = "";
- while (i < l)
- {
- size_t remain = l - i;
- if (add_crlf && o && o % 76 == 0)
- output += "\n";
- switch (remain)
- {
- case 1:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) ];
- output += "==";
- break;
- case 2:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
- output += "=";
- break;
- default:
- output += bstr[ ((input[i] >> 2) & 0x3f) ];
- output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
- output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
- output += bstr[ (input[i + 2] & 0x3f) ];
- }
- o += 4;
- i += 3;
- }
+ size_t i = 0;
+ size_t o = 0;
+
+ output = "";
+ while (i < l)
+ {
+ size_t remain = l - i;
+ if (add_crlf && o && o % 76 == 0)
+ output += "\n";
+ switch (remain)
+ {
+ case 1:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) ];
+ output += "==";
+ break;
+ case 2:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
+ output += "=";
+ break;
+ default:
+ output += bstr[ ((input[i] >> 2) & 0x3f) ];
+ output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
+ output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
+ output += bstr[ (input[i + 2] & 0x3f) ];
+ }
+ o += 4;
+ i += 3;
+ }
}
void Base64::decode(const std::string& input,std::string& output)
{
- size_t i = 0;
- size_t l = input.size();
-
- output = "";
- while (i < l)
- {
- while (i < l && (input[i] == 13 || input[i] == 10))
- i++;
- if (i < l)
- {
- char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) +
- (rstr[(int)input[i + 1]] >> 4 & 0x03));
- output += b1;
- if (input[i + 2] != '=')
- {
- char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
- (rstr[(int)input[i + 2]] >> 2 & 0x0f));
- output += b2;
- }
- if (input[i + 3] != '=')
- {
- char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
- rstr[(int)input[i + 3]]);
- output += b3;
- }
- i += 4;
- }
- }
+ size_t i = 0;
+ size_t l = input.size();
+
+ output = "";
+ while (i < l)
+ {
+ while (i < l && (input[i] == 13 || input[i] == 10))
+ i++;
+ if (i < l)
+ {
+ char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) +
+ (rstr[(int)input[i + 1]] >> 4 & 0x03));
+ output += b1;
+ if (input[i + 2] != '=')
+ {
+ char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
+ (rstr[(int)input[i + 2]] >> 2 & 0x0f));
+ output += b2;
+ }
+ if (input[i + 3] != '=')
+ {
+ char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
+ rstr[(int)input[i + 3]]);
+ output += b3;
+ }
+ i += 4;
+ }
+ }
}
void Base64::decode(const std::string& input, unsigned char *output, size_t& sz)
{
- size_t i = 0;
- size_t l = input.size();
- size_t j = 0;
-
- while (i < l)
- {
- while (i < l && (input[i] == 13 || input[i] == 10))
- i++;
- if (i < l)
- {
- unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) +
- (rstr[(int)input[i + 1]] >> 4 & 0x03));
- if (output)
- {
- output[j] = b1;
- }
- j++;
- if (input[i + 2] != '=')
- {
- unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
- (rstr[(int)input[i + 2]] >> 2 & 0x0f));
- if (output)
- {
- output[j] = b2;
- }
- j++;
- }
- if (input[i + 3] != '=')
- {
- unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
- rstr[(int)input[i + 3]]);
- if (output)
- {
- output[j] = b3;
- }
- j++;
- }
- i += 4;
- }
- }
- sz = j;
+ size_t i = 0;
+ size_t l = input.size();
+ size_t j = 0;
+
+ while (i < l)
+ {
+ while (i < l && (input[i] == 13 || input[i] == 10))
+ i++;
+ if (i < l)
+ {
+ unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) +
+ (rstr[(int)input[i + 1]] >> 4 & 0x03));
+ if (output)
+ {
+ output[j] = b1;
+ }
+ j++;
+ if (input[i + 2] != '=')
+ {
+ unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
+ (rstr[(int)input[i + 2]] >> 2 & 0x0f));
+ if (output)
+ {
+ output[j] = b2;
+ }
+ j++;
+ }
+ if (input[i + 3] != '=')
+ {
+ unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
+ rstr[(int)input[i + 3]]);
+ if (output)
+ {
+ output[j] = b3;
+ }
+ j++;
+ }
+ i += 4;
+ }
+ }
+ sz = j;
}
size_t Base64::decode_length(const std::string& str64)
{
- if (str64.empty() || str64.size() % 4)
- return 0;
- size_t l = 3 * (str64.size() / 4 - 1) + 1;
- if (str64[str64.size() - 2] != '=')
- l++;
- if (str64[str64.size() - 1] != '=')
- l++;
- return l;
+ if (str64.empty() || str64.size() % 4)
+ return 0;
+ size_t l = 3 * (str64.size() / 4 - 1) + 1;
+ if (str64[str64.size() - 2] != '=')
+ l++;
+ if (str64[str64.size() - 1] != '=')
+ l++;
+ return l;
}
diff --git a/dep/src/sockets/Exception.cpp b/dep/src/sockets/Exception.cpp
index a005669e4c9..b3844982c0f 100644
--- a/dep/src/sockets/Exception.cpp
+++ b/dep/src/sockets/Exception.cpp
@@ -1,7 +1,7 @@
/**
- ** \file Exception.cpp
- ** \date 2007-09-28
- ** \author grymse@alhem.net
+ ** \file Exception.cpp
+ ** \date 2007-09-28
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2007 Anders Hedstrom
@@ -38,7 +38,7 @@ Exception::Exception(const std::string& description) : m_description(description
const std::string Exception::ToString() const
{
- return m_description;
+ return m_description;
}
diff --git a/dep/src/sockets/Ipv4Address.cpp b/dep/src/sockets/Ipv4Address.cpp
index 58f25e53b83..88a7d33fb63 100644
--- a/dep/src/sockets/Ipv4Address.cpp
+++ b/dep/src/sockets/Ipv4Address.cpp
@@ -1,7 +1,7 @@
/**
- ** \file Ipv4Address.cpp
- ** \date 2006-09-21
- ** \author grymse@alhem.net
+ ** \file Ipv4Address.cpp
+ ** \date 2006-09-21
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2007 Anders Hedstrom
@@ -36,50 +36,50 @@ namespace SOCKETS_NAMESPACE {
Ipv4Address::Ipv4Address(port_t port) : m_valid(true)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin_family = AF_INET;
- m_addr.sin_port = htons( port );
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin_family = AF_INET;
+ m_addr.sin_port = htons( port );
}
Ipv4Address::Ipv4Address(ipaddr_t a,port_t port) : m_valid(true)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin_family = AF_INET;
- m_addr.sin_port = htons( port );
- memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr));
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin_family = AF_INET;
+ m_addr.sin_port = htons( port );
+ memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr));
}
Ipv4Address::Ipv4Address(struct in_addr& a,port_t port) : m_valid(true)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin_family = AF_INET;
- m_addr.sin_port = htons( port );
- m_addr.sin_addr = a;
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin_family = AF_INET;
+ m_addr.sin_port = htons( port );
+ m_addr.sin_addr = a;
}
Ipv4Address::Ipv4Address(const std::string& host,port_t port) : m_valid(false)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin_family = AF_INET;
- m_addr.sin_port = htons( port );
- {
- ipaddr_t a;
- if (Utility::u2ip(host, a))
- {
- memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr));
- m_valid = true;
- }
- }
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin_family = AF_INET;
+ m_addr.sin_port = htons( port );
+ {
+ ipaddr_t a;
+ if (Utility::u2ip(host, a))
+ {
+ memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr));
+ m_valid = true;
+ }
+ }
}
Ipv4Address::Ipv4Address(struct sockaddr_in& sa)
{
- m_addr = sa;
- m_valid = sa.sin_family == AF_INET;
+ m_addr = sa;
+ m_valid = sa.sin_family == AF_INET;
}
@@ -90,121 +90,121 @@ Ipv4Address::~Ipv4Address()
Ipv4Address::operator struct sockaddr *()
{
- return (struct sockaddr *)&m_addr;
+ return (struct sockaddr *)&m_addr;
}
Ipv4Address::operator socklen_t()
{
- return sizeof(struct sockaddr_in);
+ return sizeof(struct sockaddr_in);
}
void Ipv4Address::SetPort(port_t port)
{
- m_addr.sin_port = htons( port );
+ m_addr.sin_port = htons( port );
}
port_t Ipv4Address::GetPort()
{
- return ntohs( m_addr.sin_port );
+ return ntohs( m_addr.sin_port );
}
bool Ipv4Address::Resolve(const std::string& hostname,struct in_addr& a)
{
- struct sockaddr_in sa;
- memset(&a, 0, sizeof(a));
- if (Utility::isipv4(hostname))
- {
- if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST))
- return false;
- a = sa.sin_addr;
- return true;
- }
- if (!Utility::u2ip(hostname, sa))
- return false;
- a = sa.sin_addr;
- return true;
+ struct sockaddr_in sa;
+ memset(&a, 0, sizeof(a));
+ if (Utility::isipv4(hostname))
+ {
+ if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST))
+ return false;
+ a = sa.sin_addr;
+ return true;
+ }
+ if (!Utility::u2ip(hostname, sa))
+ return false;
+ a = sa.sin_addr;
+ return true;
}
bool Ipv4Address::Reverse(struct in_addr& a,std::string& name)
{
- struct sockaddr_in sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- sa.sin_addr = a;
- return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name);
+ struct sockaddr_in sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
+ sa.sin_addr = a;
+ return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name);
}
std::string Ipv4Address::Convert(bool include_port)
{
- if (include_port)
- return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort());
- return Convert(m_addr.sin_addr);
+ if (include_port)
+ return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort());
+ return Convert(m_addr.sin_addr);
}
std::string Ipv4Address::Convert(struct in_addr& a)
{
- struct sockaddr_in sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- sa.sin_addr = a;
- std::string name;
- Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST);
- return name;
+ struct sockaddr_in sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
+ sa.sin_addr = a;
+ std::string name;
+ Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST);
+ return name;
}
void Ipv4Address::SetAddress(struct sockaddr *sa)
{
- memcpy(&m_addr, sa, sizeof(struct sockaddr_in));
+ memcpy(&m_addr, sa, sizeof(struct sockaddr_in));
}
int Ipv4Address::GetFamily()
{
- return m_addr.sin_family;
+ return m_addr.sin_family;
}
bool Ipv4Address::IsValid()
{
- return m_valid;
+ return m_valid;
}
bool Ipv4Address::operator==(SocketAddress& a)
{
- if (a.GetFamily() != GetFamily())
- return false;
- if ((socklen_t)a != sizeof(m_addr))
- return false;
- struct sockaddr *sa = a;
- struct sockaddr_in *p = (struct sockaddr_in *)sa;
- if (p -> sin_port != m_addr.sin_port)
- return false;
- if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4))
- return false;
- return true;
+ if (a.GetFamily() != GetFamily())
+ return false;
+ if ((socklen_t)a != sizeof(m_addr))
+ return false;
+ struct sockaddr *sa = a;
+ struct sockaddr_in *p = (struct sockaddr_in *)sa;
+ if (p -> sin_port != m_addr.sin_port)
+ return false;
+ if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4))
+ return false;
+ return true;
}
std::auto_ptr<SocketAddress> Ipv4Address::GetCopy()
{
- return std::auto_ptr<SocketAddress>(new Ipv4Address(m_addr));
+ return std::auto_ptr<SocketAddress>(new Ipv4Address(m_addr));
}
std::string Ipv4Address::Reverse()
{
- std::string tmp;
- Reverse(m_addr.sin_addr, tmp);
- return tmp;
+ std::string tmp;
+ Reverse(m_addr.sin_addr, tmp);
+ return tmp;
}
diff --git a/dep/src/sockets/Ipv6Address.cpp b/dep/src/sockets/Ipv6Address.cpp
index 2e0f1e9acf3..c6f1443af2e 100644
--- a/dep/src/sockets/Ipv6Address.cpp
+++ b/dep/src/sockets/Ipv6Address.cpp
@@ -1,7 +1,7 @@
/**
- ** \file Ipv6Address.cpp
- ** \date 2006-09-21
- ** \author grymse@alhem.net
+ ** \file Ipv6Address.cpp
+ ** \date 2006-09-21
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2007 Anders Hedstrom
@@ -37,41 +37,41 @@ namespace SOCKETS_NAMESPACE {
Ipv6Address::Ipv6Address(port_t port) : m_valid(true)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin6_family = AF_INET6;
- m_addr.sin6_port = htons( port );
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin6_family = AF_INET6;
+ m_addr.sin6_port = htons( port );
}
Ipv6Address::Ipv6Address(struct in6_addr& a,port_t port) : m_valid(true)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin6_family = AF_INET6;
- m_addr.sin6_port = htons( port );
- m_addr.sin6_addr = a;
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin6_family = AF_INET6;
+ m_addr.sin6_port = htons( port );
+ m_addr.sin6_addr = a;
}
Ipv6Address::Ipv6Address(const std::string& host,port_t port) : m_valid(false)
{
- memset(&m_addr, 0, sizeof(m_addr));
- m_addr.sin6_family = AF_INET6;
- m_addr.sin6_port = htons( port );
- {
- struct in6_addr a;
- if (Utility::u2ip(host, a))
- {
- m_addr.sin6_addr = a;
- m_valid = true;
- }
- }
+ memset(&m_addr, 0, sizeof(m_addr));
+ m_addr.sin6_family = AF_INET6;
+ m_addr.sin6_port = htons( port );
+ {
+ struct in6_addr a;
+ if (Utility::u2ip(host, a))
+ {
+ m_addr.sin6_addr = a;
+ m_valid = true;
+ }
+ }
}
Ipv6Address::Ipv6Address(struct sockaddr_in6& sa)
{
- m_addr = sa;
- m_valid = sa.sin6_family == AF_INET6;
+ m_addr = sa;
+ m_valid = sa.sin6_family == AF_INET6;
}
@@ -82,183 +82,183 @@ Ipv6Address::~Ipv6Address()
Ipv6Address::operator struct sockaddr *()
{
- return (struct sockaddr *)&m_addr;
+ return (struct sockaddr *)&m_addr;
}
Ipv6Address::operator socklen_t()
{
- return sizeof(struct sockaddr_in6);
+ return sizeof(struct sockaddr_in6);
}
void Ipv6Address::SetPort(port_t port)
{
- m_addr.sin6_port = htons( port );
+ m_addr.sin6_port = htons( port );
}
port_t Ipv6Address::GetPort()
{
- return ntohs( m_addr.sin6_port );
+ return ntohs( m_addr.sin6_port );
}
bool Ipv6Address::Resolve(const std::string& hostname,struct in6_addr& a)
{
- struct sockaddr_in6 sa;
- memset(&a, 0, sizeof(a));
- if (Utility::isipv6(hostname))
- {
- if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST))
- return false;
- a = sa.sin6_addr;
- return true;
- }
- if (!Utility::u2ip(hostname, sa))
- return false;
- a = sa.sin6_addr;
- return true;
+ struct sockaddr_in6 sa;
+ memset(&a, 0, sizeof(a));
+ if (Utility::isipv6(hostname))
+ {
+ if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST))
+ return false;
+ a = sa.sin6_addr;
+ return true;
+ }
+ if (!Utility::u2ip(hostname, sa))
+ return false;
+ a = sa.sin6_addr;
+ return true;
}
bool Ipv6Address::Reverse(struct in6_addr& a,std::string& name)
{
- struct sockaddr_in6 sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin6_family = AF_INET6;
- sa.sin6_addr = a;
- return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name);
+ struct sockaddr_in6 sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin6_family = AF_INET6;
+ sa.sin6_addr = a;
+ return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name);
}
std::string Ipv6Address::Convert(bool include_port)
{
- if (include_port)
- return Convert(m_addr.sin6_addr) + ":" + Utility::l2string(GetPort());
- return Convert(m_addr.sin6_addr);
+ if (include_port)
+ return Convert(m_addr.sin6_addr) + ":" + Utility::l2string(GetPort());
+ return Convert(m_addr.sin6_addr);
}
std::string Ipv6Address::Convert(struct in6_addr& a,bool mixed)
{
- char slask[100]; // l2ip temporary
- *slask = 0;
- unsigned int prev = 0;
- bool skipped = false;
- bool ok_to_skip = true;
- if (mixed)
- {
- unsigned short x;
- unsigned short addr16[8];
- memcpy(addr16, &a, sizeof(addr16));
- for (size_t i = 0; i < 6; i++)
- {
- x = ntohs(addr16[i]);
- if (*slask && (x || !ok_to_skip || prev))
- strcat(slask,":");
- if (x || !ok_to_skip)
- {
- sprintf(slask + strlen(slask),"%x", x);
- if (x && skipped)
- ok_to_skip = false;
- }
- else
- {
- skipped = true;
- }
- prev = x;
- }
- x = ntohs(addr16[6]);
- sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255);
- x = ntohs(addr16[7]);
- sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255);
- }
- else
- {
- struct sockaddr_in6 sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin6_family = AF_INET6;
- sa.sin6_addr = a;
- std::string name;
- Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST);
- return name;
- }
- return slask;
+ char slask[100]; // l2ip temporary
+ *slask = 0;
+ unsigned int prev = 0;
+ bool skipped = false;
+ bool ok_to_skip = true;
+ if (mixed)
+ {
+ unsigned short x;
+ unsigned short addr16[8];
+ memcpy(addr16, &a, sizeof(addr16));
+ for (size_t i = 0; i < 6; i++)
+ {
+ x = ntohs(addr16[i]);
+ if (*slask && (x || !ok_to_skip || prev))
+ strcat(slask,":");
+ if (x || !ok_to_skip)
+ {
+ sprintf(slask + strlen(slask),"%x", x);
+ if (x && skipped)
+ ok_to_skip = false;
+ }
+ else
+ {
+ skipped = true;
+ }
+ prev = x;
+ }
+ x = ntohs(addr16[6]);
+ sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255);
+ x = ntohs(addr16[7]);
+ sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255);
+ }
+ else
+ {
+ struct sockaddr_in6 sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin6_family = AF_INET6;
+ sa.sin6_addr = a;
+ std::string name;
+ Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST);
+ return name;
+ }
+ return slask;
}
void Ipv6Address::SetAddress(struct sockaddr *sa)
{
- memcpy(&m_addr, sa, sizeof(struct sockaddr_in6));
+ memcpy(&m_addr, sa, sizeof(struct sockaddr_in6));
}
int Ipv6Address::GetFamily()
{
- return m_addr.sin6_family;
+ return m_addr.sin6_family;
}
void Ipv6Address::SetFlowinfo(uint32_t x)
{
- m_addr.sin6_flowinfo = x;
+ m_addr.sin6_flowinfo = x;
}
uint32_t Ipv6Address::GetFlowinfo()
{
- return m_addr.sin6_flowinfo;
+ return m_addr.sin6_flowinfo;
}
#ifndef _WIN32
void Ipv6Address::SetScopeId(uint32_t x)
{
- m_addr.sin6_scope_id = x;
+ m_addr.sin6_scope_id = x;
}
uint32_t Ipv6Address::GetScopeId()
{
- return m_addr.sin6_scope_id;
+ return m_addr.sin6_scope_id;
}
#endif
bool Ipv6Address::IsValid()
{
- return m_valid;
+ return m_valid;
}
bool Ipv6Address::operator==(SocketAddress& a)
{
- if (a.GetFamily() != GetFamily())
- return false;
- if ((socklen_t)a != sizeof(m_addr))
- return false;
- struct sockaddr *sa = a;
- struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa;
- if (p -> sin6_port != m_addr.sin6_port)
- return false;
- if (memcmp(&p -> sin6_addr, &m_addr.sin6_addr, sizeof(struct in6_addr)))
- return false;
- return true;
+ if (a.GetFamily() != GetFamily())
+ return false;
+ if ((socklen_t)a != sizeof(m_addr))
+ return false;
+ struct sockaddr *sa = a;
+ struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa;
+ if (p -> sin6_port != m_addr.sin6_port)
+ return false;
+ if (memcmp(&p -> sin6_addr, &m_addr.sin6_addr, sizeof(struct in6_addr)))
+ return false;
+ return true;
}
std::auto_ptr<SocketAddress> Ipv6Address::GetCopy()
{
- return std::auto_ptr<SocketAddress>(new Ipv6Address(m_addr));
+ return std::auto_ptr<SocketAddress>(new Ipv6Address(m_addr));
}
std::string Ipv6Address::Reverse()
{
- std::string tmp;
- Reverse(m_addr.sin6_addr, tmp);
- return tmp;
+ std::string tmp;
+ Reverse(m_addr.sin6_addr, tmp);
+ return tmp;
}
diff --git a/dep/src/sockets/Lock.cpp b/dep/src/sockets/Lock.cpp
index 3f7902e232b..3f7ad87b2ba 100644
--- a/dep/src/sockets/Lock.cpp
+++ b/dep/src/sockets/Lock.cpp
@@ -1,6 +1,6 @@
/** \file Lock.cpp
- ** \date 2005-08-22
- ** \author grymse@alhem.net
+ ** \date 2005-08-22
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2005,2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2005,2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -37,13 +37,13 @@ namespace SOCKETS_NAMESPACE {
Lock::Lock(Mutex& m) : m_mutex(m)
{
- m_mutex.Lock();
+ m_mutex.Lock();
}
Lock::~Lock()
{
- m_mutex.Unlock();
+ m_mutex.Unlock();
}
diff --git a/dep/src/sockets/Mutex.cpp b/dep/src/sockets/Mutex.cpp
index f7a03c7d990..8284fefacd8 100644
--- a/dep/src/sockets/Mutex.cpp
+++ b/dep/src/sockets/Mutex.cpp
@@ -1,6 +1,6 @@
/** \file Mutex.cpp
- ** \date 2004-10-30
- ** \author grymse@alhem.net
+ ** \date 2004-10-30
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -37,9 +37,9 @@ namespace SOCKETS_NAMESPACE {
Mutex::Mutex()
{
#ifdef _WIN32
- m_mutex = ::CreateMutex(NULL, FALSE, NULL);
+ m_mutex = ::CreateMutex(NULL, FALSE, NULL);
#else
- pthread_mutex_init(&m_mutex, NULL);
+ pthread_mutex_init(&m_mutex, NULL);
#endif
}
@@ -47,9 +47,9 @@ Mutex::Mutex()
Mutex::~Mutex()
{
#ifdef _WIN32
- ::CloseHandle(m_mutex);
+ ::CloseHandle(m_mutex);
#else
- pthread_mutex_destroy(&m_mutex);
+ pthread_mutex_destroy(&m_mutex);
#endif
}
@@ -57,10 +57,10 @@ Mutex::~Mutex()
void Mutex::Lock()
{
#ifdef _WIN32
- /*DWORD d =*/ WaitForSingleObject(m_mutex, INFINITE);
- /// \todo check 'd' for result
+ /*DWORD d =*/ WaitForSingleObject(m_mutex, INFINITE);
+ /// \todo check 'd' for result
#else
- pthread_mutex_lock(&m_mutex);
+ pthread_mutex_lock(&m_mutex);
#endif
}
@@ -68,9 +68,9 @@ void Mutex::Lock()
void Mutex::Unlock()
{
#ifdef _WIN32
- ::ReleaseMutex(m_mutex);
+ ::ReleaseMutex(m_mutex);
#else
- pthread_mutex_unlock(&m_mutex);
+ pthread_mutex_unlock(&m_mutex);
#endif
}
diff --git a/dep/src/sockets/Parse.cpp b/dep/src/sockets/Parse.cpp
index 58122c0c96e..4d4dd99cd98 100644
--- a/dep/src/sockets/Parse.cpp
+++ b/dep/src/sockets/Parse.cpp
@@ -1,6 +1,6 @@
/** \file Parse.cpp - parse a string
**
- ** Written: 1999-Feb-10 grymse@alhem.net
+ ** Written: 1999-Feb-10 grymse@alhem.net
**/
/*
@@ -9,7 +9,7 @@ Copyright (C) 1999-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -102,214 +102,214 @@ Parse::~Parse()
short Parse::issplit(const char c)
{
- for (size_t i = 0; i < pa_splits.size(); i++)
- if (pa_splits[i] == c)
- return 1;
- return 0;
+ for (size_t i = 0; i < pa_splits.size(); i++)
+ if (pa_splits[i] == c)
+ return 1;
+ return 0;
}
void Parse::getsplit()
{
- size_t x;
-
- if (C == '=')
- {
- x = pa_the_ptr++;
- } else
- {
- while (C && (issplit(C)))
- pa_the_ptr++;
- x = pa_the_ptr;
- while (C && !issplit(C) && C != '=')
- pa_the_ptr++;
- }
- if (x == pa_the_ptr && C == '=')
- pa_the_ptr++;
- pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
+ size_t x;
+
+ if (C == '=')
+ {
+ x = pa_the_ptr++;
+ } else
+ {
+ while (C && (issplit(C)))
+ pa_the_ptr++;
+ x = pa_the_ptr;
+ while (C && !issplit(C) && C != '=')
+ pa_the_ptr++;
+ }
+ if (x == pa_the_ptr && C == '=')
+ pa_the_ptr++;
+ pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
}
std::string Parse::getword()
{
- size_t x;
- int disabled = 0;
- int quote = 0;
- int rem = 0;
-
- if (pa_nospace)
- {
- while (C && issplit(C))
- pa_the_ptr++;
- x = pa_the_ptr;
- while (C && !issplit(C) && (C != pa_breakchar || !pa_breakchar || disabled))
- {
- if (pa_breakchar && C == pa_disable)
- disabled = 1;
- if (pa_breakchar && C == pa_enable)
- disabled = 0;
- if (pa_quote && C == '"')
- quote = 1;
- pa_the_ptr++;
- while (quote && C && C != '"')
- {
- pa_the_ptr++;
- }
- if (pa_quote && C == '"')
- {
- pa_the_ptr++;
- }
- quote = 0;
- }
- } else
- {
- if (C == pa_breakchar && pa_breakchar)
- {
- x = pa_the_ptr++;
- rem = 1;
- } else
- {
- while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
- pa_the_ptr++;
- x = pa_the_ptr;
- while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) &&
- (C != pa_breakchar || !pa_breakchar || disabled))
- {
- if (pa_breakchar && C == pa_disable)
- disabled = 1;
- if (pa_breakchar && C == pa_enable)
- disabled = 0;
- if (pa_quote && C == '"')
- {
- quote = 1;
- pa_the_ptr++;
- while (quote && C && C != '"')
- {
- pa_the_ptr++;
- }
- if (pa_quote && C == '"')
- {
- pa_the_ptr++;
- }
- }
- else
- pa_the_ptr++;
- quote = 0;
- }
- pa_the_ptr++;
- rem = 1;
- }
- if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
- pa_the_ptr++;
- }
- if (x < pa_the_str.size())
- {
- pa_ord = pa_the_str.substr(x,pa_the_ptr - x - rem);
- }
- else
- {
- pa_ord = "";
- }
- return pa_ord;
+ size_t x;
+ int disabled = 0;
+ int quote = 0;
+ int rem = 0;
+
+ if (pa_nospace)
+ {
+ while (C && issplit(C))
+ pa_the_ptr++;
+ x = pa_the_ptr;
+ while (C && !issplit(C) && (C != pa_breakchar || !pa_breakchar || disabled))
+ {
+ if (pa_breakchar && C == pa_disable)
+ disabled = 1;
+ if (pa_breakchar && C == pa_enable)
+ disabled = 0;
+ if (pa_quote && C == '"')
+ quote = 1;
+ pa_the_ptr++;
+ while (quote && C && C != '"')
+ {
+ pa_the_ptr++;
+ }
+ if (pa_quote && C == '"')
+ {
+ pa_the_ptr++;
+ }
+ quote = 0;
+ }
+ } else
+ {
+ if (C == pa_breakchar && pa_breakchar)
+ {
+ x = pa_the_ptr++;
+ rem = 1;
+ } else
+ {
+ while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
+ pa_the_ptr++;
+ x = pa_the_ptr;
+ while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) &&
+ (C != pa_breakchar || !pa_breakchar || disabled))
+ {
+ if (pa_breakchar && C == pa_disable)
+ disabled = 1;
+ if (pa_breakchar && C == pa_enable)
+ disabled = 0;
+ if (pa_quote && C == '"')
+ {
+ quote = 1;
+ pa_the_ptr++;
+ while (quote && C && C != '"')
+ {
+ pa_the_ptr++;
+ }
+ if (pa_quote && C == '"')
+ {
+ pa_the_ptr++;
+ }
+ }
+ else
+ pa_the_ptr++;
+ quote = 0;
+ }
+ pa_the_ptr++;
+ rem = 1;
+ }
+ if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
+ pa_the_ptr++;
+ }
+ if (x < pa_the_str.size())
+ {
+ pa_ord = pa_the_str.substr(x,pa_the_ptr - x - rem);
+ }
+ else
+ {
+ pa_ord = "";
+ }
+ return pa_ord;
}
void Parse::getword(std::string&s)
{
- s = Parse::getword();
+ s = Parse::getword();
}
void Parse::getsplit(std::string&s)
{
- Parse::getsplit();
- s = pa_ord;
+ Parse::getsplit();
+ s = pa_ord;
}
void Parse::getword(std::string&s,std::string&fill,int l)
{
- Parse::getword();
- s = "";
- while (s.size() + pa_ord.size() < (size_t)l)
- s += fill;
- s += pa_ord;
+ Parse::getword();
+ s = "";
+ while (s.size() + pa_ord.size() < (size_t)l)
+ s += fill;
+ s += pa_ord;
}
std::string Parse::getrest()
{
- std::string s;
- while (C && (C == ' ' || C == 9 || issplit(C)))
- pa_the_ptr++;
- s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
- return s;
+ std::string s;
+ while (C && (C == ' ' || C == 9 || issplit(C)))
+ pa_the_ptr++;
+ s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
+ return s;
}
void Parse::getrest(std::string&s)
{
- while (C && (C == ' ' || C == 9 || issplit(C)))
- pa_the_ptr++;
- s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
+ while (C && (C == ' ' || C == 9 || issplit(C)))
+ pa_the_ptr++;
+ s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
}
long Parse::getvalue()
{
- Parse::getword();
- return atol(pa_ord.c_str());
+ Parse::getword();
+ return atol(pa_ord.c_str());
}
void Parse::setbreak(const char c)
{
- pa_breakchar = c;
+ pa_breakchar = c;
}
int Parse::getwordlen()
{
- size_t x,y = pa_the_ptr,len;
-
- if (C == pa_breakchar && pa_breakchar)
- {
- x = pa_the_ptr++;
- } else
- {
- while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
- pa_the_ptr++;
- x = pa_the_ptr;
- while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) && (C != pa_breakchar || !pa_breakchar))
- pa_the_ptr++;
- }
- if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
- pa_the_ptr++;
- len = pa_the_ptr - x;
- pa_the_ptr = y;
- return (int)len;
+ size_t x,y = pa_the_ptr,len;
+
+ if (C == pa_breakchar && pa_breakchar)
+ {
+ x = pa_the_ptr++;
+ } else
+ {
+ while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
+ pa_the_ptr++;
+ x = pa_the_ptr;
+ while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) && (C != pa_breakchar || !pa_breakchar))
+ pa_the_ptr++;
+ }
+ if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
+ pa_the_ptr++;
+ len = pa_the_ptr - x;
+ pa_the_ptr = y;
+ return (int)len;
}
int Parse::getrestlen()
{
- size_t y = pa_the_ptr;
- size_t len;
-
- while (C && (C == ' ' || C == 9 || issplit(C)))
- pa_the_ptr++;
- len = strlen(pa_the_str.c_str() + pa_the_ptr);
- pa_the_ptr = y;
- return (int)len;
+ size_t y = pa_the_ptr;
+ size_t len;
+
+ while (C && (C == ' ' || C == 9 || issplit(C)))
+ pa_the_ptr++;
+ len = strlen(pa_the_str.c_str() + pa_the_ptr);
+ pa_the_ptr = y;
+ return (int)len;
}
void Parse::getline()
{
- size_t x;
-
- x = pa_the_ptr;
- while (C && C != 13 && C != 10)
- pa_the_ptr++;
- pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
- if (C == 13)
- pa_the_ptr++;
- if (C == 10)
- pa_the_ptr++;
+ size_t x;
+
+ x = pa_the_ptr;
+ while (C && C != 13 && C != 10)
+ pa_the_ptr++;
+ pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
+ if (C == 13)
+ pa_the_ptr++;
+ if (C == 10)
+ pa_the_ptr++;
}
void Parse::getline(std::string&s)
{
- getline();
- s = pa_ord;
+ getline();
+ s = pa_ord;
}
/* end of implementation of class Parse */
diff --git a/dep/src/sockets/ResolvServer.cpp b/dep/src/sockets/ResolvServer.cpp
index 83f842b5343..3923df33079 100644
--- a/dep/src/sockets/ResolvServer.cpp
+++ b/dep/src/sockets/ResolvServer.cpp
@@ -1,6 +1,6 @@
/** \file ResolvServer.cpp
- ** \date 2005-03-24
- ** \author grymse@alhem.net
+ ** \date 2005-03-24
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -58,34 +58,34 @@ ResolvServer::~ResolvServer()
void ResolvServer::Run()
{
-// StdoutLog log;
- SocketHandler h;
- ListenSocket<ResolvSocket> l(h);
-
- if (l.Bind("127.0.0.1", m_port))
- {
- return;
- }
- h.Add(&l);
-
- m_ready = true;
- while (!m_quit && IsRunning() )
- {
- h.Select(0, 500000);
- }
- SetRunning(false);
+// StdoutLog log;
+ SocketHandler h;
+ ListenSocket<ResolvSocket> l(h);
+
+ if (l.Bind("127.0.0.1", m_port))
+ {
+ return;
+ }
+ h.Add(&l);
+
+ m_ready = true;
+ while (!m_quit && IsRunning() )
+ {
+ h.Select(0, 500000);
+ }
+ SetRunning(false);
}
void ResolvServer::Quit()
{
- m_quit = true;
+ m_quit = true;
}
bool ResolvServer::Ready()
{
- return m_ready;
+ return m_ready;
}
diff --git a/dep/src/sockets/ResolvSocket.cpp b/dep/src/sockets/ResolvSocket.cpp
index 2d9d31d5a4f..6096dc89e37 100644
--- a/dep/src/sockets/ResolvSocket.cpp
+++ b/dep/src/sockets/ResolvSocket.cpp
@@ -1,6 +1,6 @@
/** \file ResolvSocket.cpp
- ** \date 2005-03-24
- ** \author grymse@alhem.net
+ ** \date 2005-03-24
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -69,7 +69,7 @@ ResolvSocket::ResolvSocket(ISocketHandler& h)
#endif
,m_cached(false)
{
- SetLineProtocol();
+ SetLineProtocol();
}
@@ -84,7 +84,7 @@ ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, const std::string&
#endif
,m_cached(false)
{
- SetLineProtocol();
+ SetLineProtocol();
}
@@ -99,7 +99,7 @@ ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, ipaddr_t a)
#endif
,m_cached(false)
{
- SetLineProtocol();
+ SetLineProtocol();
}
@@ -113,7 +113,7 @@ ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, in6_addr& a)
,m_resolv_address6(a)
,m_cached(false)
{
- SetLineProtocol();
+ SetLineProtocol();
}
#endif
@@ -125,145 +125,145 @@ ResolvSocket::~ResolvSocket()
void ResolvSocket::OnLine(const std::string& line)
{
- Parse pa(line, ":");
- if (m_bServer)
- {
- m_query = pa.getword();
- m_data = pa.getrest();
-DEB( fprintf(stderr, " *** ResolvSocket server; query=%s, data=%s\n", m_query.c_str(), m_data.c_str());)
- // %! check cache
- {
- Lock lock(m_cache_mutex);
- if (m_cache[m_query].find(m_data) != m_cache[m_query].end())
- {
- if (time(NULL) - m_cache_to[m_query][m_data] < 3600) // ttl
- {
- std::string result = m_cache[m_query][m_data];
+ Parse pa(line, ":");
+ if (m_bServer)
+ {
+ m_query = pa.getword();
+ m_data = pa.getrest();
+DEB( fprintf(stderr, " *** ResolvSocket server; query=%s, data=%s\n", m_query.c_str(), m_data.c_str());)
+ // %! check cache
+ {
+ Lock lock(m_cache_mutex);
+ if (m_cache[m_query].find(m_data) != m_cache[m_query].end())
+ {
+ if (time(NULL) - m_cache_to[m_query][m_data] < 3600) // ttl
+ {
+ std::string result = m_cache[m_query][m_data];
DEB(fprintf(stderr, " *** Returning cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), result.c_str());)
- Send("Cached\n");
- if (!result.size()) /* failed */
- {
- Send("Failed\n\n");
- SetCloseAndDelete();
- return;
- }
- else
- if (m_query == "gethostbyname")
- {
- Send("A: " + result + "\n\n");
- SetCloseAndDelete();
- return;
- }
- else
+ Send("Cached\n");
+ if (!result.size()) /* failed */
+ {
+ Send("Failed\n\n");
+ SetCloseAndDelete();
+ return;
+ }
+ else
+ if (m_query == "gethostbyname")
+ {
+ Send("A: " + result + "\n\n");
+ SetCloseAndDelete();
+ return;
+ }
+ else
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (m_query == "gethostbyname2")
- {
- Send("AAAA: " + result + "\n\n");
- SetCloseAndDelete();
- return;
- }
- else
+ if (m_query == "gethostbyname2")
+ {
+ Send("AAAA: " + result + "\n\n");
+ SetCloseAndDelete();
+ return;
+ }
+ else
#endif
#endif
- if (m_query == "gethostbyaddr")
- {
- Send("Name: " + result + "\n\n");
- SetCloseAndDelete();
- return;
- }
- }
- }
- }
- if (!Detach()) // detach failed?
- {
- SetCloseAndDelete();
- }
- return;
- }
- std::string key = pa.getword();
- std::string value = pa.getrest();
-DEB( fprintf(stderr, " *** ResolvSocket response; %s: %s\n", key.c_str(), value.c_str());)
-
- if (key == "Cached")
- {
- m_cached = true;
- }
- else
- if (key == "Failed" && m_parent)
- {
-DEB( fprintf(stderr, " ************ Resolve failed\n");)
- if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
- {
- m_parent -> OnResolveFailed(m_resolv_id);
- }
- // update cache
- if (!m_cached)
- {
- Lock lock(m_cache_mutex);
+ if (m_query == "gethostbyaddr")
+ {
+ Send("Name: " + result + "\n\n");
+ SetCloseAndDelete();
+ return;
+ }
+ }
+ }
+ }
+ if (!Detach()) // detach failed?
+ {
+ SetCloseAndDelete();
+ }
+ return;
+ }
+ std::string key = pa.getword();
+ std::string value = pa.getrest();
+DEB( fprintf(stderr, " *** ResolvSocket response; %s: %s\n", key.c_str(), value.c_str());)
+
+ if (key == "Cached")
+ {
+ m_cached = true;
+ }
+ else
+ if (key == "Failed" && m_parent)
+ {
+DEB( fprintf(stderr, " ************ Resolve failed\n");)
+ if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
+ {
+ m_parent -> OnResolveFailed(m_resolv_id);
+ }
+ // update cache
+ if (!m_cached)
+ {
+ Lock lock(m_cache_mutex);
DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());)
- m_cache[m_query][m_data] = value;
- m_cache_to[m_query][m_data] = time(NULL);
- }
- m_parent = NULL;
- }
- else
- if (key == "Name" && !m_resolv_host.size() && m_parent)
- {
- if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
- {
- m_parent -> OnReverseResolved(m_resolv_id, value);
- }
- // update cache
- if (!m_cached)
- {
- Lock lock(m_cache_mutex);
+ m_cache[m_query][m_data] = value;
+ m_cache_to[m_query][m_data] = time(NULL);
+ }
+ m_parent = NULL;
+ }
+ else
+ if (key == "Name" && !m_resolv_host.size() && m_parent)
+ {
+ if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
+ {
+ m_parent -> OnReverseResolved(m_resolv_id, value);
+ }
+ // update cache
+ if (!m_cached)
+ {
+ Lock lock(m_cache_mutex);
DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());)
- m_cache[m_query][m_data] = value;
- m_cache_to[m_query][m_data] = time(NULL);
- }
- m_parent = NULL;
- }
- else
- if (key == "A" && m_parent)
- {
- if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
- {
- ipaddr_t l;
- Utility::u2ip(value, l); // ip2ipaddr_t
- m_parent -> OnResolved(m_resolv_id, l, m_resolv_port);
- }
- // update cache
- if (!m_cached)
- {
- Lock lock(m_cache_mutex);
+ m_cache[m_query][m_data] = value;
+ m_cache_to[m_query][m_data] = time(NULL);
+ }
+ m_parent = NULL;
+ }
+ else
+ if (key == "A" && m_parent)
+ {
+ if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
+ {
+ ipaddr_t l;
+ Utility::u2ip(value, l); // ip2ipaddr_t
+ m_parent -> OnResolved(m_resolv_id, l, m_resolv_port);
+ }
+ // update cache
+ if (!m_cached)
+ {
+ Lock lock(m_cache_mutex);
DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());)
- m_cache[m_query][m_data] = value;
- m_cache_to[m_query][m_data] = time(NULL);
- }
- m_parent = NULL; // always use first ip in case there are several
- }
+ m_cache[m_query][m_data] = value;
+ m_cache_to[m_query][m_data] = time(NULL);
+ }
+ m_parent = NULL; // always use first ip in case there are several
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- else
- if (key == "AAAA" && m_parent)
- {
- if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
- {
- in6_addr a;
- Utility::u2ip(value, a);
- m_parent -> OnResolved(m_resolv_id, a, m_resolv_port);
- }
- // update cache
- if (!m_cached)
- {
- Lock lock(m_cache_mutex);
+ else
+ if (key == "AAAA" && m_parent)
+ {
+ if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
+ {
+ in6_addr a;
+ Utility::u2ip(value, a);
+ m_parent -> OnResolved(m_resolv_id, a, m_resolv_port);
+ }
+ // update cache
+ if (!m_cached)
+ {
+ Lock lock(m_cache_mutex);
DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());)
- m_cache[m_query][m_data] = value;
- m_cache_to[m_query][m_data] = time(NULL);
- }
- m_parent = NULL;
- }
+ m_cache[m_query][m_data] = value;
+ m_cache_to[m_query][m_data] = time(NULL);
+ }
+ m_parent = NULL;
+ }
#endif
#endif
}
@@ -271,160 +271,160 @@ DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(),
void ResolvSocket::OnDetached()
{
-DEB( fprintf(stderr, " *** ResolvSocket::OnDetached(); query=%s, data=%s\n", m_query.c_str(), m_data.c_str());)
- if (m_query == "gethostbyname")
- {
- struct sockaddr_in sa;
- if (Utility::u2ip(m_data, sa))
- {
- std::string ip;
- Utility::l2ip(sa.sin_addr, ip);
- Send("A: " + ip + "\n");
- }
- else
- {
- Send("Failed\n");
- }
- Send("\n");
- }
- else
+DEB( fprintf(stderr, " *** ResolvSocket::OnDetached(); query=%s, data=%s\n", m_query.c_str(), m_data.c_str());)
+ if (m_query == "gethostbyname")
+ {
+ struct sockaddr_in sa;
+ if (Utility::u2ip(m_data, sa))
+ {
+ std::string ip;
+ Utility::l2ip(sa.sin_addr, ip);
+ Send("A: " + ip + "\n");
+ }
+ else
+ {
+ Send("Failed\n");
+ }
+ Send("\n");
+ }
+ else
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (m_query == "gethostbyname2")
- {
- struct sockaddr_in6 sa;
- if (Utility::u2ip(m_data, sa))
- {
- std::string ip;
- Utility::l2ip(sa.sin6_addr, ip);
- Send("AAAA: " + ip + "\n");
- }
- else
- {
- Send("Failed\n");
- }
- Send("\n");
- }
- else
+ if (m_query == "gethostbyname2")
+ {
+ struct sockaddr_in6 sa;
+ if (Utility::u2ip(m_data, sa))
+ {
+ std::string ip;
+ Utility::l2ip(sa.sin6_addr, ip);
+ Send("AAAA: " + ip + "\n");
+ }
+ else
+ {
+ Send("Failed\n");
+ }
+ Send("\n");
+ }
+ else
#endif
#endif
- if (m_query == "gethostbyaddr")
- {
- if (Utility::isipv4( m_data ))
- {
- struct sockaddr_in sa;
- if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST))
- {
- Send("Failed: convert to sockaddr_in failed\n");
- }
- else
- {
- std::string name;
- if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name))
- {
- Send("Failed: ipv4 reverse lookup of " + m_data + "\n");
- }
- else
- {
- Send("Name: " + name + "\n");
- }
- }
- }
- else
+ if (m_query == "gethostbyaddr")
+ {
+ if (Utility::isipv4( m_data ))
+ {
+ struct sockaddr_in sa;
+ if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST))
+ {
+ Send("Failed: convert to sockaddr_in failed\n");
+ }
+ else
+ {
+ std::string name;
+ if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name))
+ {
+ Send("Failed: ipv4 reverse lookup of " + m_data + "\n");
+ }
+ else
+ {
+ Send("Name: " + name + "\n");
+ }
+ }
+ }
+ else
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (Utility::isipv6( m_data ))
- {
- struct sockaddr_in6 sa;
- if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST))
- {
- Send("Failed: convert to sockaddr_in6 failed\n");
- }
- else
- {
- std::string name;
- if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name))
- {
- Send("Failed: ipv6 reverse lookup of " + m_data + "\n");
- }
- else
- {
- Send("Name: " + name + "\n");
- }
- }
- }
- else
+ if (Utility::isipv6( m_data ))
+ {
+ struct sockaddr_in6 sa;
+ if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST))
+ {
+ Send("Failed: convert to sockaddr_in6 failed\n");
+ }
+ else
+ {
+ std::string name;
+ if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name))
+ {
+ Send("Failed: ipv6 reverse lookup of " + m_data + "\n");
+ }
+ else
+ {
+ Send("Name: " + name + "\n");
+ }
+ }
+ }
+ else
#endif
#endif
- {
- Send("Failed: malformed address\n");
- }
- Send("\n");
- }
- else
- {
- std::string msg = "Unknown query type: " + m_query;
- Handler().LogError(this, "OnDetached", 0, msg);
- Send("Unknown\n\n");
- }
- SetCloseAndDelete();
+ {
+ Send("Failed: malformed address\n");
+ }
+ Send("\n");
+ }
+ else
+ {
+ std::string msg = "Unknown query type: " + m_query;
+ Handler().LogError(this, "OnDetached", 0, msg);
+ Send("Unknown\n\n");
+ }
+ SetCloseAndDelete();
}
void ResolvSocket::OnConnect()
{
- if (!m_resolv_host.empty())
- {
+ if (!m_resolv_host.empty())
+ {
#ifdef ENABLE_IPV6
- std::string msg = (m_resolve_ipv6 ? "gethostbyname2 " : "gethostbyname ") + m_resolv_host + "\n";
- m_query = m_resolve_ipv6 ? "gethostbyname2" : "gethostbyname";
+ std::string msg = (m_resolve_ipv6 ? "gethostbyname2 " : "gethostbyname ") + m_resolv_host + "\n";
+ m_query = m_resolve_ipv6 ? "gethostbyname2" : "gethostbyname";
#else
- std::string msg = "gethostbyname " + m_resolv_host + "\n";
- m_query = "gethostbyname";
+ std::string msg = "gethostbyname " + m_resolv_host + "\n";
+ m_query = "gethostbyname";
#endif
- m_data = m_resolv_host;
- Send( msg );
- return;
- }
+ m_data = m_resolv_host;
+ Send( msg );
+ return;
+ }
#ifdef ENABLE_IPV6
- if (m_resolve_ipv6)
- {
- std::string tmp;
- Utility::l2ip(m_resolv_address6, tmp);
- m_query = "gethostbyaddr";
- m_data = tmp;
- std::string msg = "gethostbyaddr " + tmp + "\n";
- Send( msg );
- }
+ if (m_resolve_ipv6)
+ {
+ std::string tmp;
+ Utility::l2ip(m_resolv_address6, tmp);
+ m_query = "gethostbyaddr";
+ m_data = tmp;
+ std::string msg = "gethostbyaddr " + tmp + "\n";
+ Send( msg );
+ }
#endif
- std::string tmp;
- Utility::l2ip(m_resolv_address, tmp);
- m_query = "gethostbyaddr";
- m_data = tmp;
- std::string msg = "gethostbyaddr " + tmp + "\n";
- Send( msg );
+ std::string tmp;
+ Utility::l2ip(m_resolv_address, tmp);
+ m_query = "gethostbyaddr";
+ m_data = tmp;
+ std::string msg = "gethostbyaddr " + tmp + "\n";
+ Send( msg );
}
void ResolvSocket::OnDelete()
{
- if (m_parent)
- {
- if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
- {
- m_parent -> OnResolveFailed(m_resolv_id);
- }
- // update cache
- if (!m_cached)
- {
- Lock lock(m_cache_mutex);
- std::string value;
+ if (m_parent)
+ {
+ if (Handler().Resolving(m_parent) || Handler().Valid(m_parent))
+ {
+ m_parent -> OnResolveFailed(m_resolv_id);
+ }
+ // update cache
+ if (!m_cached)
+ {
+ Lock lock(m_cache_mutex);
+ std::string value;
DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());)
- m_cache[m_query][m_data] = value;
- m_cache_to[m_query][m_data] = time(NULL);
- }
- m_parent = NULL;
- }
+ m_cache[m_query][m_data] = value;
+ m_cache_to[m_query][m_data] = time(NULL);
+ }
+ m_parent = NULL;
+ }
}
diff --git a/dep/src/sockets/Socket.cpp b/dep/src/sockets/Socket.cpp
index 883363eb1dd..5e739ec0c71 100644
--- a/dep/src/sockets/Socket.cpp
+++ b/dep/src/sockets/Socket.cpp
@@ -1,6 +1,6 @@
/** \file Socket.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -114,15 +114,15 @@ Socket::Socket(ISocketHandler& h)
Socket::~Socket()
{
- Handler().Remove(this);
- if (m_socket != INVALID_SOCKET
+ Handler().Remove(this);
+ if (m_socket != INVALID_SOCKET
#ifdef ENABLE_POOL
- && !m_bRetain
+ && !m_bRetain
#endif
- )
- {
- Close();
- }
+ )
+ {
+ Close();
+ }
}
@@ -143,11 +143,11 @@ void Socket::OnWrite()
void Socket::OnException()
{
- // %! exception doesn't always mean something bad happened, this code should be reworked
- // errno valid here?
- int err = SoError();
- Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ // %! exception doesn't always mean something bad happened, this code should be reworked
+ // errno valid here?
+ int err = SoError();
+ Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
}
@@ -168,159 +168,159 @@ void Socket::OnAccept()
int Socket::Close()
{
- if (m_socket == INVALID_SOCKET) // this could happen
- {
- Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING);
- return 0;
- }
- int n;
- if ((n = closesocket(m_socket)) == -1)
- {
- // failed...
- Handler().LogError(this, "close", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- Handler().Set(m_socket, false, false, false); // remove from fd_set's
- Handler().AddList(m_socket, LIST_CALLONCONNECT, false);
+ if (m_socket == INVALID_SOCKET) // this could happen
+ {
+ Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING);
+ return 0;
+ }
+ int n;
+ if ((n = closesocket(m_socket)) == -1)
+ {
+ // failed...
+ Handler().LogError(this, "close", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ Handler().Set(m_socket, false, false, false); // remove from fd_set's
+ Handler().AddList(m_socket, LIST_CALLONCONNECT, false);
#ifdef ENABLE_DETACH
- Handler().AddList(m_socket, LIST_DETACH, false);
+ Handler().AddList(m_socket, LIST_DETACH, false);
#endif
- Handler().AddList(m_socket, LIST_TIMEOUT, false);
- Handler().AddList(m_socket, LIST_RETRY, false);
- Handler().AddList(m_socket, LIST_CLOSE, false);
- m_socket = INVALID_SOCKET;
- return n;
+ Handler().AddList(m_socket, LIST_TIMEOUT, false);
+ Handler().AddList(m_socket, LIST_RETRY, false);
+ Handler().AddList(m_socket, LIST_CLOSE, false);
+ m_socket = INVALID_SOCKET;
+ return n;
}
SOCKET Socket::CreateSocket(int af,int type, const std::string& protocol)
{
- struct protoent *p = NULL;
- SOCKET s;
+ struct protoent *p = NULL;
+ SOCKET s;
#ifdef ENABLE_POOL
- m_socket_type = type;
- m_socket_protocol = protocol;
-#endif
- if (!protocol.empty())
- {
- p = getprotobyname( protocol.c_str() );
- if (!p)
- {
- Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ m_socket_type = type;
+ m_socket_protocol = protocol;
+#endif
+ if (!protocol.empty())
+ {
+ p = getprotobyname( protocol.c_str() );
+ if (!p)
+ {
+ Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
- throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno));
-#endif
- return INVALID_SOCKET;
- }
- }
- int protno = p ? p -> p_proto : 0;
-
- s = socket(af, type, protno);
- if (s == INVALID_SOCKET)
- {
- Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno));
+#endif
+ return INVALID_SOCKET;
+ }
+ }
+ int protno = p ? p -> p_proto : 0;
+
+ s = socket(af, type, protno);
+ if (s == INVALID_SOCKET)
+ {
+ Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
- throw Exception(std::string("socket() failed: ") + StrError(Errno));
+ throw Exception(std::string("socket() failed: ") + StrError(Errno));
#endif
- return INVALID_SOCKET;
- }
- Attach(s);
- OnOptions(af, type, protno, s);
- Attach(INVALID_SOCKET);
- return s;
+ return INVALID_SOCKET;
+ }
+ Attach(s);
+ OnOptions(af, type, protno, s);
+ Attach(INVALID_SOCKET);
+ return s;
}
void Socket::Attach(SOCKET s)
{
- m_socket = s;
+ m_socket = s;
}
SOCKET Socket::GetSocket()
{
- return m_socket;
+ return m_socket;
}
void Socket::SetDeleteByHandler(bool x)
{
- m_bDel = x;
+ m_bDel = x;
}
bool Socket::DeleteByHandler()
{
- return m_bDel;
+ return m_bDel;
}
void Socket::SetCloseAndDelete(bool x)
{
- if (x != m_bClose)
- {
- Handler().AddList(m_socket, LIST_CLOSE, x);
- m_bClose = x;
- if (x)
- {
- m_tClose = time(NULL);
- }
- }
+ if (x != m_bClose)
+ {
+ Handler().AddList(m_socket, LIST_CLOSE, x);
+ m_bClose = x;
+ if (x)
+ {
+ m_tClose = time(NULL);
+ }
+ }
}
bool Socket::CloseAndDelete()
{
- return m_bClose;
+ return m_bClose;
}
void Socket::SetRemoteAddress(SocketAddress& ad) //struct sockaddr* sa, socklen_t l)
{
- m_remote_address = ad.GetCopy();
+ m_remote_address = ad.GetCopy();
}
std::auto_ptr<SocketAddress> Socket::GetRemoteSocketAddress()
{
- return m_remote_address -> GetCopy();
+ return m_remote_address -> GetCopy();
}
ISocketHandler& Socket::Handler() const
{
#ifdef ENABLE_DETACH
- if (IsDetached())
- return *m_slave_handler;
+ if (IsDetached())
+ return *m_slave_handler;
#endif
- return m_handler;
+ return m_handler;
}
ISocketHandler& Socket::MasterHandler() const
{
- return m_handler;
+ return m_handler;
}
ipaddr_t Socket::GetRemoteIP4()
{
- ipaddr_t l = 0;
+ ipaddr_t l = 0;
#ifdef ENABLE_IPV6
- if (m_ipv6)
- {
- Handler().LogError(this, "GetRemoteIP4", 0, "get ipv4 address for ipv6 socket", LOG_LEVEL_WARNING);
- }
+ if (m_ipv6)
+ {
+ Handler().LogError(this, "GetRemoteIP4", 0, "get ipv4 address for ipv6 socket", LOG_LEVEL_WARNING);
+ }
#endif
- if (m_remote_address.get() != NULL)
- {
- struct sockaddr *p = *m_remote_address;
- struct sockaddr_in *sa = (struct sockaddr_in *)p;
- memcpy(&l, &sa -> sin_addr, sizeof(struct in_addr));
- }
- return l;
+ if (m_remote_address.get() != NULL)
+ {
+ struct sockaddr *p = *m_remote_address;
+ struct sockaddr_in *sa = (struct sockaddr_in *)p;
+ memcpy(&l, &sa -> sin_addr, sizeof(struct in_addr));
+ }
+ return l;
}
@@ -328,21 +328,21 @@ ipaddr_t Socket::GetRemoteIP4()
#ifdef IPPROTO_IPV6
struct in6_addr Socket::GetRemoteIP6()
{
- if (!m_ipv6)
- {
- Handler().LogError(this, "GetRemoteIP6", 0, "get ipv6 address for ipv4 socket", LOG_LEVEL_WARNING);
- }
- struct sockaddr_in6 fail;
- if (m_remote_address.get() != NULL)
- {
- struct sockaddr *p = *m_remote_address;
- memcpy(&fail, p, sizeof(struct sockaddr_in6));
- }
- else
- {
- memset(&fail, 0, sizeof(struct sockaddr_in6));
- }
- return fail.sin6_addr;
+ if (!m_ipv6)
+ {
+ Handler().LogError(this, "GetRemoteIP6", 0, "get ipv6 address for ipv4 socket", LOG_LEVEL_WARNING);
+ }
+ struct sockaddr_in6 fail;
+ if (m_remote_address.get() != NULL)
+ {
+ struct sockaddr *p = *m_remote_address;
+ memcpy(&fail, p, sizeof(struct sockaddr_in6));
+ }
+ else
+ {
+ memset(&fail, 0, sizeof(struct sockaddr_in6));
+ }
+ return fail.sin6_addr;
}
#endif
#endif
@@ -350,63 +350,63 @@ struct in6_addr Socket::GetRemoteIP6()
port_t Socket::GetRemotePort()
{
- if (!m_remote_address.get())
- {
- return 0;
- }
- return m_remote_address -> GetPort();
+ if (!m_remote_address.get())
+ {
+ return 0;
+ }
+ return m_remote_address -> GetPort();
}
std::string Socket::GetRemoteAddress()
{
- if (!m_remote_address.get())
- {
- return "";
- }
- return m_remote_address -> Convert(false);
+ if (!m_remote_address.get())
+ {
+ return "";
+ }
+ return m_remote_address -> Convert(false);
}
std::string Socket::GetRemoteHostname()
{
- if (!m_remote_address.get())
- {
- return "";
- }
- return m_remote_address -> Reverse();
+ if (!m_remote_address.get())
+ {
+ return "";
+ }
+ return m_remote_address -> Reverse();
}
bool Socket::SetNonblocking(bool bNb)
{
#ifdef _WIN32
- unsigned long l = bNb ? 1 : 0;
- int n = ioctlsocket(m_socket, FIONBIO, &l);
- if (n != 0)
- {
- Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, "");
- return false;
- }
- return true;
+ unsigned long l = bNb ? 1 : 0;
+ int n = ioctlsocket(m_socket, FIONBIO, &l);
+ if (n != 0)
+ {
+ Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, "");
+ return false;
+ }
+ return true;
#else
- if (bNb)
- {
- if (fcntl(m_socket, F_SETFL, O_NONBLOCK) == -1)
- {
- Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- return false;
- }
- }
- else
- {
- if (fcntl(m_socket, F_SETFL, 0) == -1)
- {
- Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- return false;
- }
- }
- return true;
+ if (bNb)
+ {
+ if (fcntl(m_socket, F_SETFL, O_NONBLOCK) == -1)
+ {
+ Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ return false;
+ }
+ }
+ else
+ {
+ if (fcntl(m_socket, F_SETFL, 0) == -1)
+ {
+ Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ return false;
+ }
+ }
+ return true;
#endif
}
@@ -414,47 +414,47 @@ bool Socket::SetNonblocking(bool bNb)
bool Socket::SetNonblocking(bool bNb, SOCKET s)
{
#ifdef _WIN32
- unsigned long l = bNb ? 1 : 0;
- int n = ioctlsocket(s, FIONBIO, &l);
- if (n != 0)
- {
- Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, "");
- return false;
- }
- return true;
+ unsigned long l = bNb ? 1 : 0;
+ int n = ioctlsocket(s, FIONBIO, &l);
+ if (n != 0)
+ {
+ Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, "");
+ return false;
+ }
+ return true;
#else
- if (bNb)
- {
- if (fcntl(s, F_SETFL, O_NONBLOCK) == -1)
- {
- Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- return false;
- }
- }
- else
- {
- if (fcntl(s, F_SETFL, 0) == -1)
- {
- Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- return false;
- }
- }
- return true;
+ if (bNb)
+ {
+ if (fcntl(s, F_SETFL, O_NONBLOCK) == -1)
+ {
+ Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ return false;
+ }
+ }
+ else
+ {
+ if (fcntl(s, F_SETFL, 0) == -1)
+ {
+ Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ return false;
+ }
+ }
+ return true;
#endif
}
void Socket::Set(bool bRead, bool bWrite, bool bException)
{
- Handler().Set(m_socket, bRead, bWrite, bException);
+ Handler().Set(m_socket, bRead, bWrite, bException);
}
bool Socket::Ready()
{
- if (m_socket != INVALID_SOCKET && !CloseAndDelete())
- return true;
- return false;
+ if (m_socket != INVALID_SOCKET && !CloseAndDelete())
+ return true;
+ return false;
}
@@ -470,26 +470,26 @@ void Socket::OnConnectFailed()
Socket *Socket::GetParent()
{
- return m_parent;
+ return m_parent;
}
void Socket::SetParent(Socket *x)
{
- m_parent = x;
+ m_parent = x;
}
port_t Socket::GetPort()
{
- Handler().LogError(this, "GetPort", 0, "GetPort only implemented for ListenSocket", LOG_LEVEL_WARNING);
- return 0;
+ Handler().LogError(this, "GetPort", 0, "GetPort only implemented for ListenSocket", LOG_LEVEL_WARNING);
+ return 0;
}
bool Socket::OnConnectRetry()
{
- return true;
+ return true;
}
@@ -502,33 +502,33 @@ void Socket::OnReconnect()
time_t Socket::Uptime()
{
- return time(NULL) - m_tCreate;
+ return time(NULL) - m_tCreate;
}
#ifdef ENABLE_IPV6
void Socket::SetIpv6(bool x)
{
- m_ipv6 = x;
+ m_ipv6 = x;
}
bool Socket::IsIpv6()
{
- return m_ipv6;
+ return m_ipv6;
}
#endif
void Socket::DisableRead(bool x)
{
- m_b_disable_read = x;
+ m_b_disable_read = x;
}
bool Socket::IsDisableRead()
{
- return m_b_disable_read;
+ return m_b_disable_read;
}
@@ -544,13 +544,13 @@ void Socket::Send(const std::string&,int)
void Socket::SetConnected(bool x)
{
- m_connected = x;
+ m_connected = x;
}
bool Socket::IsConnected()
{
- return m_connected;
+ return m_connected;
}
@@ -561,63 +561,63 @@ void Socket::OnDisconnect()
void Socket::SetLost()
{
- m_bLost = true;
+ m_bLost = true;
}
bool Socket::Lost()
{
- return m_bLost;
+ return m_bLost;
}
void Socket::SetErasedByHandler(bool x)
{
- m_b_erased_by_handler = x;
+ m_b_erased_by_handler = x;
}
bool Socket::ErasedByHandler()
{
- return m_b_erased_by_handler;
+ return m_b_erased_by_handler;
}
time_t Socket::TimeSinceClose()
{
- return time(NULL) - m_tClose;
+ return time(NULL) - m_tClose;
}
void Socket::SetClientRemoteAddress(SocketAddress& ad)
{
- if (!ad.IsValid())
- {
- Handler().LogError(this, "SetClientRemoteAddress", 0, "remote address not valid", LOG_LEVEL_ERROR);
- }
- m_client_remote_address = ad.GetCopy();
+ if (!ad.IsValid())
+ {
+ Handler().LogError(this, "SetClientRemoteAddress", 0, "remote address not valid", LOG_LEVEL_ERROR);
+ }
+ m_client_remote_address = ad.GetCopy();
}
std::auto_ptr<SocketAddress> Socket::GetClientRemoteAddress()
{
- if (!m_client_remote_address.get())
- {
- Handler().LogError(this, "GetClientRemoteAddress", 0, "remote address not yet set", LOG_LEVEL_ERROR);
- }
- return m_client_remote_address -> GetCopy();
+ if (!m_client_remote_address.get())
+ {
+ Handler().LogError(this, "GetClientRemoteAddress", 0, "remote address not yet set", LOG_LEVEL_ERROR);
+ }
+ return m_client_remote_address -> GetCopy();
}
uint64_t Socket::GetBytesSent(bool)
{
- return 0;
+ return 0;
}
uint64_t Socket::GetBytesReceived(bool)
{
- return 0;
+ return 0;
}
@@ -634,43 +634,43 @@ void Socket::OnSSLAccept()
bool Socket::SSLNegotiate()
{
- return false;
+ return false;
}
bool Socket::IsSSL()
{
- return m_b_enable_ssl;
+ return m_b_enable_ssl;
}
void Socket::EnableSSL(bool x)
{
- m_b_enable_ssl = x;
+ m_b_enable_ssl = x;
}
bool Socket::IsSSLNegotiate()
{
- return m_b_ssl;
+ return m_b_ssl;
}
void Socket::SetSSLNegotiate(bool x)
{
- m_b_ssl = x;
+ m_b_ssl = x;
}
bool Socket::IsSSLServer()
{
- return m_b_ssl_server;
+ return m_b_ssl_server;
}
void Socket::SetSSLServer(bool x)
{
- m_b_ssl_server = x;
+ m_b_ssl_server = x;
}
@@ -688,57 +688,57 @@ void Socket::OnSSLAcceptFailed()
#ifdef ENABLE_POOL
void Socket::CopyConnection(Socket *sock)
{
- Attach( sock -> GetSocket() );
+ Attach( sock -> GetSocket() );
#ifdef ENABLE_IPV6
- SetIpv6( sock -> IsIpv6() );
+ SetIpv6( sock -> IsIpv6() );
#endif
- SetSocketType( sock -> GetSocketType() );
- SetSocketProtocol( sock -> GetSocketProtocol() );
+ SetSocketType( sock -> GetSocketType() );
+ SetSocketProtocol( sock -> GetSocketProtocol() );
- SetClientRemoteAddress( *sock -> GetClientRemoteAddress() );
- SetRemoteAddress( *sock -> GetRemoteSocketAddress() );
+ SetClientRemoteAddress( *sock -> GetClientRemoteAddress() );
+ SetRemoteAddress( *sock -> GetRemoteSocketAddress() );
}
void Socket::SetIsClient()
{
- m_bClient = true;
+ m_bClient = true;
}
void Socket::SetSocketType(int x)
{
- m_socket_type = x;
+ m_socket_type = x;
}
int Socket::GetSocketType()
{
- return m_socket_type;
+ return m_socket_type;
}
void Socket::SetSocketProtocol(const std::string& x)
{
- m_socket_protocol = x;
+ m_socket_protocol = x;
}
const std::string& Socket::GetSocketProtocol()
{
- return m_socket_protocol;
+ return m_socket_protocol;
}
void Socket::SetRetain()
{
- if (m_bClient) m_bRetain = true;
+ if (m_bClient) m_bRetain = true;
}
bool Socket::Retain()
{
- return m_bRetain;
+ return m_bRetain;
}
@@ -748,74 +748,74 @@ bool Socket::Retain()
#ifdef ENABLE_SOCKS4
void Socket::OnSocks4Connect()
{
- Handler().LogError(this, "OnSocks4Connect", 0, "Use with TcpSocket only");
+ Handler().LogError(this, "OnSocks4Connect", 0, "Use with TcpSocket only");
}
void Socket::OnSocks4ConnectFailed()
{
- Handler().LogError(this, "OnSocks4ConnectFailed", 0, "Use with TcpSocket only");
+ Handler().LogError(this, "OnSocks4ConnectFailed", 0, "Use with TcpSocket only");
}
bool Socket::OnSocks4Read()
{
- Handler().LogError(this, "OnSocks4Read", 0, "Use with TcpSocket only");
- return true;
+ Handler().LogError(this, "OnSocks4Read", 0, "Use with TcpSocket only");
+ return true;
}
void Socket::SetSocks4Host(const std::string& host)
{
- Utility::u2ip(host, m_socks4_host);
+ Utility::u2ip(host, m_socks4_host);
}
bool Socket::Socks4()
{
- return m_bSocks4;
+ return m_bSocks4;
}
void Socket::SetSocks4(bool x)
{
- m_bSocks4 = x;
+ m_bSocks4 = x;
}
void Socket::SetSocks4Host(ipaddr_t a)
{
- m_socks4_host = a;
+ m_socks4_host = a;
}
void Socket::SetSocks4Port(port_t p)
{
- m_socks4_port = p;
+ m_socks4_port = p;
}
void Socket::SetSocks4Userid(const std::string& x)
{
- m_socks4_userid = x;
+ m_socks4_userid = x;
}
ipaddr_t Socket::GetSocks4Host()
{
- return m_socks4_host;
+ return m_socks4_host;
}
port_t Socket::GetSocks4Port()
{
- return m_socks4_port;
+ return m_socks4_port;
}
const std::string& Socket::GetSocks4Userid()
{
- return m_socks4_userid;
+ return m_socks4_userid;
}
#endif // ENABLE_SOCKS4
@@ -823,22 +823,22 @@ const std::string& Socket::GetSocks4Userid()
#ifdef ENABLE_DETACH
bool Socket::Detach()
{
- if (!DeleteByHandler())
- return false;
- if (m_pThread)
- return false;
- if (m_detached)
- return false;
- SetDetach();
- return true;
+ if (!DeleteByHandler())
+ return false;
+ if (m_pThread)
+ return false;
+ if (m_detached)
+ return false;
+ SetDetach();
+ return true;
}
void Socket::DetachSocket()
{
- SetDetached();
- m_pThread = new SocketThread(this);
- m_pThread -> SetRelease(true);
+ SetDetached();
+ m_pThread = new SocketThread(this);
+ m_pThread -> SetRelease(true);
}
@@ -849,32 +849,32 @@ void Socket::OnDetached()
void Socket::SetDetach(bool x)
{
- Handler().AddList(m_socket, LIST_DETACH, x);
- m_detach = x;
+ Handler().AddList(m_socket, LIST_DETACH, x);
+ m_detach = x;
}
bool Socket::IsDetach()
{
- return m_detach;
+ return m_detach;
}
void Socket::SetDetached(bool x)
{
- m_detached = x;
+ m_detached = x;
}
const bool Socket::IsDetached() const
{
- return m_detached;
+ return m_detached;
}
void Socket::SetSlaveHandler(ISocketHandler *p)
{
- m_slave_handler = p;
+ m_slave_handler = p;
}
@@ -882,40 +882,40 @@ Socket::SocketThread::SocketThread(Socket *p)
:Thread(false)
,m_socket(p)
{
- // Creator will release
+ // Creator will release
}
Socket::SocketThread::~SocketThread()
{
- if (IsRunning())
- {
- SetRelease(true);
- SetRunning(false);
+ if (IsRunning())
+ {
+ SetRelease(true);
+ SetRunning(false);
#ifdef _WIN32
- Sleep(1000);
+ Sleep(1000);
#else
- sleep(1);
+ sleep(1);
#endif
- }
+ }
}
void Socket::SocketThread::Run()
{
- SocketHandler h;
- h.SetSlave();
- h.Add(m_socket);
- m_socket -> SetSlaveHandler(&h);
- m_socket -> OnDetached();
- while (h.GetCount() && IsRunning())
- {
- h.Select(0, 500000);
- }
- // m_socket now deleted oops
- // yeah oops m_socket delete its socket thread, that means this
- // so Socket will no longer delete its socket thread, instead we do this:
- SetDeleteOnExit();
+ SocketHandler h;
+ h.SetSlave();
+ h.Add(m_socket);
+ m_socket -> SetSlaveHandler(&h);
+ m_socket -> OnDetached();
+ while (h.GetCount() && IsRunning())
+ {
+ h.Select(0, 500000);
+ }
+ // m_socket now deleted oops
+ // yeah oops m_socket delete its socket thread, that means this
+ // so Socket will no longer delete its socket thread, instead we do this:
+ SetDeleteOnExit();
}
#endif // ENABLE_DETACH
@@ -923,28 +923,28 @@ void Socket::SocketThread::Run()
#ifdef ENABLE_RESOLVER
int Socket::Resolve(const std::string& host,port_t port)
{
- return Handler().Resolve(this, host, port);
+ return Handler().Resolve(this, host, port);
}
#ifdef ENABLE_IPV6
int Socket::Resolve6(const std::string& host,port_t port)
{
- return Handler().Resolve6(this, host, port);
+ return Handler().Resolve6(this, host, port);
}
#endif
int Socket::Resolve(ipaddr_t a)
{
- return Handler().Resolve(this, a);
+ return Handler().Resolve(this, a);
}
#ifdef ENABLE_IPV6
int Socket::Resolve(in6_addr& a)
{
- return Handler().Resolve(this, a);
+ return Handler().Resolve(this, a);
}
#endif
@@ -978,15 +978,15 @@ void Socket::OnResolveFailed(int)
bool Socket::SetIpOptions(const void *p, socklen_t len)
{
#ifdef IP_OPTIONS
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_OPTIONS, (char *)p, len) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_OPTIONS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_OPTIONS, (char *)p, len) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_OPTIONS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_OPTIONS", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_OPTIONS", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -994,13 +994,13 @@ bool Socket::SetIpOptions(const void *p, socklen_t len)
#ifdef IP_PKTINFO
bool Socket::SetIpPktinfo(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_PKTINFO, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_PKTINFO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_PKTINFO, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_PKTINFO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1008,13 +1008,13 @@ bool Socket::SetIpPktinfo(bool x)
#ifdef IP_RECVTOS
bool Socket::SetIpRecvTOS(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTOS, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTOS, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1022,13 +1022,13 @@ bool Socket::SetIpRecvTOS(bool x)
#ifdef IP_RECVTTL
bool Socket::SetIpRecvTTL(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTTL, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTTL, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1036,13 +1036,13 @@ bool Socket::SetIpRecvTTL(bool x)
#ifdef IP_RECVOPTS
bool Socket::SetIpRecvopts(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVOPTS, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVOPTS, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1050,13 +1050,13 @@ bool Socket::SetIpRecvopts(bool x)
#ifdef IP_RETOPTS
bool Socket::SetIpRetopts(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_RETOPTS, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RETOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_RETOPTS, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RETOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1064,80 +1064,80 @@ bool Socket::SetIpRetopts(bool x)
bool Socket::SetIpTOS(unsigned char tos)
{
#ifdef IP_TOS
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(tos)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(tos)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO);
+ return false;
#endif
}
unsigned char Socket::IpTOS()
{
- unsigned char tos = 0;
+ unsigned char tos = 0;
#ifdef IP_TOS
- socklen_t len = sizeof(tos);
- if (getsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(tos);
+ if (getsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO);
+ Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO);
#endif
- return tos;
+ return tos;
}
bool Socket::SetIpTTL(int ttl)
{
#ifdef IP_TTL
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(ttl)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(ttl)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO);
+ return false;
#endif
}
int Socket::IpTTL()
{
- int ttl = 0;
+ int ttl = 0;
#ifdef IP_TTL
- socklen_t len = sizeof(ttl);
- if (getsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(ttl);
+ if (getsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO);
+ Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO);
#endif
- return ttl;
+ return ttl;
}
bool Socket::SetIpHdrincl(bool x)
{
#ifdef IP_HDRINCL
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_HDRINCL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_HDRINCL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_HDRINCL", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_HDRINCL", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1145,13 +1145,13 @@ bool Socket::SetIpHdrincl(bool x)
#ifdef IP_RECVERR
bool Socket::SetIpRecverr(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVERR, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVERR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVERR, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVERR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1159,13 +1159,13 @@ bool Socket::SetIpRecverr(bool x)
#ifdef IP_MTU_DISCOVER
bool Socket::SetIpMtudiscover(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_MTU_DISCOVER, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MTU_DISCOVER)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_MTU_DISCOVER, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MTU_DISCOVER)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1173,13 +1173,13 @@ bool Socket::SetIpMtudiscover(bool x)
#ifdef IP_MTU
int Socket::IpMtu()
{
- int mtu = 0;
- socklen_t len = sizeof(mtu);
- if (getsockopt(GetSocket(), IPPROTO_IP, IP_MTU, (char *)&mtu, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MTU)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
- return mtu;
+ int mtu = 0;
+ socklen_t len = sizeof(mtu);
+ if (getsockopt(GetSocket(), IPPROTO_IP, IP_MTU, (char *)&mtu, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MTU)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
+ return mtu;
}
#endif
@@ -1187,13 +1187,13 @@ int Socket::IpMtu()
#ifdef IP_ROUTER_ALERT
bool Socket::SetIpRouterAlert(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_ROUTER_ALERT, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ROUTER_ALERT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_ROUTER_ALERT, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ROUTER_ALERT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1201,48 +1201,48 @@ bool Socket::SetIpRouterAlert(bool x)
bool Socket::SetIpMulticastTTL(int ttl)
{
#ifdef IP_MULTICAST_TTL
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO);
+ return false;
#endif
}
int Socket::IpMulticastTTL()
{
- int ttl = 0;
+ int ttl = 0;
#ifdef IP_MULTICAST_TTL
- socklen_t len = sizeof(ttl);
- if (getsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(ttl);
+ if (getsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO);
+ Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO);
#endif
- return ttl;
+ return ttl;
}
bool Socket::SetMulticastLoop(bool x)
{
#ifdef IP_MULTICAST_LOOP
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_LOOP", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_LOOP", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1251,15 +1251,15 @@ bool Socket::SetMulticastLoop(bool x)
bool Socket::IpAddMembership(struct ip_mreqn& ref)
{
#ifdef IP_ADD_MEMBERSHIP
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO);
+ return false;
#endif
}
#endif
@@ -1268,15 +1268,15 @@ bool Socket::IpAddMembership(struct ip_mreqn& ref)
bool Socket::IpAddMembership(struct ip_mreq& ref)
{
#ifdef IP_ADD_MEMBERSHIP
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1285,15 +1285,15 @@ bool Socket::IpAddMembership(struct ip_mreq& ref)
bool Socket::IpDropMembership(struct ip_mreqn& ref)
{
#ifdef IP_DROP_MEMBERSHIP
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO);
+ return false;
#endif
}
#endif
@@ -1302,15 +1302,15 @@ bool Socket::IpDropMembership(struct ip_mreqn& ref)
bool Socket::IpDropMembership(struct ip_mreq& ref)
{
#ifdef IP_DROP_MEMBERSHIP
- if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1321,16 +1321,16 @@ bool Socket::IpDropMembership(struct ip_mreq& ref)
bool Socket::SetSoReuseaddr(bool x)
{
#ifdef SO_REUSEADDR
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_REUSEADDR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_REUSEADDR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_REUSEADDR", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_REUSEADDR", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1338,16 +1338,16 @@ bool Socket::SetSoReuseaddr(bool x)
bool Socket::SetSoKeepalive(bool x)
{
#ifdef SO_KEEPALIVE
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_KEEPALIVE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_KEEPALIVE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_KEEPALIVE", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_KEEPALIVE", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1355,43 +1355,43 @@ bool Socket::SetSoKeepalive(bool x)
#ifdef SO_NOSIGPIPE
bool Socket::SetSoNosigpipe(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_NOSIGPIPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_NOSIGPIPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
bool Socket::SoAcceptconn()
{
- int value = 0;
+ int value = 0;
#ifdef SO_ACCEPTCONN
- socklen_t len = sizeof(value);
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_ACCEPTCONN, (char *)&value, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ACCEPTCONN)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(value);
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_ACCEPTCONN, (char *)&value, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ACCEPTCONN)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "socket option not available", 0, "SO_ACCEPTCONN", LOG_LEVEL_INFO);
+ Handler().LogError(this, "socket option not available", 0, "SO_ACCEPTCONN", LOG_LEVEL_INFO);
#endif
- return value ? true : false;
+ return value ? true : false;
}
#ifdef SO_BSDCOMPAT
bool Socket::SetSoBsdcompat(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_BSDCOMPAT, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BSDCOMPAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_BSDCOMPAT, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BSDCOMPAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1399,12 +1399,12 @@ bool Socket::SetSoBsdcompat(bool x)
#ifdef SO_BINDTODEVICE
bool Socket::SetSoBindtodevice(const std::string& intf)
{
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_BINDTODEVICE, (char *)intf.c_str(), intf.size()) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BINDTODEVICE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_BINDTODEVICE, (char *)intf.c_str(), intf.size()) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BINDTODEVICE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1412,16 +1412,16 @@ bool Socket::SetSoBindtodevice(const std::string& intf)
bool Socket::SetSoBroadcast(bool x)
{
#ifdef SO_BROADCAST
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BROADCAST)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BROADCAST)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_BROADCAST", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_BROADCAST", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1429,49 +1429,49 @@ bool Socket::SetSoBroadcast(bool x)
bool Socket::SetSoDebug(bool x)
{
#ifdef SO_DEBUG
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_DEBUG, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DEBUG)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_DEBUG, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DEBUG)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_DEBUG", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_DEBUG", LOG_LEVEL_INFO);
+ return false;
#endif
}
int Socket::SoError()
{
- int value = 0;
+ int value = 0;
#ifdef SO_ERROR
- socklen_t len = sizeof(value);
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_ERROR, (char *)&value, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ERROR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(value);
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_ERROR, (char *)&value, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ERROR)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "socket option not available", 0, "SO_ERROR", LOG_LEVEL_INFO);
+ Handler().LogError(this, "socket option not available", 0, "SO_ERROR", LOG_LEVEL_INFO);
#endif
- return value;
+ return value;
}
bool Socket::SetSoDontroute(bool x)
{
#ifdef SO_DONTROUTE
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_DONTROUTE, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DONTROUTE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_DONTROUTE, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DONTROUTE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_DONTROUTE", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_DONTROUTE", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1479,18 +1479,18 @@ bool Socket::SetSoDontroute(bool x)
bool Socket::SetSoLinger(int onoff, int linger)
{
#ifdef SO_LINGER
- struct linger stl;
- stl.l_onoff = onoff;
- stl.l_linger = linger;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_LINGER, (char *)&stl, sizeof(stl)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_LINGER)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ struct linger stl;
+ stl.l_onoff = onoff;
+ stl.l_linger = linger;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_LINGER, (char *)&stl, sizeof(stl)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_LINGER)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_LINGER", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_LINGER", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1498,16 +1498,16 @@ bool Socket::SetSoLinger(int onoff, int linger)
bool Socket::SetSoOobinline(bool x)
{
#ifdef SO_OOBINLINE
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_OOBINLINE, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_OOBINLINE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_OOBINLINE, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_OOBINLINE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_OOBINLINE", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_OOBINLINE", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1515,13 +1515,13 @@ bool Socket::SetSoOobinline(bool x)
#ifdef SO_PASSCRED
bool Socket::SetSoPasscred(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_PASSCRED, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PASSCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_PASSCRED, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PASSCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1529,12 +1529,12 @@ bool Socket::SetSoPasscred(bool x)
#ifdef SO_PEERCRED
bool Socket::SoPeercred(struct ucred& ucr)
{
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_PEERCRED, (char *)&ucr, sizeof(ucr)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PEERCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_PEERCRED, (char *)&ucr, sizeof(ucr)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PEERCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1542,12 +1542,12 @@ bool Socket::SoPeercred(struct ucred& ucr)
#ifdef SO_PRIORITY
bool Socket::SetSoPriority(int x)
{
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_PRIORITY, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PRIORITY)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_PRIORITY, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PRIORITY)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1555,15 +1555,15 @@ bool Socket::SetSoPriority(int x)
bool Socket::SetSoRcvlowat(int x)
{
#ifdef SO_RCVLOWAT
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVLOWAT, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVLOWAT, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_RCVLOWAT", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_RCVLOWAT", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1571,15 +1571,15 @@ bool Socket::SetSoRcvlowat(int x)
bool Socket::SetSoSndlowat(int x)
{
#ifdef SO_SNDLOWAT
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDLOWAT, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDLOWAT, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_SNDLOWAT", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_SNDLOWAT", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1587,15 +1587,15 @@ bool Socket::SetSoSndlowat(int x)
bool Socket::SetSoRcvtimeo(struct timeval& tv)
{
#ifdef SO_RCVTIMEO
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_RCVTIMEO", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_RCVTIMEO", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1603,15 +1603,15 @@ bool Socket::SetSoRcvtimeo(struct timeval& tv)
bool Socket::SetSoSndtimeo(struct timeval& tv)
{
#ifdef SO_SNDTIMEO
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_SNDTIMEO", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_SNDTIMEO", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1619,44 +1619,44 @@ bool Socket::SetSoSndtimeo(struct timeval& tv)
bool Socket::SetSoRcvbuf(int x)
{
#ifdef SO_RCVBUF
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO);
+ return false;
#endif
}
int Socket::SoRcvbuf()
{
- int value = 0;
+ int value = 0;
#ifdef SO_RCVBUF
- socklen_t len = sizeof(value);
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&value, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(value);
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&value, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO);
+ Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO);
#endif
- return value;
+ return value;
}
#ifdef SO_RCVBUFFORCE
bool Socket::SetSoRcvbufforce(int x)
{
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUFFORCE, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUFFORCE, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1664,44 +1664,44 @@ bool Socket::SetSoRcvbufforce(int x)
bool Socket::SetSoSndbuf(int x)
{
#ifdef SO_SNDBUF
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO);
+ return false;
#endif
}
int Socket::SoSndbuf()
{
- int value = 0;
+ int value = 0;
#ifdef SO_SNDBUF
- socklen_t len = sizeof(value);
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&value, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(value);
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&value, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO);
+ Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO);
#endif
- return value;
+ return value;
}
#ifdef SO_SNDBUFFORCE
bool Socket::SetSoSndbufforce(int x)
{
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUFFORCE, (char *)&x, sizeof(x)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUFFORCE, (char *)&x, sizeof(x)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
@@ -1709,43 +1709,43 @@ bool Socket::SetSoSndbufforce(int x)
#ifdef SO_TIMESTAMP
bool Socket::SetSoTimestamp(bool x)
{
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_TIMESTAMP, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_TIMESTAMP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_TIMESTAMP, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_TIMESTAMP)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
}
#endif
int Socket::SoType()
{
- int value = 0;
+ int value = 0;
#ifdef SO_TYPE
- socklen_t len = sizeof(value);
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, (char *)&value, &len) == -1)
- {
- Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_TYPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- }
+ socklen_t len = sizeof(value);
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, (char *)&value, &len) == -1)
+ {
+ Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_TYPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ }
#else
- Handler().LogError(this, "socket option not available", 0, "SO_TYPE", LOG_LEVEL_INFO);
+ Handler().LogError(this, "socket option not available", 0, "SO_TYPE", LOG_LEVEL_INFO);
#endif
- return value;
+ return value;
}
#ifdef ENABLE_TRIGGERS
void Socket::Subscribe(int id)
{
- Handler().Subscribe(id, this);
+ Handler().Subscribe(id, this);
}
void Socket::Unsubscribe(int id)
{
- Handler().Unsubscribe(id, this);
+ Handler().Unsubscribe(id, this);
}
@@ -1762,14 +1762,14 @@ void Socket::OnCancelled(int)
void Socket::SetTimeout(time_t secs)
{
- if (!secs)
- {
- Handler().AddList(m_socket, LIST_TIMEOUT, false);
- return;
- }
- Handler().AddList(m_socket, LIST_TIMEOUT, true);
- m_timeout_start = time(NULL);
- m_timeout_limit = secs;
+ if (!secs)
+ {
+ Handler().AddList(m_socket, LIST_TIMEOUT, false);
+ return;
+ }
+ Handler().AddList(m_socket, LIST_TIMEOUT, true);
+ m_timeout_start = time(NULL);
+ m_timeout_limit = secs;
}
@@ -1785,9 +1785,9 @@ void Socket::OnConnectTimeout()
bool Socket::Timeout(time_t tnow)
{
- if (tnow - m_timeout_start > m_timeout_limit)
- return true;
- return false;
+ if (tnow - m_timeout_start > m_timeout_limit)
+ return true;
+ return false;
}
@@ -1796,21 +1796,21 @@ port_t Socket::GetSockPort()
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- struct sockaddr_in6 sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- return ntohs(sa.sin6_port);
- }
+ if (IsIpv6())
+ {
+ struct sockaddr_in6 sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ return ntohs(sa.sin6_port);
+ }
#endif
#endif
- struct sockaddr_in sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- return ntohs(sa.sin_port);
+ struct sockaddr_in sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ return ntohs(sa.sin_port);
}
@@ -1819,19 +1819,19 @@ ipaddr_t Socket::GetSockIP4()
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- return 0;
- }
+ if (IsIpv6())
+ {
+ return 0;
+ }
#endif
#endif
- struct sockaddr_in sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- ipaddr_t a;
- memcpy(&a, &sa.sin_addr, 4);
- return a;
+ struct sockaddr_in sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ ipaddr_t a;
+ memcpy(&a, &sa.sin_addr, 4);
+ return a;
}
@@ -1840,18 +1840,18 @@ std::string Socket::GetSockAddress()
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- return "";
- }
+ if (IsIpv6())
+ {
+ return "";
+ }
#endif
#endif
- struct sockaddr_in sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- Ipv4Address addr( sa );
- return addr.Convert();
+ struct sockaddr_in sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ Ipv4Address addr( sa );
+ return addr.Convert();
}
@@ -1860,33 +1860,33 @@ std::string Socket::GetSockAddress()
/** Returns local ipv6 address for bound socket file descriptor. */
struct in6_addr Socket::GetSockIP6()
{
- if (IsIpv6())
- {
- struct sockaddr_in6 sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- return sa.sin6_addr;
- }
- struct in6_addr a;
- memset(&a, 0, sizeof(a));
- return a;
+ if (IsIpv6())
+ {
+ struct sockaddr_in6 sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ return sa.sin6_addr;
+ }
+ struct in6_addr a;
+ memset(&a, 0, sizeof(a));
+ return a;
}
/** Returns local ipv6 address as text for bound socket file descriptor. */
std::string Socket::GetSockAddress6()
{
- if (IsIpv6())
- {
- struct sockaddr_in6 sa;
- socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
- if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
- memset(&sa, 0, sizeof(sa));
- Ipv6Address addr( sa );
- return addr.Convert();
- }
- return "";
+ if (IsIpv6())
+ {
+ struct sockaddr_in6 sa;
+ socklen_t sockaddr_length = sizeof(struct sockaddr_in6);
+ if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1)
+ memset(&sa, 0, sizeof(sa));
+ Ipv6Address addr( sa );
+ return addr.Convert();
+ }
+ return "";
}
#endif
#endif
diff --git a/dep/src/sockets/SocketHandler.cpp b/dep/src/sockets/SocketHandler.cpp
index 9ec5412af38..8a7307f4192 100644
--- a/dep/src/sockets/SocketHandler.cpp
+++ b/dep/src/sockets/SocketHandler.cpp
@@ -1,6 +1,6 @@
/** \file SocketHandler.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -52,7 +52,7 @@ namespace SOCKETS_NAMESPACE {
//#ifdef _DEBUG
//#define DEB(x) x; fflush(stderr);
//#else
-#define DEB(x)
+#define DEB(x)
//#endif
@@ -83,9 +83,9 @@ SocketHandler::SocketHandler(StdLog *p)
,m_slave(false)
#endif
{
- FD_ZERO(&m_rfds);
- FD_ZERO(&m_wfds);
- FD_ZERO(&m_efds);
+ FD_ZERO(&m_rfds);
+ FD_ZERO(&m_wfds);
+ FD_ZERO(&m_efds);
}
@@ -116,878 +116,878 @@ SocketHandler::SocketHandler(Mutex& mutex,StdLog *p)
,m_slave(false)
#endif
{
- m_mutex.Lock();
- FD_ZERO(&m_rfds);
- FD_ZERO(&m_wfds);
- FD_ZERO(&m_efds);
+ m_mutex.Lock();
+ FD_ZERO(&m_rfds);
+ FD_ZERO(&m_wfds);
+ FD_ZERO(&m_efds);
}
SocketHandler::~SocketHandler()
{
#ifdef ENABLE_RESOLVER
- if (m_resolver)
- {
- m_resolver -> Quit();
- }
+ if (m_resolver)
+ {
+ m_resolver -> Quit();
+ }
#endif
- {
- while (m_sockets.size())
- {
-DEB( fprintf(stderr, "Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());)
- socket_m::iterator it = m_sockets.begin();
- Socket *p = it -> second;
- if (p)
- {
-DEB( fprintf(stderr, " fd %d\n", p -> GetSocket());)
- p -> Close();
-DEB( fprintf(stderr, " fd closed %d\n", p -> GetSocket());)
-// p -> OnDelete(); // hey, I turn this back on. what's the worst that could happen??!!
- // MinionSocket breaks, calling MinderHandler methods in OnDelete -
- // MinderHandler is already gone when that happens...
-
- // only delete socket when controlled
- // ie master sockethandler can delete non-detached sockets
- // and a slave sockethandler can only delete a detach socket
- if (p -> DeleteByHandler()
+ {
+ while (m_sockets.size())
+ {
+DEB( fprintf(stderr, "Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());)
+ socket_m::iterator it = m_sockets.begin();
+ Socket *p = it -> second;
+ if (p)
+ {
+DEB( fprintf(stderr, " fd %d\n", p -> GetSocket());)
+ p -> Close();
+DEB( fprintf(stderr, " fd closed %d\n", p -> GetSocket());)
+// p -> OnDelete(); // hey, I turn this back on. what's the worst that could happen??!!
+ // MinionSocket breaks, calling MinderHandler methods in OnDelete -
+ // MinderHandler is already gone when that happens...
+
+ // only delete socket when controlled
+ // ie master sockethandler can delete non-detached sockets
+ // and a slave sockethandler can only delete a detach socket
+ if (p -> DeleteByHandler()
#ifdef ENABLE_DETACH
- && !(m_slave ^ p -> IsDetached())
+ && !(m_slave ^ p -> IsDetached())
#endif
- )
- {
- p -> SetErasedByHandler();
- delete p;
- }
- m_sockets.erase(it);
- }
- else
- {
- m_sockets.erase(it);
- }
-DEB( fprintf(stderr, "next\n");)
- }
-DEB( fprintf(stderr, "/Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());)
- }
+ )
+ {
+ p -> SetErasedByHandler();
+ delete p;
+ }
+ m_sockets.erase(it);
+ }
+ else
+ {
+ m_sockets.erase(it);
+ }
+DEB( fprintf(stderr, "next\n");)
+ }
+DEB( fprintf(stderr, "/Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());)
+ }
#ifdef ENABLE_RESOLVER
- if (m_resolver)
- {
- delete m_resolver;
- }
+ if (m_resolver)
+ {
+ delete m_resolver;
+ }
#endif
- if (m_b_use_mutex)
- {
- m_mutex.Unlock();
- }
+ if (m_b_use_mutex)
+ {
+ m_mutex.Unlock();
+ }
}
Mutex& SocketHandler::GetMutex() const
{
- return m_mutex;
+ return m_mutex;
}
#ifdef ENABLE_DETACH
void SocketHandler::SetSlave(bool x)
{
- m_slave = x;
+ m_slave = x;
}
bool SocketHandler::IsSlave()
{
- return m_slave;
+ return m_slave;
}
#endif
void SocketHandler::RegStdLog(StdLog *log)
{
- m_stdlog = log;
+ m_stdlog = log;
}
void SocketHandler::LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t)
{
- if (m_stdlog)
- {
- m_stdlog -> error(this, p, user_text, err, sys_err, t);
- }
+ if (m_stdlog)
+ {
+ m_stdlog -> error(this, p, user_text, err, sys_err, t);
+ }
}
void SocketHandler::Add(Socket *p)
{
- if (p -> GetSocket() == INVALID_SOCKET)
- {
- LogError(p, "Add", -1, "Invalid socket", LOG_LEVEL_WARNING);
- if (p -> CloseAndDelete())
- {
- m_delete.push_back(p);
- }
- return;
- }
- if (m_add.find(p -> GetSocket()) != m_add.end())
- {
- LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in add queue", LOG_LEVEL_FATAL);
- m_delete.push_back(p);
- return;
- }
- m_add[p -> GetSocket()] = p;
+ if (p -> GetSocket() == INVALID_SOCKET)
+ {
+ LogError(p, "Add", -1, "Invalid socket", LOG_LEVEL_WARNING);
+ if (p -> CloseAndDelete())
+ {
+ m_delete.push_back(p);
+ }
+ return;
+ }
+ if (m_add.find(p -> GetSocket()) != m_add.end())
+ {
+ LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in add queue", LOG_LEVEL_FATAL);
+ m_delete.push_back(p);
+ return;
+ }
+ m_add[p -> GetSocket()] = p;
}
void SocketHandler::Get(SOCKET s,bool& r,bool& w,bool& e)
{
- if (s >= 0)
- {
- r = FD_ISSET(s, &m_rfds) ? true : false;
- w = FD_ISSET(s, &m_wfds) ? true : false;
- e = FD_ISSET(s, &m_efds) ? true : false;
- }
+ if (s >= 0)
+ {
+ r = FD_ISSET(s, &m_rfds) ? true : false;
+ w = FD_ISSET(s, &m_wfds) ? true : false;
+ e = FD_ISSET(s, &m_efds) ? true : false;
+ }
}
void SocketHandler::Set(SOCKET s,bool bRead,bool bWrite,bool bException)
{
-DEB( fprintf(stderr, "Set(%d, %s, %s, %s)\n", s, bRead ? "true" : "false", bWrite ? "true" : "false", bException ? "true" : "false");)
- if (s >= 0)
- {
- if (bRead)
- {
- if (!FD_ISSET(s, &m_rfds))
- {
- FD_SET(s, &m_rfds);
- }
- }
- else
- {
- FD_CLR(s, &m_rfds);
- }
- if (bWrite)
- {
- if (!FD_ISSET(s, &m_wfds))
- {
- FD_SET(s, &m_wfds);
- }
- }
- else
- {
- FD_CLR(s, &m_wfds);
- }
- if (bException)
- {
- if (!FD_ISSET(s, &m_efds))
- {
- FD_SET(s, &m_efds);
- }
- }
- else
- {
- FD_CLR(s, &m_efds);
- }
- }
+DEB( fprintf(stderr, "Set(%d, %s, %s, %s)\n", s, bRead ? "true" : "false", bWrite ? "true" : "false", bException ? "true" : "false");)
+ if (s >= 0)
+ {
+ if (bRead)
+ {
+ if (!FD_ISSET(s, &m_rfds))
+ {
+ FD_SET(s, &m_rfds);
+ }
+ }
+ else
+ {
+ FD_CLR(s, &m_rfds);
+ }
+ if (bWrite)
+ {
+ if (!FD_ISSET(s, &m_wfds))
+ {
+ FD_SET(s, &m_wfds);
+ }
+ }
+ else
+ {
+ FD_CLR(s, &m_wfds);
+ }
+ if (bException)
+ {
+ if (!FD_ISSET(s, &m_efds))
+ {
+ FD_SET(s, &m_efds);
+ }
+ }
+ else
+ {
+ FD_CLR(s, &m_efds);
+ }
+ }
}
int SocketHandler::Select(long sec,long usec)
{
- struct timeval tv;
- tv.tv_sec = sec;
- tv.tv_usec = usec;
- return Select(&tv);
+ struct timeval tv;
+ tv.tv_sec = sec;
+ tv.tv_usec = usec;
+ return Select(&tv);
}
int SocketHandler::Select()
{
- if (!m_fds_callonconnect.empty() ||
+ if (!m_fds_callonconnect.empty() ||
#ifdef ENABLE_DETACH
- (!m_slave && !m_fds_detach.empty()) ||
+ (!m_slave && !m_fds_detach.empty()) ||
#endif
- !m_fds_timeout.empty() ||
- !m_fds_retry.empty() ||
- !m_fds_close.empty() ||
- !m_fds_erase.empty())
- {
- return Select(0, 200000);
- }
- return Select(NULL);
+ !m_fds_timeout.empty() ||
+ !m_fds_retry.empty() ||
+ !m_fds_close.empty() ||
+ !m_fds_erase.empty())
+ {
+ return Select(0, 200000);
+ }
+ return Select(NULL);
}
int SocketHandler::Select(struct timeval *tsel)
{
- size_t ignore = 0;
- while (m_add.size() > ignore)
- {
- if (m_sockets.size() >= FD_SETSIZE)
- {
- LogError(NULL, "Select", (int)m_sockets.size(), "FD_SETSIZE reached", LOG_LEVEL_WARNING);
- break;
- }
- socket_m::iterator it = m_add.begin();
- SOCKET s = it -> first;
- Socket *p = it -> second;
-DEB( fprintf(stderr, "Trying to add fd %d, m_add.size() %d, ignore %d\n", (int)s, (int)m_add.size(), (int)ignore);)
- //
- if (m_sockets.find(p -> GetSocket()) != m_sockets.end())
- {
- LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in controlled queue", LOG_LEVEL_FATAL);
- // %! it's a dup, don't add to delete queue, just ignore it
- m_delete.push_back(p);
- m_add.erase(it);
-// ignore++;
- continue;
- }
- if (!p -> CloseAndDelete())
- {
- StreamSocket *scp = dynamic_cast<StreamSocket *>(p);
- if (scp && scp -> Connecting()) // 'Open' called before adding socket
- {
- Set(s,false,true);
- }
- else
- {
- TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
- bool bWrite = tcp ? tcp -> GetOutputLength() != 0 : false;
- if (p -> IsDisableRead())
- {
- Set(s, false, bWrite);
- }
- else
- {
- Set(s, true, bWrite);
- }
- }
- m_maxsock = (s > m_maxsock) ? s : m_maxsock;
- }
- else
- {
- LogError(p, "Add", (int)p -> GetSocket(), "Trying to add socket with SetCloseAndDelete() true", LOG_LEVEL_WARNING);
- }
- // only add to m_fds (process fd_set events) if
- // slave handler and detached/detaching socket
- // master handler and non-detached socket
+ size_t ignore = 0;
+ while (m_add.size() > ignore)
+ {
+ if (m_sockets.size() >= FD_SETSIZE)
+ {
+ LogError(NULL, "Select", (int)m_sockets.size(), "FD_SETSIZE reached", LOG_LEVEL_WARNING);
+ break;
+ }
+ socket_m::iterator it = m_add.begin();
+ SOCKET s = it -> first;
+ Socket *p = it -> second;
+DEB( fprintf(stderr, "Trying to add fd %d, m_add.size() %d, ignore %d\n", (int)s, (int)m_add.size(), (int)ignore);)
+ //
+ if (m_sockets.find(p -> GetSocket()) != m_sockets.end())
+ {
+ LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in controlled queue", LOG_LEVEL_FATAL);
+ // %! it's a dup, don't add to delete queue, just ignore it
+ m_delete.push_back(p);
+ m_add.erase(it);
+// ignore++;
+ continue;
+ }
+ if (!p -> CloseAndDelete())
+ {
+ StreamSocket *scp = dynamic_cast<StreamSocket *>(p);
+ if (scp && scp -> Connecting()) // 'Open' called before adding socket
+ {
+ Set(s,false,true);
+ }
+ else
+ {
+ TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
+ bool bWrite = tcp ? tcp -> GetOutputLength() != 0 : false;
+ if (p -> IsDisableRead())
+ {
+ Set(s, false, bWrite);
+ }
+ else
+ {
+ Set(s, true, bWrite);
+ }
+ }
+ m_maxsock = (s > m_maxsock) ? s : m_maxsock;
+ }
+ else
+ {
+ LogError(p, "Add", (int)p -> GetSocket(), "Trying to add socket with SetCloseAndDelete() true", LOG_LEVEL_WARNING);
+ }
+ // only add to m_fds (process fd_set events) if
+ // slave handler and detached/detaching socket
+ // master handler and non-detached socket
#ifdef ENABLE_DETACH
- if (!(m_slave ^ p -> IsDetach()))
+ if (!(m_slave ^ p -> IsDetach()))
#endif
- {
- m_fds.push_back(s);
- }
- m_sockets[s] = p;
- //
- m_add.erase(it);
- }
+ {
+ m_fds.push_back(s);
+ }
+ m_sockets[s] = p;
+ //
+ m_add.erase(it);
+ }
#ifdef MACOSX
- fd_set rfds;
- fd_set wfds;
- fd_set efds;
- FD_COPY(&m_rfds, &rfds);
- FD_COPY(&m_wfds, &wfds);
- FD_COPY(&m_efds, &efds);
+ fd_set rfds;
+ fd_set wfds;
+ fd_set efds;
+ FD_COPY(&m_rfds, &rfds);
+ FD_COPY(&m_wfds, &wfds);
+ FD_COPY(&m_efds, &efds);
#else
- fd_set rfds = m_rfds;
- fd_set wfds = m_wfds;
- fd_set efds = m_efds;
+ fd_set rfds = m_rfds;
+ fd_set wfds = m_wfds;
+ fd_set efds = m_efds;
#endif
- int n;
- if (m_b_use_mutex)
- {
- m_mutex.Unlock();
- n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel);
- m_mutex.Lock();
- }
- else
- {
- n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel);
- }
- if (n == -1)
- {
- /*
- EBADF An invalid file descriptor was given in one of the sets.
- EINTR A non blocked signal was caught.
- EINVAL n is negative. Or struct timeval contains bad time values (<0).
- ENOMEM select was unable to allocate memory for internal tables.
- */
- if (Errno != m_preverror || m_errcnt++ % 10000 == 0)
- {
- LogError(NULL, "select", Errno, StrError(Errno));
-DEB( fprintf(stderr, "m_maxsock: %d\n", m_maxsock);
- fprintf(stderr, "%s\n", Errno == EINVAL ? "EINVAL" :
- Errno == EINTR ? "EINTR" :
- Errno == EBADF ? "EBADF" :
- Errno == ENOMEM ? "ENOMEM" : "<another>");
- // test bad fd
- for (SOCKET i = 0; i <= m_maxsock; i++)
- {
- bool t = false;
- FD_ZERO(&rfds);
- FD_ZERO(&wfds);
- FD_ZERO(&efds);
- if (FD_ISSET(i, &m_rfds))
- {
- FD_SET(i, &rfds);
- t = true;
- }
- if (FD_ISSET(i, &m_wfds))
- {
- FD_SET(i, &wfds);
- t = true;
- }
- if (FD_ISSET(i, &m_efds))
- {
- FD_SET(i, &efds);
- t = true;
- }
- if (t && m_sockets.find(i) == m_sockets.end())
- {
- fprintf(stderr, "Bad fd in fd_set: %d\n", i);
- }
- }
+ int n;
+ if (m_b_use_mutex)
+ {
+ m_mutex.Unlock();
+ n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel);
+ m_mutex.Lock();
+ }
+ else
+ {
+ n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel);
+ }
+ if (n == -1)
+ {
+ /*
+ EBADF An invalid file descriptor was given in one of the sets.
+ EINTR A non blocked signal was caught.
+ EINVAL n is negative. Or struct timeval contains bad time values (<0).
+ ENOMEM select was unable to allocate memory for internal tables.
+ */
+ if (Errno != m_preverror || m_errcnt++ % 10000 == 0)
+ {
+ LogError(NULL, "select", Errno, StrError(Errno));
+DEB( fprintf(stderr, "m_maxsock: %d\n", m_maxsock);
+ fprintf(stderr, "%s\n", Errno == EINVAL ? "EINVAL" :
+ Errno == EINTR ? "EINTR" :
+ Errno == EBADF ? "EBADF" :
+ Errno == ENOMEM ? "ENOMEM" : "<another>");
+ // test bad fd
+ for (SOCKET i = 0; i <= m_maxsock; i++)
+ {
+ bool t = false;
+ FD_ZERO(&rfds);
+ FD_ZERO(&wfds);
+ FD_ZERO(&efds);
+ if (FD_ISSET(i, &m_rfds))
+ {
+ FD_SET(i, &rfds);
+ t = true;
+ }
+ if (FD_ISSET(i, &m_wfds))
+ {
+ FD_SET(i, &wfds);
+ t = true;
+ }
+ if (FD_ISSET(i, &m_efds))
+ {
+ FD_SET(i, &efds);
+ t = true;
+ }
+ if (t && m_sockets.find(i) == m_sockets.end())
+ {
+ fprintf(stderr, "Bad fd in fd_set: %d\n", i);
+ }
+ }
) // DEB
- m_preverror = Errno;
- }
- /// \todo rebuild fd_set's from active sockets list (m_sockets) here
- }
- else
- if (!n)
- {
- m_preverror = -1;
- }
- else
- if (n > 0)
- {
- for (socket_v::iterator it2 = m_fds.begin(); it2 != m_fds.end() && n; it2++)
- {
- SOCKET i = *it2;
- if (FD_ISSET(i, &rfds))
- {
- socket_m::iterator itmp = m_sockets.find(i);
- if (itmp != m_sockets.end()) // found
- {
- Socket *p = itmp -> second;
- // new SSL negotiate method
+ m_preverror = Errno;
+ }
+ /// \todo rebuild fd_set's from active sockets list (m_sockets) here
+ }
+ else
+ if (!n)
+ {
+ m_preverror = -1;
+ }
+ else
+ if (n > 0)
+ {
+ for (socket_v::iterator it2 = m_fds.begin(); it2 != m_fds.end() && n; it2++)
+ {
+ SOCKET i = *it2;
+ if (FD_ISSET(i, &rfds))
+ {
+ socket_m::iterator itmp = m_sockets.find(i);
+ if (itmp != m_sockets.end()) // found
+ {
+ Socket *p = itmp -> second;
+ // new SSL negotiate method
#ifdef HAVE_OPENSSL
- if (p -> IsSSLNegotiate())
- {
- p -> SSLNegotiate();
- }
- else
+ if (p -> IsSSLNegotiate())
+ {
+ p -> SSLNegotiate();
+ }
+ else
#endif
- {
- p -> OnRead();
- }
- }
- else
- {
- LogError(NULL, "GetSocket/handler/1", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- n--;
- }
- if (FD_ISSET(i, &wfds))
- {
- socket_m::iterator itmp = m_sockets.find(i);
- if (itmp != m_sockets.end()) // found
- {
- Socket *p = itmp -> second;
- // new SSL negotiate method
+ {
+ p -> OnRead();
+ }
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/1", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ n--;
+ }
+ if (FD_ISSET(i, &wfds))
+ {
+ socket_m::iterator itmp = m_sockets.find(i);
+ if (itmp != m_sockets.end()) // found
+ {
+ Socket *p = itmp -> second;
+ // new SSL negotiate method
#ifdef HAVE_OPENSSL
- if (p -> IsSSLNegotiate())
- {
- p -> SSLNegotiate();
- }
- else
+ if (p -> IsSSLNegotiate())
+ {
+ p -> SSLNegotiate();
+ }
+ else
#endif
- {
- p -> OnWrite();
- }
- }
- else
- {
- LogError(NULL, "GetSocket/handler/2", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- n--;
- }
- if (FD_ISSET(i, &efds))
- {
- socket_m::iterator itmp = m_sockets.find(i);
- if (itmp != m_sockets.end()) // found
- {
- Socket *p = itmp -> second;
- p -> OnException();
- }
- else
- {
- LogError(NULL, "GetSocket/handler/3", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- n--;
- }
- } // m_fds loop
- m_preverror = -1;
- } // if (n > 0)
-
- // check CallOnConnect - EVENT
- if (!m_fds_callonconnect.empty())
- {
- socket_v tmp = m_fds_callonconnect;
- for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
- {
- Socket *p = NULL;
- {
- socket_m::iterator itmp = m_sockets.find(*it);
- if (itmp != m_sockets.end()) // found
- {
- p = itmp -> second;
- }
- else
- {
- LogError(NULL, "GetSocket/handler/4", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- }
- if (p)
- {
-// if (p -> CallOnConnect() && p -> Ready() )
- {
- p -> SetConnected(); // moved here from inside if (tcp) check below
+ {
+ p -> OnWrite();
+ }
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/2", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ n--;
+ }
+ if (FD_ISSET(i, &efds))
+ {
+ socket_m::iterator itmp = m_sockets.find(i);
+ if (itmp != m_sockets.end()) // found
+ {
+ Socket *p = itmp -> second;
+ p -> OnException();
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/3", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ n--;
+ }
+ } // m_fds loop
+ m_preverror = -1;
+ } // if (n > 0)
+
+ // check CallOnConnect - EVENT
+ if (!m_fds_callonconnect.empty())
+ {
+ socket_v tmp = m_fds_callonconnect;
+ for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
+ {
+ Socket *p = NULL;
+ {
+ socket_m::iterator itmp = m_sockets.find(*it);
+ if (itmp != m_sockets.end()) // found
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/4", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ }
+ if (p)
+ {
+// if (p -> CallOnConnect() && p -> Ready() )
+ {
+ p -> SetConnected(); // moved here from inside if (tcp) check below
#ifdef HAVE_OPENSSL
- if (p -> IsSSL()) // SSL Enabled socket
- p -> OnSSLConnect();
- else
+ if (p -> IsSSL()) // SSL Enabled socket
+ p -> OnSSLConnect();
+ else
#endif
#ifdef ENABLE_SOCKS4
- if (p -> Socks4())
- p -> OnSocks4Connect();
- else
+ if (p -> Socks4())
+ p -> OnSocks4Connect();
+ else
#endif
- {
- TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
- if (tcp)
- {
- if (tcp -> GetOutputLength())
- {
- p -> OnWrite();
- }
- }
+ {
+ TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
+ if (tcp)
+ {
+ if (tcp -> GetOutputLength())
+ {
+ p -> OnWrite();
+ }
+ }
#ifdef ENABLE_RECONNECT
- if (tcp && tcp -> IsReconnect())
- p -> OnReconnect();
- else
+ if (tcp && tcp -> IsReconnect())
+ p -> OnReconnect();
+ else
#endif
- {
-// LogError(p, "Calling OnConnect", 0, "Because CallOnConnect", LOG_LEVEL_INFO);
- p -> OnConnect();
- }
- }
-// p -> SetCallOnConnect( false );
- AddList(p -> GetSocket(), LIST_CALLONCONNECT, false);
- }
- }
- }
- }
+ {
+// LogError(p, "Calling OnConnect", 0, "Because CallOnConnect", LOG_LEVEL_INFO);
+ p -> OnConnect();
+ }
+ }
+// p -> SetCallOnConnect( false );
+ AddList(p -> GetSocket(), LIST_CALLONCONNECT, false);
+ }
+ }
+ }
+ }
#ifdef ENABLE_DETACH
- // check detach of socket if master handler - EVENT
- if (!m_slave && !m_fds_detach.empty())
- {
- // %! why not using tmp list here??!?
- for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++)
- {
- Socket *p = NULL;
- {
- socket_m::iterator itmp = m_sockets.find(*it);
- if (itmp != m_sockets.end()) // found
- {
- p = itmp -> second;
- }
- else
- {
- LogError(NULL, "GetSocket/handler/5", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- }
- if (p)
- {
-// if (p -> IsDetach())
- {
- Set(p -> GetSocket(), false, false, false);
- // After DetachSocket(), all calls to Handler() will return a reference
- // to the new slave SocketHandler running in the new thread.
- p -> DetachSocket();
- // Adding the file descriptor to m_fds_erase will now also remove the
- // socket from the detach queue - tnx knightmad
- m_fds_erase.push_back(p -> GetSocket());
- }
- }
- }
- }
+ // check detach of socket if master handler - EVENT
+ if (!m_slave && !m_fds_detach.empty())
+ {
+ // %! why not using tmp list here??!?
+ for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++)
+ {
+ Socket *p = NULL;
+ {
+ socket_m::iterator itmp = m_sockets.find(*it);
+ if (itmp != m_sockets.end()) // found
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/5", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ }
+ if (p)
+ {
+// if (p -> IsDetach())
+ {
+ Set(p -> GetSocket(), false, false, false);
+ // After DetachSocket(), all calls to Handler() will return a reference
+ // to the new slave SocketHandler running in the new thread.
+ p -> DetachSocket();
+ // Adding the file descriptor to m_fds_erase will now also remove the
+ // socket from the detach queue - tnx knightmad
+ m_fds_erase.push_back(p -> GetSocket());
+ }
+ }
+ }
+ }
#endif
- // check Connecting - connection timeout - conditional event
- if (m_fds_timeout.size())
- {
- time_t tnow = time(NULL);
- if (tnow != m_tlast)
- {
- socket_v tmp = m_fds_timeout;
-DEB( fprintf(stderr, "Checking %d socket(s) for timeout\n", tmp.size());)
- for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
- {
- Socket *p = NULL;
- {
- socket_m::iterator itmp = m_sockets.find(*it);
- if (itmp != m_sockets.end()) // found
- {
- p = itmp -> second;
- }
- else
- {
- itmp = m_add.find(*it);
- if (itmp != m_add.end())
- {
- p = itmp -> second;
- }
- else
- {
- LogError(NULL, "GetSocket/handler/6", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- }
- }
- if (p)
- {
- if (p -> Timeout(tnow))
- {
- StreamSocket *scp = dynamic_cast<StreamSocket *>(p);
- if (scp && scp -> Connecting())
- p -> OnConnectTimeout();
- else
- p -> OnTimeout();
- p -> SetTimeout(0);
- }
- }
- }
- m_tlast = tnow;
- } // tnow != tlast
- }
- // check retry client connect - EVENT
- if (!m_fds_retry.empty())
- {
- socket_v tmp = m_fds_retry;
- for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
- {
- Socket *p = NULL;
- {
- socket_m::iterator itmp = m_sockets.find(*it);
- if (itmp != m_sockets.end()) // found
- {
- p = itmp -> second;
- }
- else
- {
- LogError(NULL, "GetSocket/handler/7", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- }
- if (p)
- {
-// if (p -> RetryClientConnect())
- {
- TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
- SOCKET nn = *it; //(*it3).first;
- tcp -> SetRetryClientConnect(false);
-DEB( fprintf(stderr, "Close() before retry client connect\n");)
- p -> Close(); // removes from m_fds_retry
- std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress();
- if (ad.get())
- {
- tcp -> Open(*ad);
- }
- else
- {
- LogError(p, "RetryClientConnect", 0, "no address", LOG_LEVEL_ERROR);
- }
- Add(p);
- m_fds_erase.push_back(nn);
- }
- }
- }
- }
- // check close and delete - conditional event
- if (!m_fds_close.empty())
- {
- socket_v tmp = m_fds_close;
-DEB( fprintf(stderr, "m_fds_close.size() == %d\n", (int)m_fds_close.size());)
- for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
- {
- Socket *p = NULL;
- {
- socket_m::iterator itmp = m_sockets.find(*it);
- if (itmp != m_sockets.end()) // found
- {
- p = itmp -> second;
- }
- else
- {
- itmp = m_add.find(*it);
- if (itmp != m_add.end())
- {
- p = itmp -> second;
- }
- else
- {
- LogError(NULL, "GetSocket/handler/8", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
- }
- }
- }
- if (p)
- {
-// if (p -> CloseAndDelete() )
- {
- TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
- // new graceful tcp - flush and close timeout 5s
- if (tcp && p -> IsConnected() && tcp -> GetFlushBeforeClose() &&
+ // check Connecting - connection timeout - conditional event
+ if (m_fds_timeout.size())
+ {
+ time_t tnow = time(NULL);
+ if (tnow != m_tlast)
+ {
+ socket_v tmp = m_fds_timeout;
+DEB( fprintf(stderr, "Checking %d socket(s) for timeout\n", tmp.size());)
+ for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
+ {
+ Socket *p = NULL;
+ {
+ socket_m::iterator itmp = m_sockets.find(*it);
+ if (itmp != m_sockets.end()) // found
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ itmp = m_add.find(*it);
+ if (itmp != m_add.end())
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/6", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ }
+ }
+ if (p)
+ {
+ if (p -> Timeout(tnow))
+ {
+ StreamSocket *scp = dynamic_cast<StreamSocket *>(p);
+ if (scp && scp -> Connecting())
+ p -> OnConnectTimeout();
+ else
+ p -> OnTimeout();
+ p -> SetTimeout(0);
+ }
+ }
+ }
+ m_tlast = tnow;
+ } // tnow != tlast
+ }
+ // check retry client connect - EVENT
+ if (!m_fds_retry.empty())
+ {
+ socket_v tmp = m_fds_retry;
+ for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
+ {
+ Socket *p = NULL;
+ {
+ socket_m::iterator itmp = m_sockets.find(*it);
+ if (itmp != m_sockets.end()) // found
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/7", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ }
+ if (p)
+ {
+// if (p -> RetryClientConnect())
+ {
+ TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
+ SOCKET nn = *it; //(*it3).first;
+ tcp -> SetRetryClientConnect(false);
+DEB( fprintf(stderr, "Close() before retry client connect\n");)
+ p -> Close(); // removes from m_fds_retry
+ std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress();
+ if (ad.get())
+ {
+ tcp -> Open(*ad);
+ }
+ else
+ {
+ LogError(p, "RetryClientConnect", 0, "no address", LOG_LEVEL_ERROR);
+ }
+ Add(p);
+ m_fds_erase.push_back(nn);
+ }
+ }
+ }
+ }
+ // check close and delete - conditional event
+ if (!m_fds_close.empty())
+ {
+ socket_v tmp = m_fds_close;
+DEB( fprintf(stderr, "m_fds_close.size() == %d\n", (int)m_fds_close.size());)
+ for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++)
+ {
+ Socket *p = NULL;
+ {
+ socket_m::iterator itmp = m_sockets.find(*it);
+ if (itmp != m_sockets.end()) // found
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ itmp = m_add.find(*it);
+ if (itmp != m_add.end())
+ {
+ p = itmp -> second;
+ }
+ else
+ {
+ LogError(NULL, "GetSocket/handler/8", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING);
+ }
+ }
+ }
+ if (p)
+ {
+// if (p -> CloseAndDelete() )
+ {
+ TcpSocket *tcp = dynamic_cast<TcpSocket *>(p);
+ // new graceful tcp - flush and close timeout 5s
+ if (tcp && p -> IsConnected() && tcp -> GetFlushBeforeClose() &&
#ifdef HAVE_OPENSSL
- !tcp -> IsSSL() &&
+ !tcp -> IsSSL() &&
#endif
- p -> TimeSinceClose() < 5)
- {
-DEB( fprintf(stderr, " close(1)\n");)
- if (tcp -> GetOutputLength())
- {
- LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Sending all data before closing", LOG_LEVEL_INFO);
- }
- else // shutdown write when output buffer is empty
- if (!(tcp -> GetShutdown() & SHUT_WR))
- {
- SOCKET nn = *it;
- if (nn != INVALID_SOCKET && shutdown(nn, SHUT_WR) == -1)
- {
- LogError(p, "graceful shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- tcp -> SetShutdown(SHUT_WR);
- }
- }
- else
+ p -> TimeSinceClose() < 5)
+ {
+DEB( fprintf(stderr, " close(1)\n");)
+ if (tcp -> GetOutputLength())
+ {
+ LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Sending all data before closing", LOG_LEVEL_INFO);
+ }
+ else // shutdown write when output buffer is empty
+ if (!(tcp -> GetShutdown() & SHUT_WR))
+ {
+ SOCKET nn = *it;
+ if (nn != INVALID_SOCKET && shutdown(nn, SHUT_WR) == -1)
+ {
+ LogError(p, "graceful shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ tcp -> SetShutdown(SHUT_WR);
+ }
+ }
+ else
#ifdef ENABLE_RECONNECT
- if (tcp && p -> IsConnected() && tcp -> Reconnect())
- {
- SOCKET nn = *it; //(*it3).first;
-DEB( fprintf(stderr, " close(2) fd %d\n", nn);)
- p -> SetCloseAndDelete(false);
- tcp -> SetIsReconnect();
- p -> SetConnected(false);
-DEB( fprintf(stderr, "Close() before reconnect\n");)
- p -> Close(); // dispose of old file descriptor (Open creates a new)
- p -> OnDisconnect();
- std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress();
- if (ad.get())
- {
- tcp -> Open(*ad);
- }
- else
- {
- LogError(p, "Reconnect", 0, "no address", LOG_LEVEL_ERROR);
- }
- tcp -> ResetConnectionRetries();
- Add(p);
- m_fds_erase.push_back(nn);
- }
- else
+ if (tcp && p -> IsConnected() && tcp -> Reconnect())
+ {
+ SOCKET nn = *it; //(*it3).first;
+DEB( fprintf(stderr, " close(2) fd %d\n", nn);)
+ p -> SetCloseAndDelete(false);
+ tcp -> SetIsReconnect();
+ p -> SetConnected(false);
+DEB( fprintf(stderr, "Close() before reconnect\n");)
+ p -> Close(); // dispose of old file descriptor (Open creates a new)
+ p -> OnDisconnect();
+ std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress();
+ if (ad.get())
+ {
+ tcp -> Open(*ad);
+ }
+ else
+ {
+ LogError(p, "Reconnect", 0, "no address", LOG_LEVEL_ERROR);
+ }
+ tcp -> ResetConnectionRetries();
+ Add(p);
+ m_fds_erase.push_back(nn);
+ }
+ else
#endif
- {
- SOCKET nn = *it; //(*it3).first;
-DEB( fprintf(stderr, " close(3) fd %d GetSocket() %d\n", nn, p -> GetSocket());)
- if (tcp && p -> IsConnected() && tcp -> GetOutputLength())
- {
- LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Closing socket while data still left to send", LOG_LEVEL_WARNING);
- }
+ {
+ SOCKET nn = *it; //(*it3).first;
+DEB( fprintf(stderr, " close(3) fd %d GetSocket() %d\n", nn, p -> GetSocket());)
+ if (tcp && p -> IsConnected() && tcp -> GetOutputLength())
+ {
+ LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Closing socket while data still left to send", LOG_LEVEL_WARNING);
+ }
#ifdef ENABLE_POOL
- if (p -> Retain() && !p -> Lost())
- {
- PoolSocket *p2 = new PoolSocket(*this, p);
- p2 -> SetDeleteByHandler();
- Add(p2);
- //
- p -> SetCloseAndDelete(false); // added - remove from m_fds_close
- }
- else
+ if (p -> Retain() && !p -> Lost())
+ {
+ PoolSocket *p2 = new PoolSocket(*this, p);
+ p2 -> SetDeleteByHandler();
+ Add(p2);
+ //
+ p -> SetCloseAndDelete(false); // added - remove from m_fds_close
+ }
+ else
#endif // ENABLE_POOL
- {
- Set(p -> GetSocket(),false,false,false);
-DEB( fprintf(stderr, "Close() before OnDelete\n");)
- p -> Close();
- }
- p -> OnDelete();
- if (p -> DeleteByHandler())
- {
- p -> SetErasedByHandler();
- }
- m_fds_erase.push_back(nn);
- }
- }
- }
- }
- }
-
- // check erased sockets
- bool check_max_fd = false;
- while (!m_fds_erase.empty())
- {
- socket_v::iterator it = m_fds_erase.begin();
- SOCKET nn = *it;
+ {
+ Set(p -> GetSocket(),false,false,false);
+DEB( fprintf(stderr, "Close() before OnDelete\n");)
+ p -> Close();
+ }
+ p -> OnDelete();
+ if (p -> DeleteByHandler())
+ {
+ p -> SetErasedByHandler();
+ }
+ m_fds_erase.push_back(nn);
+ }
+ }
+ }
+ }
+ }
+
+ // check erased sockets
+ bool check_max_fd = false;
+ while (!m_fds_erase.empty())
+ {
+ socket_v::iterator it = m_fds_erase.begin();
+ SOCKET nn = *it;
#ifdef ENABLE_DETACH
- {
- for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++)
- {
- if (*it == nn)
- {
- m_fds_detach.erase(it);
- break;
- }
- }
- }
+ {
+ for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++)
+ {
+ if (*it == nn)
+ {
+ m_fds_detach.erase(it);
+ break;
+ }
+ }
+ }
#endif
- {
- for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++)
- {
- if (*it == nn)
- {
- m_fds.erase(it);
- break;
- }
- }
- }
- {
- socket_m::iterator it = m_sockets.find(nn);
- if (it != m_sockets.end())
- {
- Socket *p = it -> second;
- /* Sometimes a SocketThread class can finish its run before the master
- sockethandler gets here. In that case, the SocketThread has set the
- 'ErasedByHandler' flag on the socket which will make us end up with a
- double delete on the socket instance.
- The fix is to make sure that the master sockethandler only can delete
- non-detached sockets, and a slave sockethandler only can delete
- detach sockets. */
- if (p -> ErasedByHandler()
+ {
+ for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++)
+ {
+ if (*it == nn)
+ {
+ m_fds.erase(it);
+ break;
+ }
+ }
+ }
+ {
+ socket_m::iterator it = m_sockets.find(nn);
+ if (it != m_sockets.end())
+ {
+ Socket *p = it -> second;
+ /* Sometimes a SocketThread class can finish its run before the master
+ sockethandler gets here. In that case, the SocketThread has set the
+ 'ErasedByHandler' flag on the socket which will make us end up with a
+ double delete on the socket instance.
+ The fix is to make sure that the master sockethandler only can delete
+ non-detached sockets, and a slave sockethandler only can delete
+ detach sockets. */
+ if (p -> ErasedByHandler()
#ifdef ENABLE_DETACH
- && !(m_slave ^ p -> IsDetached())
+ && !(m_slave ^ p -> IsDetached())
#endif
- )
- {
+ )
+ {
#ifdef ENABLE_TRIGGERS
- bool again = false;
- do
- {
- again = false;
- for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++)
- {
- int id = it -> first;
- Socket *src = it -> second;
- if (src == p)
- {
- for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
- {
- Socket *dst = it -> first;
- if (Valid(dst))
- {
- dst -> OnCancelled(id);
- }
- }
- m_trigger_src.erase(m_trigger_src.find(id));
- m_trigger_dst.erase(m_trigger_dst.find(id));
- again = true;
- break;
- }
- }
- } while (again);
+ bool again = false;
+ do
+ {
+ again = false;
+ for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++)
+ {
+ int id = it -> first;
+ Socket *src = it -> second;
+ if (src == p)
+ {
+ for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
+ {
+ Socket *dst = it -> first;
+ if (Valid(dst))
+ {
+ dst -> OnCancelled(id);
+ }
+ }
+ m_trigger_src.erase(m_trigger_src.find(id));
+ m_trigger_dst.erase(m_trigger_dst.find(id));
+ again = true;
+ break;
+ }
+ }
+ } while (again);
#endif
- delete p;
- }
- m_sockets.erase(it);
- }
- }
- m_fds_erase.erase(it);
- check_max_fd = true;
- }
- // calculate max file descriptor for select() call
- if (check_max_fd)
- {
- m_maxsock = 0;
- for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++)
- {
- SOCKET s = *it;
- m_maxsock = s > m_maxsock ? s : m_maxsock;
- }
- }
- // remove Add's that fizzed
- while (!m_delete.empty())
- {
- std::list<Socket *>::iterator it = m_delete.begin();
- Socket *p = *it;
- p -> OnDelete();
- m_delete.erase(it);
- if (p -> DeleteByHandler()
+ delete p;
+ }
+ m_sockets.erase(it);
+ }
+ }
+ m_fds_erase.erase(it);
+ check_max_fd = true;
+ }
+ // calculate max file descriptor for select() call
+ if (check_max_fd)
+ {
+ m_maxsock = 0;
+ for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++)
+ {
+ SOCKET s = *it;
+ m_maxsock = s > m_maxsock ? s : m_maxsock;
+ }
+ }
+ // remove Add's that fizzed
+ while (!m_delete.empty())
+ {
+ std::list<Socket *>::iterator it = m_delete.begin();
+ Socket *p = *it;
+ p -> OnDelete();
+ m_delete.erase(it);
+ if (p -> DeleteByHandler()
#ifdef ENABLE_DETACH
- && !(m_slave ^ p -> IsDetached())
+ && !(m_slave ^ p -> IsDetached())
#endif
- )
- {
- p -> SetErasedByHandler();
+ )
+ {
+ p -> SetErasedByHandler();
#ifdef ENABLE_TRIGGERS
- bool again = false;
- do
- {
- again = false;
- for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++)
- {
- int id = it -> first;
- Socket *src = it -> second;
- if (src == p)
- {
- for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
- {
- Socket *dst = it -> first;
- if (Valid(dst))
- {
- dst -> OnCancelled(id);
- }
- }
- m_trigger_src.erase(m_trigger_src.find(id));
- m_trigger_dst.erase(m_trigger_dst.find(id));
- again = true;
- break;
- }
- }
- } while (again);
+ bool again = false;
+ do
+ {
+ again = false;
+ for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++)
+ {
+ int id = it -> first;
+ Socket *src = it -> second;
+ if (src == p)
+ {
+ for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
+ {
+ Socket *dst = it -> first;
+ if (Valid(dst))
+ {
+ dst -> OnCancelled(id);
+ }
+ }
+ m_trigger_src.erase(m_trigger_src.find(id));
+ m_trigger_dst.erase(m_trigger_dst.find(id));
+ again = true;
+ break;
+ }
+ }
+ } while (again);
#endif
- delete p;
- }
- }
- return n;
+ delete p;
+ }
+ }
+ return n;
}
#ifdef ENABLE_RESOLVER
bool SocketHandler::Resolving(Socket *p0)
{
- std::map<Socket *, bool>::iterator it = m_resolve_q.find(p0);
- return it != m_resolve_q.end();
+ std::map<Socket *, bool>::iterator it = m_resolve_q.find(p0);
+ return it != m_resolve_q.end();
}
#endif
bool SocketHandler::Valid(Socket *p0)
{
- for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
- {
- Socket *p = it -> second;
- if (p0 == p)
- return true;
- }
- return false;
+ for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
+ {
+ Socket *p = it -> second;
+ if (p0 == p)
+ return true;
+ }
+ return false;
}
bool SocketHandler::OkToAccept(Socket *)
{
- return true;
+ return true;
}
@@ -998,32 +998,32 @@ printf(" m_sockets : %d\n", m_sockets.size());
printf(" m_add : %d\n", m_add.size());
printf(" m_delete : %d\n", m_delete.size());
*/
- return m_sockets.size() + m_add.size() + m_delete.size();
+ return m_sockets.size() + m_add.size() + m_delete.size();
}
#ifdef ENABLE_SOCKS4
void SocketHandler::SetSocks4Host(ipaddr_t a)
{
- m_socks4_host = a;
+ m_socks4_host = a;
}
void SocketHandler::SetSocks4Host(const std::string& host)
{
- Utility::u2ip(host, m_socks4_host);
+ Utility::u2ip(host, m_socks4_host);
}
void SocketHandler::SetSocks4Port(port_t port)
{
- m_socks4_port = port;
+ m_socks4_port = port;
}
void SocketHandler::SetSocks4Userid(const std::string& id)
{
- m_socks4_userid = id;
+ m_socks4_userid = id;
}
#endif
@@ -1031,94 +1031,94 @@ void SocketHandler::SetSocks4Userid(const std::string& id)
#ifdef ENABLE_RESOLVER
int SocketHandler::Resolve(Socket *p,const std::string& host,port_t port)
{
- // check cache
- ResolvSocket *resolv = new ResolvSocket(*this, p, host, port);
- resolv -> SetId(++m_resolv_id);
- resolv -> SetDeleteByHandler();
- ipaddr_t local;
- Utility::u2ip("127.0.0.1", local);
- if (!resolv -> Open(local, m_resolver_port))
- {
- LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
- }
- Add(resolv);
- m_resolve_q[p] = true;
-DEB( fprintf(stderr, " *** Resolve '%s:%d' id#%d m_resolve_q size: %d p: %p\n", host.c_str(), port, resolv -> GetId(), m_resolve_q.size(), p);)
- return resolv -> GetId();
+ // check cache
+ ResolvSocket *resolv = new ResolvSocket(*this, p, host, port);
+ resolv -> SetId(++m_resolv_id);
+ resolv -> SetDeleteByHandler();
+ ipaddr_t local;
+ Utility::u2ip("127.0.0.1", local);
+ if (!resolv -> Open(local, m_resolver_port))
+ {
+ LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
+ }
+ Add(resolv);
+ m_resolve_q[p] = true;
+DEB( fprintf(stderr, " *** Resolve '%s:%d' id#%d m_resolve_q size: %d p: %p\n", host.c_str(), port, resolv -> GetId(), m_resolve_q.size(), p);)
+ return resolv -> GetId();
}
#ifdef ENABLE_IPV6
int SocketHandler::Resolve6(Socket *p,const std::string& host,port_t port)
{
- // check cache
- ResolvSocket *resolv = new ResolvSocket(*this, p, host, port, true);
- resolv -> SetId(++m_resolv_id);
- resolv -> SetDeleteByHandler();
- ipaddr_t local;
- Utility::u2ip("127.0.0.1", local);
- if (!resolv -> Open(local, m_resolver_port))
- {
- LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
- }
- Add(resolv);
- m_resolve_q[p] = true;
- return resolv -> GetId();
+ // check cache
+ ResolvSocket *resolv = new ResolvSocket(*this, p, host, port, true);
+ resolv -> SetId(++m_resolv_id);
+ resolv -> SetDeleteByHandler();
+ ipaddr_t local;
+ Utility::u2ip("127.0.0.1", local);
+ if (!resolv -> Open(local, m_resolver_port))
+ {
+ LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
+ }
+ Add(resolv);
+ m_resolve_q[p] = true;
+ return resolv -> GetId();
}
#endif
int SocketHandler::Resolve(Socket *p,ipaddr_t a)
{
- // check cache
- ResolvSocket *resolv = new ResolvSocket(*this, p, a);
- resolv -> SetId(++m_resolv_id);
- resolv -> SetDeleteByHandler();
- ipaddr_t local;
- Utility::u2ip("127.0.0.1", local);
- if (!resolv -> Open(local, m_resolver_port))
- {
- LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
- }
- Add(resolv);
- m_resolve_q[p] = true;
- return resolv -> GetId();
+ // check cache
+ ResolvSocket *resolv = new ResolvSocket(*this, p, a);
+ resolv -> SetId(++m_resolv_id);
+ resolv -> SetDeleteByHandler();
+ ipaddr_t local;
+ Utility::u2ip("127.0.0.1", local);
+ if (!resolv -> Open(local, m_resolver_port))
+ {
+ LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
+ }
+ Add(resolv);
+ m_resolve_q[p] = true;
+ return resolv -> GetId();
}
#ifdef ENABLE_IPV6
int SocketHandler::Resolve(Socket *p,in6_addr& a)
{
- // check cache
- ResolvSocket *resolv = new ResolvSocket(*this, p, a);
- resolv -> SetId(++m_resolv_id);
- resolv -> SetDeleteByHandler();
- ipaddr_t local;
- Utility::u2ip("127.0.0.1", local);
- if (!resolv -> Open(local, m_resolver_port))
- {
- LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
- }
- Add(resolv);
- m_resolve_q[p] = true;
- return resolv -> GetId();
+ // check cache
+ ResolvSocket *resolv = new ResolvSocket(*this, p, a);
+ resolv -> SetId(++m_resolv_id);
+ resolv -> SetDeleteByHandler();
+ ipaddr_t local;
+ Utility::u2ip("127.0.0.1", local);
+ if (!resolv -> Open(local, m_resolver_port))
+ {
+ LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL);
+ }
+ Add(resolv);
+ m_resolve_q[p] = true;
+ return resolv -> GetId();
}
#endif
void SocketHandler::EnableResolver(port_t port)
{
- if (!m_resolver)
- {
- m_resolver_port = port;
- m_resolver = new ResolvServer(port);
- }
+ if (!m_resolver)
+ {
+ m_resolver_port = port;
+ m_resolver = new ResolvServer(port);
+ }
}
bool SocketHandler::ResolverReady()
{
- return m_resolver ? m_resolver -> Ready() : false;
+ return m_resolver ? m_resolver -> Ready() : false;
}
#endif // ENABLE_RESOLVER
@@ -1126,45 +1126,45 @@ bool SocketHandler::ResolverReady()
#ifdef ENABLE_SOCKS4
void SocketHandler::SetSocks4TryDirect(bool x)
{
- m_bTryDirect = x;
+ m_bTryDirect = x;
}
ipaddr_t SocketHandler::GetSocks4Host()
{
- return m_socks4_host;
+ return m_socks4_host;
}
port_t SocketHandler::GetSocks4Port()
{
- return m_socks4_port;
+ return m_socks4_port;
}
const std::string& SocketHandler::GetSocks4Userid()
{
- return m_socks4_userid;
+ return m_socks4_userid;
}
bool SocketHandler::Socks4TryDirect()
{
- return m_bTryDirect;
+ return m_bTryDirect;
}
#endif
#ifdef ENABLE_RESOLVER
-bool SocketHandler::ResolverEnabled()
-{
- return m_resolver ? true : false;
+bool SocketHandler::ResolverEnabled()
+{
+ return m_resolver ? true : false;
}
-port_t SocketHandler::GetResolverPort()
-{
- return m_resolver_port;
+port_t SocketHandler::GetResolverPort()
+{
+ return m_resolver_port;
}
#endif // ENABLE_RESOLVER
@@ -1172,35 +1172,35 @@ port_t SocketHandler::GetResolverPort()
#ifdef ENABLE_POOL
ISocketHandler::PoolSocket *SocketHandler::FindConnection(int type,const std::string& protocol,SocketAddress& ad)
{
- for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end() && !m_sockets.empty(); it++)
- {
- PoolSocket *pools = dynamic_cast<PoolSocket *>(it -> second);
- if (pools)
- {
- if (pools -> GetSocketType() == type &&
- pools -> GetSocketProtocol() == protocol &&
-// %! pools -> GetClientRemoteAddress() &&
- *pools -> GetClientRemoteAddress() == ad)
- {
- m_sockets.erase(it);
- pools -> SetRetain(); // avoid Close in Socket destructor
- return pools; // Caller is responsible that this socket is deleted
- }
- }
- }
- return NULL;
+ for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end() && !m_sockets.empty(); it++)
+ {
+ PoolSocket *pools = dynamic_cast<PoolSocket *>(it -> second);
+ if (pools)
+ {
+ if (pools -> GetSocketType() == type &&
+ pools -> GetSocketProtocol() == protocol &&
+// %! pools -> GetClientRemoteAddress() &&
+ *pools -> GetClientRemoteAddress() == ad)
+ {
+ m_sockets.erase(it);
+ pools -> SetRetain(); // avoid Close in Socket destructor
+ return pools; // Caller is responsible that this socket is deleted
+ }
+ }
+ }
+ return NULL;
}
void SocketHandler::EnablePool(bool x)
{
- m_b_enable_pool = x;
+ m_b_enable_pool = x;
}
-bool SocketHandler::PoolEnabled()
-{
- return m_b_enable_pool;
+bool SocketHandler::PoolEnabled()
+{
+ return m_b_enable_pool;
}
#endif
@@ -1208,210 +1208,210 @@ bool SocketHandler::PoolEnabled()
void SocketHandler::Remove(Socket *p)
{
#ifdef ENABLE_RESOLVER
- std::map<Socket *, bool>::iterator it4 = m_resolve_q.find(p);
- if (it4 != m_resolve_q.end())
- m_resolve_q.erase(it4);
+ std::map<Socket *, bool>::iterator it4 = m_resolve_q.find(p);
+ if (it4 != m_resolve_q.end())
+ m_resolve_q.erase(it4);
#endif
- if (p -> ErasedByHandler())
- {
- return;
- }
- for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
- {
- if (it -> second == p)
- {
- LogError(p, "Remove", -1, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
- m_sockets.erase(it);
- return;
- }
- }
- for (socket_m::iterator it2 = m_add.begin(); it2 != m_add.end(); it2++)
- {
- if ((*it2).second == p)
- {
- LogError(p, "Remove", -2, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
- m_add.erase(it2);
- return;
- }
- }
- for (std::list<Socket *>::iterator it3 = m_delete.begin(); it3 != m_delete.end(); it3++)
- {
- if (*it3 == p)
- {
- LogError(p, "Remove", -3, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
- m_delete.erase(it3);
- return;
- }
- }
+ if (p -> ErasedByHandler())
+ {
+ return;
+ }
+ for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
+ {
+ if (it -> second == p)
+ {
+ LogError(p, "Remove", -1, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
+ m_sockets.erase(it);
+ return;
+ }
+ }
+ for (socket_m::iterator it2 = m_add.begin(); it2 != m_add.end(); it2++)
+ {
+ if ((*it2).second == p)
+ {
+ LogError(p, "Remove", -2, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
+ m_add.erase(it2);
+ return;
+ }
+ }
+ for (std::list<Socket *>::iterator it3 = m_delete.begin(); it3 != m_delete.end(); it3++)
+ {
+ if (*it3 == p)
+ {
+ LogError(p, "Remove", -3, "Socket destructor called while still in use", LOG_LEVEL_WARNING);
+ m_delete.erase(it3);
+ return;
+ }
+ }
}
void SocketHandler::CheckSanity()
{
- CheckList(m_fds, "active sockets"); // active sockets
- CheckList(m_fds_erase, "sockets to be erased"); // should always be empty anyway
- CheckList(m_fds_callonconnect, "checklist CallOnConnect");
+ CheckList(m_fds, "active sockets"); // active sockets
+ CheckList(m_fds_erase, "sockets to be erased"); // should always be empty anyway
+ CheckList(m_fds_callonconnect, "checklist CallOnConnect");
#ifdef ENABLE_DETACH
- CheckList(m_fds_detach, "checklist Detach");
+ CheckList(m_fds_detach, "checklist Detach");
#endif
- CheckList(m_fds_timeout, "checklist Timeout");
- CheckList(m_fds_retry, "checklist retry client connect");
- CheckList(m_fds_close, "checklist close and delete");
+ CheckList(m_fds_timeout, "checklist Timeout");
+ CheckList(m_fds_retry, "checklist retry client connect");
+ CheckList(m_fds_close, "checklist close and delete");
}
void SocketHandler::CheckList(socket_v& ref,const std::string& listname)
{
- for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
- {
- SOCKET s = *it;
- if (m_sockets.find(s) != m_sockets.end())
- continue;
- if (m_add.find(s) != m_add.end())
- continue;
- bool found = false;
- for (std::list<Socket *>::iterator it = m_delete.begin(); it != m_delete.end(); it++)
- {
- Socket *p = *it;
- if (p -> GetSocket() == s)
- {
- found = true;
- break;
- }
- }
- if (!found)
- {
- fprintf(stderr, "CheckList failed for \"%s\": fd %d\n", listname.c_str(), s);
- }
- }
+ for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
+ {
+ SOCKET s = *it;
+ if (m_sockets.find(s) != m_sockets.end())
+ continue;
+ if (m_add.find(s) != m_add.end())
+ continue;
+ bool found = false;
+ for (std::list<Socket *>::iterator it = m_delete.begin(); it != m_delete.end(); it++)
+ {
+ Socket *p = *it;
+ if (p -> GetSocket() == s)
+ {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ {
+ fprintf(stderr, "CheckList failed for \"%s\": fd %d\n", listname.c_str(), s);
+ }
+ }
}
void SocketHandler::AddList(SOCKET s,list_t which_one,bool add)
{
- if (s == INVALID_SOCKET)
- {
-DEB( fprintf(stderr, "AddList: invalid_socket\n");)
- return;
- }
- socket_v& ref =
- (which_one == LIST_CALLONCONNECT) ? m_fds_callonconnect :
+ if (s == INVALID_SOCKET)
+ {
+DEB( fprintf(stderr, "AddList: invalid_socket\n");)
+ return;
+ }
+ socket_v& ref =
+ (which_one == LIST_CALLONCONNECT) ? m_fds_callonconnect :
#ifdef ENABLE_DETACH
- (which_one == LIST_DETACH) ? m_fds_detach :
+ (which_one == LIST_DETACH) ? m_fds_detach :
#endif
- (which_one == LIST_TIMEOUT) ? m_fds_timeout :
- (which_one == LIST_RETRY) ? m_fds_retry :
- (which_one == LIST_CLOSE) ? m_fds_close : m_fds_close;
- if (add)
- {
+ (which_one == LIST_TIMEOUT) ? m_fds_timeout :
+ (which_one == LIST_RETRY) ? m_fds_retry :
+ (which_one == LIST_CLOSE) ? m_fds_close : m_fds_close;
+ if (add)
+ {
#ifdef ENABLE_DETACH
-DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" :
- (which_one == LIST_DETACH) ? "Detach" :
- (which_one == LIST_TIMEOUT) ? "Timeout" :
- (which_one == LIST_RETRY) ? "Retry" :
- (which_one == LIST_CLOSE) ? "Close" : "<undef>",
- add ? "Add" : "Remove");)
+DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" :
+ (which_one == LIST_DETACH) ? "Detach" :
+ (which_one == LIST_TIMEOUT) ? "Timeout" :
+ (which_one == LIST_RETRY) ? "Retry" :
+ (which_one == LIST_CLOSE) ? "Close" : "<undef>",
+ add ? "Add" : "Remove");)
#else
-DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" :
- (which_one == LIST_TIMEOUT) ? "Timeout" :
- (which_one == LIST_RETRY) ? "Retry" :
- (which_one == LIST_CLOSE) ? "Close" : "<undef>",
- add ? "Add" : "Remove");)
+DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" :
+ (which_one == LIST_TIMEOUT) ? "Timeout" :
+ (which_one == LIST_RETRY) ? "Retry" :
+ (which_one == LIST_CLOSE) ? "Close" : "<undef>",
+ add ? "Add" : "Remove");)
#endif
- }
- if (add)
- {
- for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
- {
- if (*it == s) // already there
- {
- return;
- }
- }
- ref.push_back(s);
- return;
- }
- // remove
- for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
- {
- if (*it == s)
- {
- ref.erase(it);
- break;
- }
- }
-//DEB( fprintf(stderr, "/AddList\n");)
+ }
+ if (add)
+ {
+ for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
+ {
+ if (*it == s) // already there
+ {
+ return;
+ }
+ }
+ ref.push_back(s);
+ return;
+ }
+ // remove
+ for (socket_v::iterator it = ref.begin(); it != ref.end(); it++)
+ {
+ if (*it == s)
+ {
+ ref.erase(it);
+ break;
+ }
+ }
+//DEB( fprintf(stderr, "/AddList\n");)
}
#ifdef ENABLE_TRIGGERS
int SocketHandler::TriggerID(Socket *src)
{
- int id = m_next_trigger_id++;
- m_trigger_src[id] = src;
- return id;
+ int id = m_next_trigger_id++;
+ m_trigger_src[id] = src;
+ return id;
}
bool SocketHandler::Subscribe(int id, Socket *dst)
{
- if (m_trigger_src.find(id) != m_trigger_src.end())
- {
- std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst);
- if (it != m_trigger_dst[id].end())
- {
- m_trigger_dst[id][dst] = true;
- return true;
- }
- LogError(dst, "Subscribe", id, "Already subscribed", LOG_LEVEL_INFO);
- return false;
- }
- LogError(dst, "Subscribe", id, "Trigger id not found", LOG_LEVEL_INFO);
- return false;
+ if (m_trigger_src.find(id) != m_trigger_src.end())
+ {
+ std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst);
+ if (it != m_trigger_dst[id].end())
+ {
+ m_trigger_dst[id][dst] = true;
+ return true;
+ }
+ LogError(dst, "Subscribe", id, "Already subscribed", LOG_LEVEL_INFO);
+ return false;
+ }
+ LogError(dst, "Subscribe", id, "Trigger id not found", LOG_LEVEL_INFO);
+ return false;
}
bool SocketHandler::Unsubscribe(int id, Socket *dst)
{
- if (m_trigger_src.find(id) != m_trigger_src.end())
- {
- std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst);
- if (it != m_trigger_dst[id].end())
- {
- m_trigger_dst[id].erase(it);
- return true;
- }
- LogError(dst, "Unsubscribe", id, "Not subscribed", LOG_LEVEL_INFO);
- return false;
- }
- LogError(dst, "Unsubscribe", id, "Trigger id not found", LOG_LEVEL_INFO);
- return false;
+ if (m_trigger_src.find(id) != m_trigger_src.end())
+ {
+ std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst);
+ if (it != m_trigger_dst[id].end())
+ {
+ m_trigger_dst[id].erase(it);
+ return true;
+ }
+ LogError(dst, "Unsubscribe", id, "Not subscribed", LOG_LEVEL_INFO);
+ return false;
+ }
+ LogError(dst, "Unsubscribe", id, "Trigger id not found", LOG_LEVEL_INFO);
+ return false;
}
void SocketHandler::Trigger(int id, Socket::TriggerData& data, bool erase)
{
- if (m_trigger_src.find(id) != m_trigger_src.end())
- {
- data.SetSource( m_trigger_src[id] );
- for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
- {
- Socket *dst = it -> first;
- if (Valid(dst))
- {
- dst -> OnTrigger(id, data);
- }
- }
- if (erase)
- {
- m_trigger_src.erase(m_trigger_src.find(id));
- m_trigger_dst.erase(m_trigger_dst.find(id));
- }
- }
- else
- {
- LogError(NULL, "Trigger", id, "Trigger id not found", LOG_LEVEL_INFO);
- }
+ if (m_trigger_src.find(id) != m_trigger_src.end())
+ {
+ data.SetSource( m_trigger_src[id] );
+ for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++)
+ {
+ Socket *dst = it -> first;
+ if (Valid(dst))
+ {
+ dst -> OnTrigger(id, data);
+ }
+ }
+ if (erase)
+ {
+ m_trigger_src.erase(m_trigger_src.find(id));
+ m_trigger_dst.erase(m_trigger_dst.find(id));
+ }
+ }
+ else
+ {
+ LogError(NULL, "Trigger", id, "Trigger id not found", LOG_LEVEL_INFO);
+ }
}
#endif // ENABLE_TRIGGERS
diff --git a/dep/src/sockets/StdoutLog.cpp b/dep/src/sockets/StdoutLog.cpp
index c01d8b8c215..93ae535e6d3 100644
--- a/dep/src/sockets/StdoutLog.cpp
+++ b/dep/src/sockets/StdoutLog.cpp
@@ -1,6 +1,6 @@
/** \file StdoutLog.cpp
- ** \date 2004-06-01
- ** \author grymse@alhem.net
+ ** \date 2004-06-01
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -43,49 +43,49 @@ namespace SOCKETS_NAMESPACE {
void StdoutLog::error(ISocketHandler *,Socket *sock,const std::string& call,int err,const std::string& sys_err,loglevel_t lvl)
{
- time_t t = time(NULL);
- struct tm tp;
+ time_t t = time(NULL);
+ struct tm tp;
#ifdef _WIN32
- memcpy(&tp, localtime(&t), sizeof(tp));
+ memcpy(&tp, localtime(&t), sizeof(tp));
#else
- localtime_r(&t, &tp);
+ localtime_r(&t, &tp);
#endif
- std::string level;
-
- switch (lvl)
- {
- case LOG_LEVEL_WARNING:
- level = "Warning";
- break;
- case LOG_LEVEL_ERROR:
- level = "Error";
- break;
- case LOG_LEVEL_FATAL:
- level = "Fatal";
- break;
- case LOG_LEVEL_INFO:
- level = "Info";
- break;
- }
- if (sock)
- {
- printf("%d-%02d-%02d %02d:%02d:%02d :: fd %d :: %s: %d %s (%s)\n",
- tp.tm_year + 1900,
- tp.tm_mon + 1,
- tp.tm_mday,
- tp.tm_hour,tp.tm_min,tp.tm_sec,
- sock -> GetSocket(),
- call.c_str(),err,sys_err.c_str(),level.c_str());
- }
- else
- {
- printf("%d-%02d-%02d %02d:%02d:%02d :: %s: %d %s (%s)\n",
- tp.tm_year + 1900,
- tp.tm_mon + 1,
- tp.tm_mday,
- tp.tm_hour,tp.tm_min,tp.tm_sec,
- call.c_str(),err,sys_err.c_str(),level.c_str());
- }
+ std::string level;
+
+ switch (lvl)
+ {
+ case LOG_LEVEL_WARNING:
+ level = "Warning";
+ break;
+ case LOG_LEVEL_ERROR:
+ level = "Error";
+ break;
+ case LOG_LEVEL_FATAL:
+ level = "Fatal";
+ break;
+ case LOG_LEVEL_INFO:
+ level = "Info";
+ break;
+ }
+ if (sock)
+ {
+ printf("%d-%02d-%02d %02d:%02d:%02d :: fd %d :: %s: %d %s (%s)\n",
+ tp.tm_year + 1900,
+ tp.tm_mon + 1,
+ tp.tm_mday,
+ tp.tm_hour,tp.tm_min,tp.tm_sec,
+ sock -> GetSocket(),
+ call.c_str(),err,sys_err.c_str(),level.c_str());
+ }
+ else
+ {
+ printf("%d-%02d-%02d %02d:%02d:%02d :: %s: %d %s (%s)\n",
+ tp.tm_year + 1900,
+ tp.tm_mon + 1,
+ tp.tm_mday,
+ tp.tm_hour,tp.tm_min,tp.tm_sec,
+ call.c_str(),err,sys_err.c_str(),level.c_str());
+ }
}
diff --git a/dep/src/sockets/StreamSocket.cpp b/dep/src/sockets/StreamSocket.cpp
index 5c5780e3085..4412d498536 100644
--- a/dep/src/sockets/StreamSocket.cpp
+++ b/dep/src/sockets/StreamSocket.cpp
@@ -28,136 +28,136 @@ StreamSocket::~StreamSocket()
void StreamSocket::SetConnecting(bool x)
{
- if (x != m_bConnecting)
- {
- m_bConnecting = x;
- if (x)
- {
- SetTimeout( GetConnectTimeout() );
- }
- else
- {
- SetTimeout( 0 );
- }
- }
+ if (x != m_bConnecting)
+ {
+ m_bConnecting = x;
+ if (x)
+ {
+ SetTimeout( GetConnectTimeout() );
+ }
+ else
+ {
+ SetTimeout( 0 );
+ }
+ }
}
bool StreamSocket::Connecting()
{
- return m_bConnecting;
+ return m_bConnecting;
}
bool StreamSocket::Ready()
{
- if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete())
- return true;
- return false;
+ if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete())
+ return true;
+ return false;
}
void StreamSocket::SetConnectTimeout(int x)
{
- m_connect_timeout = x;
+ m_connect_timeout = x;
}
int StreamSocket::GetConnectTimeout()
{
- return m_connect_timeout;
+ return m_connect_timeout;
}
void StreamSocket::SetFlushBeforeClose(bool x)
{
- m_flush_before_close = x;
+ m_flush_before_close = x;
}
bool StreamSocket::GetFlushBeforeClose()
{
- return m_flush_before_close;
+ return m_flush_before_close;
}
int StreamSocket::GetConnectionRetry()
{
- return m_connection_retry;
+ return m_connection_retry;
}
void StreamSocket::SetConnectionRetry(int x)
{
- m_connection_retry = x;
+ m_connection_retry = x;
}
int StreamSocket::GetConnectionRetries()
{
- return m_retries;
+ return m_retries;
}
void StreamSocket::IncreaseConnectionRetries()
{
- m_retries++;
+ m_retries++;
}
void StreamSocket::ResetConnectionRetries()
{
- m_retries = 0;
+ m_retries = 0;
}
void StreamSocket::SetCallOnConnect(bool x)
{
- Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x);
- m_call_on_connect = x;
+ Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x);
+ m_call_on_connect = x;
}
bool StreamSocket::CallOnConnect()
{
- return m_call_on_connect;
+ return m_call_on_connect;
}
void StreamSocket::SetRetryClientConnect(bool x)
{
- Handler().AddList(GetSocket(), LIST_RETRY, x);
- m_b_retry_connect = x;
+ Handler().AddList(GetSocket(), LIST_RETRY, x);
+ m_b_retry_connect = x;
}
bool StreamSocket::RetryClientConnect()
{
- return m_b_retry_connect;
+ return m_b_retry_connect;
}
void StreamSocket::SetLineProtocol(bool x)
{
- m_line_protocol = x;
+ m_line_protocol = x;
}
bool StreamSocket::LineProtocol()
{
- return m_line_protocol;
+ return m_line_protocol;
}
void StreamSocket::SetShutdown(int x)
{
- m_shutdown = x;
+ m_shutdown = x;
}
int StreamSocket::GetShutdown()
{
- return m_shutdown;
+ return m_shutdown;
}
diff --git a/dep/src/sockets/TcpSocket.cpp b/dep/src/sockets/TcpSocket.cpp
index 36df37d5832..1dc54dd3fac 100644
--- a/dep/src/sockets/TcpSocket.cpp
+++ b/dep/src/sockets/TcpSocket.cpp
@@ -1,6 +1,6 @@
/** \file TcpSocket.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -60,7 +60,7 @@ namespace SOCKETS_NAMESPACE {
//#ifdef _DEBUG
//#define DEB(x) x
//#else
-#define DEB(x)
+#define DEB(x)
//#endif
@@ -148,30 +148,30 @@ TcpSocket::TcpSocket(ISocketHandler& h,size_t isize,size_t osize) : StreamSocket
TcpSocket::~TcpSocket()
{
#ifdef SOCKETS_DYNAMIC_TEMP
- delete[] m_buf;
+ delete[] m_buf;
#endif
- // %! empty m_obuf
- while (m_obuf.size())
- {
- output_l::iterator it = m_obuf.begin();
- OUTPUT *p = *it;
- delete p;
- m_obuf.erase(it);
- }
+ // %! empty m_obuf
+ while (m_obuf.size())
+ {
+ output_l::iterator it = m_obuf.begin();
+ OUTPUT *p = *it;
+ delete p;
+ m_obuf.erase(it);
+ }
#ifdef HAVE_OPENSSL
- if (m_ssl)
- {
- SSL_free(m_ssl);
- }
+ if (m_ssl)
+ {
+ SSL_free(m_ssl);
+ }
#endif
}
bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks)
{
- Ipv4Address ad(ip, port);
- Ipv4Address local;
- return Open(ad, local, skip_socks);
+ Ipv4Address ad(ip, port);
+ Ipv4Address local;
+ return Open(ad, local, skip_socks);
}
@@ -179,8 +179,8 @@ bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks)
#ifdef IPPROTO_IPV6
bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks)
{
- Ipv6Address ad(ip, port);
- return Open(ad, skip_socks);
+ Ipv6Address ad(ip, port);
+ return Open(ad, skip_socks);
}
#endif
#endif
@@ -188,134 +188,134 @@ bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks)
bool TcpSocket::Open(SocketAddress& ad,bool skip_socks)
{
- Ipv4Address bind_ad("0.0.0.0", 0);
- return Open(ad, bind_ad, skip_socks);
+ Ipv4Address bind_ad("0.0.0.0", 0);
+ return Open(ad, bind_ad, skip_socks);
}
bool TcpSocket::Open(SocketAddress& ad,SocketAddress& bind_ad,bool skip_socks)
{
- if (!ad.IsValid())
- {
- Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- return false;
- }
- if (Handler().GetCount() >= FD_SETSIZE)
- {
- Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- return false;
- }
- SetConnecting(false);
+ if (!ad.IsValid())
+ {
+ Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ return false;
+ }
+ if (Handler().GetCount() >= FD_SETSIZE)
+ {
+ Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ return false;
+ }
+ SetConnecting(false);
#ifdef ENABLE_SOCKS4
- SetSocks4(false);
+ SetSocks4(false);
#endif
- // check for pooling
+ // check for pooling
#ifdef ENABLE_POOL
- if (Handler().PoolEnabled())
- {
- ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad);
- if (pools)
- {
- CopyConnection( pools );
- delete pools;
-
- SetIsClient();
- SetCallOnConnect(); // ISocketHandler must call OnConnect
- Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO);
- return true;
- }
- }
+ if (Handler().PoolEnabled())
+ {
+ ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad);
+ if (pools)
+ {
+ CopyConnection( pools );
+ delete pools;
+
+ SetIsClient();
+ SetCallOnConnect(); // ISocketHandler must call OnConnect
+ Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO);
+ return true;
+ }
+ }
#endif
- // if not, create new connection
- SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp");
- if (s == INVALID_SOCKET)
- {
- return false;
- }
- // socket must be nonblocking for async connect
- if (!SetNonblocking(true, s))
- {
- SetCloseAndDelete();
- closesocket(s);
- return false;
- }
+ // if not, create new connection
+ SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp");
+ if (s == INVALID_SOCKET)
+ {
+ return false;
+ }
+ // socket must be nonblocking for async connect
+ if (!SetNonblocking(true, s))
+ {
+ SetCloseAndDelete();
+ closesocket(s);
+ return false;
+ }
#ifdef ENABLE_POOL
- SetIsClient(); // client because we connect
+ SetIsClient(); // client because we connect
#endif
- SetClientRemoteAddress(ad);
- int n = 0;
- if (bind_ad.GetPort() != 0)
- {
- bind(s, bind_ad, bind_ad);
- }
+ SetClientRemoteAddress(ad);
+ int n = 0;
+ if (bind_ad.GetPort() != 0)
+ {
+ bind(s, bind_ad, bind_ad);
+ }
#ifdef ENABLE_SOCKS4
- if (!skip_socks && GetSocks4Host() && GetSocks4Port())
- {
- Ipv4Address sa(GetSocks4Host(), GetSocks4Port());
- {
- std::string sockshost;
- Utility::l2ip(GetSocks4Host(), sockshost);
- Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" +
- Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO);
- }
- SetSocks4();
- n = connect(s, sa, sa);
- SetRemoteAddress(sa);
- }
- else
+ if (!skip_socks && GetSocks4Host() && GetSocks4Port())
+ {
+ Ipv4Address sa(GetSocks4Host(), GetSocks4Port());
+ {
+ std::string sockshost;
+ Utility::l2ip(GetSocks4Host(), sockshost);
+ Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" +
+ Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO);
+ }
+ SetSocks4();
+ n = connect(s, sa, sa);
+ SetRemoteAddress(sa);
+ }
+ else
#endif
- {
- n = connect(s, ad, ad);
- SetRemoteAddress(ad);
- }
- if (n == -1)
- {
- // check error code that means a connect is in progress
+ {
+ n = connect(s, ad, ad);
+ SetRemoteAddress(ad);
+ }
+ if (n == -1)
+ {
+ // check error code that means a connect is in progress
#ifdef _WIN32
- if (Errno == WSAEWOULDBLOCK)
+ if (Errno == WSAEWOULDBLOCK)
#else
- if (Errno == EINPROGRESS)
+ if (Errno == EINPROGRESS)
#endif
- {
- Attach(s);
- SetConnecting( true ); // this flag will control fd_set's
- }
- else
+ {
+ Attach(s);
+ SetConnecting( true ); // this flag will control fd_set's
+ }
+ else
#ifdef ENABLE_SOCKS4
- if (Socks4() && Handler().Socks4TryDirect() ) // retry
- {
- closesocket(s);
- return Open(ad, true);
- }
- else
+ if (Socks4() && Handler().Socks4TryDirect() ) // retry
+ {
+ closesocket(s);
+ return Open(ad, true);
+ }
+ else
#endif
#ifdef ENABLE_RECONNECT
- if (Reconnect())
- {
- Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO);
- Attach(s);
- SetConnecting( true ); // this flag will control fd_set's
- }
- else
+ if (Reconnect())
+ {
+ Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO);
+ Attach(s);
+ SetConnecting( true ); // this flag will control fd_set's
+ }
+ else
#endif
- {
- Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- closesocket(s);
- return false;
- }
- }
- else
- {
- Attach(s);
- SetCallOnConnect(); // ISocketHandler must call OnConnect
- }
+ {
+ Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ closesocket(s);
+ return false;
+ }
+ }
+ else
+ {
+ Attach(s);
+ SetCallOnConnect(); // ISocketHandler must call OnConnect
+ }
- // 'true' means connected or connecting(not yet connected)
- // 'false' means something failed
- return true; //!Connecting();
+ // 'true' means connected or connecting(not yet connected)
+ // 'false' means something failed
+ return true; //!Connecting();
}
@@ -323,47 +323,47 @@ bool TcpSocket::Open(const std::string &host,port_t port)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
+ if (IsIpv6())
+ {
#ifdef ENABLE_RESOLVER
- if (!Handler().ResolverEnabled() || Utility::isipv6(host) )
- {
+ if (!Handler().ResolverEnabled() || Utility::isipv6(host) )
+ {
#endif
- in6_addr a;
- if (!Utility::u2ip(host, a))
- {
- SetCloseAndDelete();
- return false;
- }
- Ipv6Address ad(a, port);
- Ipv6Address local;
- return Open(ad, local);
+ in6_addr a;
+ if (!Utility::u2ip(host, a))
+ {
+ SetCloseAndDelete();
+ return false;
+ }
+ Ipv6Address ad(a, port);
+ Ipv6Address local;
+ return Open(ad, local);
#ifdef ENABLE_RESOLVER
- }
- m_resolver_id = Resolve6(host, port);
- return true;
+ }
+ m_resolver_id = Resolve6(host, port);
+ return true;
#endif
- }
+ }
#endif
#endif
#ifdef ENABLE_RESOLVER
- if (!Handler().ResolverEnabled() || Utility::isipv4(host) )
- {
+ if (!Handler().ResolverEnabled() || Utility::isipv4(host) )
+ {
#endif
- ipaddr_t l;
- if (!Utility::u2ip(host,l))
- {
- SetCloseAndDelete();
- return false;
- }
- Ipv4Address ad(l, port);
- Ipv4Address local;
- return Open(ad, local);
+ ipaddr_t l;
+ if (!Utility::u2ip(host,l))
+ {
+ SetCloseAndDelete();
+ return false;
+ }
+ Ipv4Address ad(l, port);
+ Ipv4Address local;
+ return Open(ad, local);
#ifdef ENABLE_RESOLVER
- }
- // resolve using async resolver thread
- m_resolver_id = Resolve(host, port);
- return true;
+ }
+ // resolve using async resolver thread
+ m_resolver_id = Resolve(host, port);
+ return true;
#endif
}
@@ -371,58 +371,58 @@ bool TcpSocket::Open(const std::string &host,port_t port)
#ifdef ENABLE_RESOLVER
void TcpSocket::OnResolved(int id,ipaddr_t a,port_t port)
{
-DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);)
- if (id == m_resolver_id)
- {
- if (a && port)
- {
- Ipv4Address ad(a, port);
- Ipv4Address local;
- if (Open(ad, local))
- {
- if (!Handler().Valid(this))
- {
- Handler().Add(this);
- }
- }
- }
- else
- {
- Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- }
- }
- else
- {
- Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- }
+DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);)
+ if (id == m_resolver_id)
+ {
+ if (a && port)
+ {
+ Ipv4Address ad(a, port);
+ Ipv4Address local;
+ if (Open(ad, local))
+ {
+ if (!Handler().Valid(this))
+ {
+ Handler().Add(this);
+ }
+ }
+ }
+ else
+ {
+ Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ }
+ }
+ else
+ {
+ Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ }
}
#ifdef ENABLE_IPV6
void TcpSocket::OnResolved(int id,in6_addr& a,port_t port)
{
- if (id == m_resolver_id)
- {
- Ipv6Address ad(a, port);
- if (ad.IsValid())
- {
- Ipv6Address local;
- if (Open(ad, local))
- {
- if (!Handler().Valid(this))
- {
- Handler().Add(this);
- }
- }
- }
- }
- else
- {
- Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- }
+ if (id == m_resolver_id)
+ {
+ Ipv6Address ad(a, port);
+ if (ad.IsValid())
+ {
+ Ipv6Address local;
+ if (Open(ad, local))
+ {
+ if (!Handler().Valid(this))
+ {
+ Handler().Add(this);
+ }
+ }
+ }
+ }
+ else
+ {
+ Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ }
}
#endif
#endif
@@ -430,191 +430,191 @@ void TcpSocket::OnResolved(int id,in6_addr& a,port_t port)
void TcpSocket::OnRead()
{
- int n = 0;
+ int n = 0;
#ifdef SOCKETS_DYNAMIC_TEMP
- char *buf = m_buf;
+ char *buf = m_buf;
#else
- char buf[TCP_BUFSIZE_READ];
+ char buf[TCP_BUFSIZE_READ];
#endif
#ifdef HAVE_OPENSSL
- if (IsSSL())
- {
- if (!Ready())
- return;
- n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ);
- if (n == -1)
- {
- n = SSL_get_error(m_ssl, n);
- switch (n)
- {
- case SSL_ERROR_NONE:
- case SSL_ERROR_WANT_READ:
- case SSL_ERROR_WANT_WRITE:
- break;
- case SSL_ERROR_ZERO_RETURN:
-DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");)
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- break;
- default:
-DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);)
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- }
- return;
- }
- else
- if (!n)
- {
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- SetShutdown(SHUT_WR);
- return;
- }
- else
- if (n > 0 && n <= TCP_BUFSIZE_READ)
- {
- m_bytes_received += n;
- if (GetTrafficMonitor())
- {
- GetTrafficMonitor() -> fwrite(buf, 1, n);
- }
- if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
- {
- Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING);
- }
- }
- else
- {
- Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR);
- }
- }
- else
+ if (IsSSL())
+ {
+ if (!Ready())
+ return;
+ n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ);
+ if (n == -1)
+ {
+ n = SSL_get_error(m_ssl, n);
+ switch (n)
+ {
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_WANT_READ:
+ case SSL_ERROR_WANT_WRITE:
+ break;
+ case SSL_ERROR_ZERO_RETURN:
+DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");)
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ break;
+ default:
+DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);)
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ }
+ return;
+ }
+ else
+ if (!n)
+ {
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ SetShutdown(SHUT_WR);
+ return;
+ }
+ else
+ if (n > 0 && n <= TCP_BUFSIZE_READ)
+ {
+ m_bytes_received += n;
+ if (GetTrafficMonitor())
+ {
+ GetTrafficMonitor() -> fwrite(buf, 1, n);
+ }
+ if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
+ {
+ Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING);
+ }
+ }
+ else
+ {
+ Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR);
+ }
+ }
+ else
#endif // HAVE_OPENSSL
- {
- n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL);
- if (n == -1)
- {
- Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- return;
- }
- else
- if (!n)
- {
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- SetShutdown(SHUT_WR);
- return;
- }
- else
- if (n > 0 && n <= TCP_BUFSIZE_READ)
- {
- m_bytes_received += n;
- if (GetTrafficMonitor())
- {
- GetTrafficMonitor() -> fwrite(buf, 1, n);
- }
- if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
- {
- Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING);
- }
- }
- else
- {
- Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR);
- }
- }
- //
- OnRead( buf, n );
+ {
+ n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL);
+ if (n == -1)
+ {
+ Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ return;
+ }
+ else
+ if (!n)
+ {
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ SetShutdown(SHUT_WR);
+ return;
+ }
+ else
+ if (n > 0 && n <= TCP_BUFSIZE_READ)
+ {
+ m_bytes_received += n;
+ if (GetTrafficMonitor())
+ {
+ GetTrafficMonitor() -> fwrite(buf, 1, n);
+ }
+ if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n))
+ {
+ Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING);
+ }
+ }
+ else
+ {
+ Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR);
+ }
+ }
+ //
+ OnRead( buf, n );
}
void TcpSocket::OnRead( char *buf, size_t n )
{
- // unbuffered
- if (n > 0 && n <= TCP_BUFSIZE_READ)
- {
- if (LineProtocol())
- {
- buf[n] = 0;
- size_t i = 0;
- if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c)
- {
- m_skip_c = false;
- i++;
- }
- size_t x = i;
- for (; i < n && LineProtocol(); i++)
- {
- while ((buf[i] == 13 || buf[i] == 10) && LineProtocol())
- {
- char c = buf[i];
- buf[i] = 0;
- if (buf[x])
- {
- m_line += (buf + x);
- }
- OnLine( m_line );
- i++;
- m_skip_c = true;
- m_c = c;
- if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c)
- {
- m_skip_c = false;
- i++;
- }
- x = i;
- m_line = "";
- }
- if (!LineProtocol())
- {
- break;
- }
- }
- if (!LineProtocol())
- {
- if (i < n)
- {
- OnRawData(buf + i, n - i);
- }
- }
- else
- if (buf[x])
- {
- m_line += (buf + x);
- }
- }
- else
- {
- OnRawData(buf, n);
- }
- }
- if (m_b_input_buffer_disabled)
- {
- return;
- }
- // further processing: socks4
+ // unbuffered
+ if (n > 0 && n <= TCP_BUFSIZE_READ)
+ {
+ if (LineProtocol())
+ {
+ buf[n] = 0;
+ size_t i = 0;
+ if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c)
+ {
+ m_skip_c = false;
+ i++;
+ }
+ size_t x = i;
+ for (; i < n && LineProtocol(); i++)
+ {
+ while ((buf[i] == 13 || buf[i] == 10) && LineProtocol())
+ {
+ char c = buf[i];
+ buf[i] = 0;
+ if (buf[x])
+ {
+ m_line += (buf + x);
+ }
+ OnLine( m_line );
+ i++;
+ m_skip_c = true;
+ m_c = c;
+ if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c)
+ {
+ m_skip_c = false;
+ i++;
+ }
+ x = i;
+ m_line = "";
+ }
+ if (!LineProtocol())
+ {
+ break;
+ }
+ }
+ if (!LineProtocol())
+ {
+ if (i < n)
+ {
+ OnRawData(buf + i, n - i);
+ }
+ }
+ else
+ if (buf[x])
+ {
+ m_line += (buf + x);
+ }
+ }
+ else
+ {
+ OnRawData(buf, n);
+ }
+ }
+ if (m_b_input_buffer_disabled)
+ {
+ return;
+ }
+ // further processing: socks4
#ifdef ENABLE_SOCKS4
- if (Socks4())
- {
- bool need_more = false;
- while (GetInputLength() && !need_more && !CloseAndDelete())
- {
- need_more = OnSocks4Read();
- }
- }
+ if (Socks4())
+ {
+ bool need_more = false;
+ while (GetInputLength() && !need_more && !CloseAndDelete())
+ {
+ need_more = OnSocks4Read();
+ }
+ }
#endif
}
@@ -626,252 +626,252 @@ void TcpSocket::OnWriteComplete()
void TcpSocket::OnWrite()
{
- if (Connecting())
- {
- int err = SoError();
-
- // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on
- if (!err) // ok
- {
- Set(!IsDisableRead(), false);
- SetConnecting(false);
- SetCallOnConnect();
- return;
- }
- Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL);
- Set(false, false); // no more monitoring because connection failed
-
- // failed
+ if (Connecting())
+ {
+ int err = SoError();
+
+ // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on
+ if (!err) // ok
+ {
+ Set(!IsDisableRead(), false);
+ SetConnecting(false);
+ SetCallOnConnect();
+ return;
+ }
+ Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL);
+ Set(false, false); // no more monitoring because connection failed
+
+ // failed
#ifdef ENABLE_SOCKS4
- if (Socks4())
- {
- // %! leave 'Connecting' flag set?
- OnSocks4ConnectFailed();
- return;
- }
+ if (Socks4())
+ {
+ // %! leave 'Connecting' flag set?
+ OnSocks4ConnectFailed();
+ return;
+ }
#endif
- if (GetConnectionRetry() == -1 ||
- (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
- {
- // even though the connection failed at once, only retry after
- // the connection timeout.
- // should we even try to connect again, when CheckConnect returns
- // false it's because of a connection error - not a timeout...
- return;
- }
- SetConnecting(false);
- SetCloseAndDelete( true );
- /// \todo state reason why connect failed
- OnConnectFailed();
- return;
- }
- // try send next block in buffer
- // if full block is sent, repeat
- // if all blocks are sent, reset m_wfds
-
- bool repeat = false;
- size_t sz = m_transfer_limit ? GetOutputLength() : 0;
- do
- {
- output_l::iterator it = m_obuf.begin();
- OUTPUT *p = *it;
- repeat = false;
- int n = TryWrite(p -> Buf(), p -> Len());
- if (n > 0)
- {
- size_t left = p -> Remove(n);
- m_output_length -= n;
- if (!left)
- {
- delete p;
- m_obuf.erase(it);
- if (!m_obuf.size())
- {
- m_obuf_top = NULL;
- OnWriteComplete();
- }
- else
- {
- repeat = true;
- }
- }
- }
- } while (repeat);
-
- if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit)
- {
- OnTransferLimit();
- }
-
- // check output buffer set, set/reset m_wfds accordingly
- {
- bool br;
- bool bw;
- bool bx;
- Handler().Get(GetSocket(), br, bw, bx);
- if (m_obuf.size())
- Set(br, true);
- else
- Set(br, false);
- }
+ if (GetConnectionRetry() == -1 ||
+ (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
+ {
+ // even though the connection failed at once, only retry after
+ // the connection timeout.
+ // should we even try to connect again, when CheckConnect returns
+ // false it's because of a connection error - not a timeout...
+ return;
+ }
+ SetConnecting(false);
+ SetCloseAndDelete( true );
+ /// \todo state reason why connect failed
+ OnConnectFailed();
+ return;
+ }
+ // try send next block in buffer
+ // if full block is sent, repeat
+ // if all blocks are sent, reset m_wfds
+
+ bool repeat = false;
+ size_t sz = m_transfer_limit ? GetOutputLength() : 0;
+ do
+ {
+ output_l::iterator it = m_obuf.begin();
+ OUTPUT *p = *it;
+ repeat = false;
+ int n = TryWrite(p -> Buf(), p -> Len());
+ if (n > 0)
+ {
+ size_t left = p -> Remove(n);
+ m_output_length -= n;
+ if (!left)
+ {
+ delete p;
+ m_obuf.erase(it);
+ if (!m_obuf.size())
+ {
+ m_obuf_top = NULL;
+ OnWriteComplete();
+ }
+ else
+ {
+ repeat = true;
+ }
+ }
+ }
+ } while (repeat);
+
+ if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit)
+ {
+ OnTransferLimit();
+ }
+
+ // check output buffer set, set/reset m_wfds accordingly
+ {
+ bool br;
+ bool bw;
+ bool bx;
+ Handler().Get(GetSocket(), br, bw, bx);
+ if (m_obuf.size())
+ Set(br, true);
+ else
+ Set(br, false);
+ }
}
int TcpSocket::TryWrite(const char *buf, size_t len)
{
- int n = 0;
+ int n = 0;
#ifdef HAVE_OPENSSL
- if (IsSSL())
- {
- n = SSL_write(m_ssl, buf, (int)len);
- if (n == -1)
- {
- int errnr = SSL_get_error(m_ssl, n);
- if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE )
- {
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- const char *errbuf = ERR_error_string(errnr, NULL);
- Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL);
- }
- return 0;
- }
- else
- if (!n)
- {
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
-DEB( int errnr = SSL_get_error(m_ssl, n);
- const char *errbuf = ERR_error_string(errnr, NULL);
- fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);)
- }
- }
- else
+ if (IsSSL())
+ {
+ n = SSL_write(m_ssl, buf, (int)len);
+ if (n == -1)
+ {
+ int errnr = SSL_get_error(m_ssl, n);
+ if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE )
+ {
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ const char *errbuf = ERR_error_string(errnr, NULL);
+ Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL);
+ }
+ return 0;
+ }
+ else
+ if (!n)
+ {
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+DEB( int errnr = SSL_get_error(m_ssl, n);
+ const char *errbuf = ERR_error_string(errnr, NULL);
+ fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);)
+ }
+ }
+ else
#endif // HAVE_OPENSSL
- {
- n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL);
- if (n == -1)
- {
- // normal error codes:
- // WSAEWOULDBLOCK
- // EAGAIN or EWOULDBLOCK
+ {
+ n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL);
+ if (n == -1)
+ {
+ // normal error codes:
+ // WSAEWOULDBLOCK
+ // EAGAIN or EWOULDBLOCK
#ifdef _WIN32
- if (Errno != WSAEWOULDBLOCK)
+ if (Errno != WSAEWOULDBLOCK)
#else
- if (Errno != EWOULDBLOCK)
+ if (Errno != EWOULDBLOCK)
#endif
- {
- Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- OnDisconnect();
- SetCloseAndDelete(true);
- SetFlushBeforeClose(false);
- SetLost();
- }
- return 0;
- }
- }
- if (n > 0)
- {
- m_bytes_sent += n;
- if (GetTrafficMonitor())
- {
- GetTrafficMonitor() -> fwrite(buf, 1, n);
- }
- }
- return n;
+ {
+ Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ OnDisconnect();
+ SetCloseAndDelete(true);
+ SetFlushBeforeClose(false);
+ SetLost();
+ }
+ return 0;
+ }
+ }
+ if (n > 0)
+ {
+ m_bytes_sent += n;
+ if (GetTrafficMonitor())
+ {
+ GetTrafficMonitor() -> fwrite(buf, 1, n);
+ }
+ }
+ return n;
}
void TcpSocket::Buffer(const char *buf, size_t len)
{
- size_t ptr = 0;
- m_output_length += len;
- while (ptr < len)
- {
- // buf/len => pbuf/sz
- size_t space = 0;
- if (m_obuf_top && (space = m_obuf_top -> Space()) > 0)
- {
- const char *pbuf = buf + ptr;
- size_t sz = len - ptr;
- if (space >= sz)
- {
- m_obuf_top -> Add(pbuf, sz);
- ptr += sz;
- }
- else
- {
- m_obuf_top -> Add(pbuf, space);
- ptr += space;
- }
- }
- else
- {
- m_obuf_top = new OUTPUT;
- m_obuf.push_back( m_obuf_top );
- }
- }
+ size_t ptr = 0;
+ m_output_length += len;
+ while (ptr < len)
+ {
+ // buf/len => pbuf/sz
+ size_t space = 0;
+ if (m_obuf_top && (space = m_obuf_top -> Space()) > 0)
+ {
+ const char *pbuf = buf + ptr;
+ size_t sz = len - ptr;
+ if (space >= sz)
+ {
+ m_obuf_top -> Add(pbuf, sz);
+ ptr += sz;
+ }
+ else
+ {
+ m_obuf_top -> Add(pbuf, space);
+ ptr += space;
+ }
+ }
+ else
+ {
+ m_obuf_top = new OUTPUT;
+ m_obuf.push_back( m_obuf_top );
+ }
+ }
}
void TcpSocket::Send(const std::string &str,int i)
{
- SendBuf(str.c_str(),str.size(),i);
+ SendBuf(str.c_str(),str.size(),i);
}
void TcpSocket::SendBuf(const char *buf,size_t len,int)
{
- if (!Ready() && !Connecting())
- {
- Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning
- if (GetSocket() == INVALID_SOCKET)
- Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO);
- if (Connecting())
- Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO);
- if (CloseAndDelete())
- Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO);
- return;
- }
- if (!IsConnected())
- {
- Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning
- Buffer(buf, len);
- return;
- }
- if (m_obuf_top)
- {
- Buffer(buf, len);
- return;
- }
- int n = TryWrite(buf, len);
- if (n >= 0 && n < (int)len)
- {
- Buffer(buf + n, len - n);
- }
- // if ( data in buffer || !IsConnected )
- // {
- // add to buffer
- // }
- // else
- // try_send
- // if any data is unsent, buffer it and set m_wfds
-
- // check output buffer set, set/reset m_wfds accordingly
- {
- bool br;
- bool bw;
- bool bx;
- Handler().Get(GetSocket(), br, bw, bx);
- if (m_obuf.size())
- Set(br, true);
- else
- Set(br, false);
- }
+ if (!Ready() && !Connecting())
+ {
+ Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning
+ if (GetSocket() == INVALID_SOCKET)
+ Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO);
+ if (Connecting())
+ Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO);
+ if (CloseAndDelete())
+ Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO);
+ return;
+ }
+ if (!IsConnected())
+ {
+ Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning
+ Buffer(buf, len);
+ return;
+ }
+ if (m_obuf_top)
+ {
+ Buffer(buf, len);
+ return;
+ }
+ int n = TryWrite(buf, len);
+ if (n >= 0 && n < (int)len)
+ {
+ Buffer(buf + n, len - n);
+ }
+ // if ( data in buffer || !IsConnected )
+ // {
+ // add to buffer
+ // }
+ // else
+ // try_send
+ // if any data is unsent, buffer it and set m_wfds
+
+ // check output buffer set, set/reset m_wfds accordingly
+ {
+ bool br;
+ bool bw;
+ bool bx;
+ Handler().Get(GetSocket(), br, bw, bx);
+ if (m_obuf.size())
+ Set(br, true);
+ else
+ Set(br, false);
+ }
}
@@ -896,478 +896,478 @@ TcpSocket::TcpSocket(const TcpSocket& s)
#ifdef ENABLE_SOCKS4
void TcpSocket::OnSocks4Connect()
{
- char request[1000];
- memset(request, 0, sizeof(request));
- request[0] = 4; // socks v4
- request[1] = 1; // command code: CONNECT
- {
- std::auto_ptr<SocketAddress> ad = GetClientRemoteAddress();
- if (ad.get())
- {
- struct sockaddr *p0 = (struct sockaddr *)*ad;
- struct sockaddr_in *p = (struct sockaddr_in *)p0;
- if (p -> sin_family == AF_INET)
- {
- memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here
- memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr));
- }
- else
- {
- /// \todo warn
- }
- }
- else
- {
- /// \todo warn
- }
- }
- strcpy(request + 8, GetSocks4Userid().c_str());
- size_t length = GetSocks4Userid().size() + 8 + 1;
- SendBuf(request, length);
- m_socks4_state = 0;
+ char request[1000];
+ memset(request, 0, sizeof(request));
+ request[0] = 4; // socks v4
+ request[1] = 1; // command code: CONNECT
+ {
+ std::auto_ptr<SocketAddress> ad = GetClientRemoteAddress();
+ if (ad.get())
+ {
+ struct sockaddr *p0 = (struct sockaddr *)*ad;
+ struct sockaddr_in *p = (struct sockaddr_in *)p0;
+ if (p -> sin_family == AF_INET)
+ {
+ memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here
+ memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr));
+ }
+ else
+ {
+ /// \todo warn
+ }
+ }
+ else
+ {
+ /// \todo warn
+ }
+ }
+ strcpy(request + 8, GetSocks4Userid().c_str());
+ size_t length = GetSocks4Userid().size() + 8 + 1;
+ SendBuf(request, length);
+ m_socks4_state = 0;
}
void TcpSocket::OnSocks4ConnectFailed()
{
- Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING);
- if (!Handler().Socks4TryDirect())
- {
- SetConnecting(false);
- SetCloseAndDelete();
- OnConnectFailed(); // just in case
- }
- else
- {
- SetRetryClientConnect();
- }
+ Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING);
+ if (!Handler().Socks4TryDirect())
+ {
+ SetConnecting(false);
+ SetCloseAndDelete();
+ OnConnectFailed(); // just in case
+ }
+ else
+ {
+ SetRetryClientConnect();
+ }
}
bool TcpSocket::OnSocks4Read()
{
- switch (m_socks4_state)
- {
- case 0:
- ibuf.Read(&m_socks4_vn, 1);
- m_socks4_state = 1;
- break;
- case 1:
- ibuf.Read(&m_socks4_cd, 1);
- m_socks4_state = 2;
- break;
- case 2:
- if (GetInputLength() > 1)
- {
- ibuf.Read( (char *)&m_socks4_dstport, 2);
- m_socks4_state = 3;
- }
- else
- {
- return true;
- }
- break;
- case 3:
- if (GetInputLength() > 3)
- {
- ibuf.Read( (char *)&m_socks4_dstip, 4);
- SetSocks4(false);
-
- switch (m_socks4_cd)
- {
- case 90:
- OnConnect();
- Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO);
- break;
- case 91:
- case 92:
- case 93:
- Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL);
- SetConnecting(false);
- SetCloseAndDelete();
- OnConnectFailed();
- break;
- default:
- Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- break;
- }
- }
- else
- {
- return true;
- }
- break;
- }
- return false;
+ switch (m_socks4_state)
+ {
+ case 0:
+ ibuf.Read(&m_socks4_vn, 1);
+ m_socks4_state = 1;
+ break;
+ case 1:
+ ibuf.Read(&m_socks4_cd, 1);
+ m_socks4_state = 2;
+ break;
+ case 2:
+ if (GetInputLength() > 1)
+ {
+ ibuf.Read( (char *)&m_socks4_dstport, 2);
+ m_socks4_state = 3;
+ }
+ else
+ {
+ return true;
+ }
+ break;
+ case 3:
+ if (GetInputLength() > 3)
+ {
+ ibuf.Read( (char *)&m_socks4_dstip, 4);
+ SetSocks4(false);
+
+ switch (m_socks4_cd)
+ {
+ case 90:
+ OnConnect();
+ Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO);
+ break;
+ case 91:
+ case 92:
+ case 93:
+ Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL);
+ SetConnecting(false);
+ SetCloseAndDelete();
+ OnConnectFailed();
+ break;
+ default:
+ Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ break;
+ }
+ }
+ else
+ {
+ return true;
+ }
+ break;
+ }
+ return false;
}
#endif
void TcpSocket::Sendf(const char *format, ...)
{
- va_list ap;
- va_start(ap, format);
- char slask[5000]; // vsprintf / vsnprintf temporary
+ va_list ap;
+ va_start(ap, format);
+ char slask[5000]; // vsprintf / vsnprintf temporary
#ifdef _WIN32
- vsprintf(slask, format, ap);
+ vsprintf(slask, format, ap);
#else
- vsnprintf(slask, 5000, format, ap);
+ vsnprintf(slask, 5000, format, ap);
#endif
- va_end(ap);
- Send( slask );
+ va_end(ap);
+ Send( slask );
}
#ifdef HAVE_OPENSSL
void TcpSocket::OnSSLConnect()
{
- SetNonblocking(true);
- {
- if (m_ssl_ctx)
- {
-DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
- SetCloseAndDelete(true);
- return;
- }
- InitSSLClient();
- }
- if (m_ssl_ctx)
- {
- /* Connect the SSL socket */
- m_ssl = SSL_new(m_ssl_ctx);
- if (!m_ssl)
- {
-DEB( fprintf(stderr, " m_ssl is NULL\n");)
- SetCloseAndDelete(true);
- return;
- }
- SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
- m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
- if (!m_sbio)
- {
-DEB( fprintf(stderr, " m_sbio is NULL\n");)
- SetCloseAndDelete(true);
- return;
- }
- SSL_set_bio(m_ssl, m_sbio, m_sbio);
- if (!SSLNegotiate())
- {
- SetSSLNegotiate();
- }
- }
- else
- {
- SetCloseAndDelete();
- }
+ SetNonblocking(true);
+ {
+ if (m_ssl_ctx)
+ {
+DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ InitSSLClient();
+ }
+ if (m_ssl_ctx)
+ {
+ /* Connect the SSL socket */
+ m_ssl = SSL_new(m_ssl_ctx);
+ if (!m_ssl)
+ {
+DEB( fprintf(stderr, " m_ssl is NULL\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
+ m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
+ if (!m_sbio)
+ {
+DEB( fprintf(stderr, " m_sbio is NULL\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ SSL_set_bio(m_ssl, m_sbio, m_sbio);
+ if (!SSLNegotiate())
+ {
+ SetSSLNegotiate();
+ }
+ }
+ else
+ {
+ SetCloseAndDelete();
+ }
}
void TcpSocket::OnSSLAccept()
{
- SetNonblocking(true);
- {
- if (m_ssl_ctx)
- {
-DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
- SetCloseAndDelete(true);
- return;
- }
- InitSSLServer();
- SetSSLServer();
- }
- if (m_ssl_ctx)
- {
- m_ssl = SSL_new(m_ssl_ctx);
- if (!m_ssl)
- {
-DEB( fprintf(stderr, " m_ssl is NULL\n");)
- SetCloseAndDelete(true);
- return;
- }
- SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
- m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
- if (!m_sbio)
- {
-DEB( fprintf(stderr, " m_sbio is NULL\n");)
- SetCloseAndDelete(true);
- return;
- }
- SSL_set_bio(m_ssl, m_sbio, m_sbio);
-// if (!SSLNegotiate())
- {
- SetSSLNegotiate();
- }
- }
+ SetNonblocking(true);
+ {
+ if (m_ssl_ctx)
+ {
+DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ InitSSLServer();
+ SetSSLServer();
+ }
+ if (m_ssl_ctx)
+ {
+ m_ssl = SSL_new(m_ssl_ctx);
+ if (!m_ssl)
+ {
+DEB( fprintf(stderr, " m_ssl is NULL\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
+ m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE);
+ if (!m_sbio)
+ {
+DEB( fprintf(stderr, " m_sbio is NULL\n");)
+ SetCloseAndDelete(true);
+ return;
+ }
+ SSL_set_bio(m_ssl, m_sbio, m_sbio);
+// if (!SSLNegotiate())
+ {
+ SetSSLNegotiate();
+ }
+ }
}
bool TcpSocket::SSLNegotiate()
{
- if (!IsSSLServer()) // client
- {
- int r = SSL_connect(m_ssl);
- if (r > 0)
- {
- SetSSLNegotiate(false);
- /// \todo: resurrect certificate check... client
-// CheckCertificateChain( "");//ServerHOST);
- SetNonblocking(false);
- //
- {
- SetConnected();
- if (GetOutputLength())
- {
- OnWrite();
- }
- }
+ if (!IsSSLServer()) // client
+ {
+ int r = SSL_connect(m_ssl);
+ if (r > 0)
+ {
+ SetSSLNegotiate(false);
+ /// \todo: resurrect certificate check... client
+// CheckCertificateChain( "");//ServerHOST);
+ SetNonblocking(false);
+ //
+ {
+ SetConnected();
+ if (GetOutputLength())
+ {
+ OnWrite();
+ }
+ }
#ifdef ENABLE_RECONNECT
- if (IsReconnect())
- OnReconnect();
- else
+ if (IsReconnect())
+ OnReconnect();
+ else
#endif
- {
- OnConnect();
- }
- Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO);
- return true;
- }
- else
- if (!r)
- {
- Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO);
- SetSSLNegotiate(false);
- SetCloseAndDelete();
- OnSSLConnectFailed();
- }
- else
- {
- r = SSL_get_error(m_ssl, r);
- if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
- {
- Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO);
-DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);)
- SetSSLNegotiate(false);
- SetCloseAndDelete(true);
- OnSSLConnectFailed();
- }
- }
- }
- else // server
- {
- int r = SSL_accept(m_ssl);
- if (r > 0)
- {
- SetSSLNegotiate(false);
- /// \todo: resurrect certificate check... server
-// CheckCertificateChain( "");//ClientHOST);
- SetNonblocking(false);
- //
- {
- SetConnected();
- if (GetOutputLength())
- {
- OnWrite();
- }
- }
- OnAccept();
- Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO);
- return true;
- }
- else
- if (!r)
- {
- Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO);
- SetSSLNegotiate(false);
- SetCloseAndDelete();
- OnSSLAcceptFailed();
- }
- else
- {
- r = SSL_get_error(m_ssl, r);
- if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
- {
- Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO);
-DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);)
- SetSSLNegotiate(false);
- SetCloseAndDelete(true);
- OnSSLAcceptFailed();
- }
- }
- }
- return false;
+ {
+ OnConnect();
+ }
+ Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO);
+ return true;
+ }
+ else
+ if (!r)
+ {
+ Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO);
+ SetSSLNegotiate(false);
+ SetCloseAndDelete();
+ OnSSLConnectFailed();
+ }
+ else
+ {
+ r = SSL_get_error(m_ssl, r);
+ if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
+ {
+ Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO);
+DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);)
+ SetSSLNegotiate(false);
+ SetCloseAndDelete(true);
+ OnSSLConnectFailed();
+ }
+ }
+ }
+ else // server
+ {
+ int r = SSL_accept(m_ssl);
+ if (r > 0)
+ {
+ SetSSLNegotiate(false);
+ /// \todo: resurrect certificate check... server
+// CheckCertificateChain( "");//ClientHOST);
+ SetNonblocking(false);
+ //
+ {
+ SetConnected();
+ if (GetOutputLength())
+ {
+ OnWrite();
+ }
+ }
+ OnAccept();
+ Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO);
+ return true;
+ }
+ else
+ if (!r)
+ {
+ Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO);
+ SetSSLNegotiate(false);
+ SetCloseAndDelete();
+ OnSSLAcceptFailed();
+ }
+ else
+ {
+ r = SSL_get_error(m_ssl, r);
+ if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
+ {
+ Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO);
+DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);)
+ SetSSLNegotiate(false);
+ SetCloseAndDelete(true);
+ OnSSLAcceptFailed();
+ }
+ }
+ }
+ return false;
}
void TcpSocket::InitSSLClient()
{
- InitializeContext("", SSLv23_method());
+ InitializeContext("", SSLv23_method());
}
void TcpSocket::InitSSLServer()
{
- Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
}
void TcpSocket::InitializeContext(const std::string& context, SSL_METHOD *meth_in)
{
- /* Create our context*/
- static std::map<std::string, SSL_CTX *> client_contexts;
- if (client_contexts.find(context) == client_contexts.end())
- {
- SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
- m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth);
- SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
- }
- else
- {
- m_ssl_ctx = client_contexts[context];
- }
+ /* Create our context*/
+ static std::map<std::string, SSL_CTX *> client_contexts;
+ if (client_contexts.find(context) == client_contexts.end())
+ {
+ SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
+ m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth);
+ SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
+ }
+ else
+ {
+ m_ssl_ctx = client_contexts[context];
+ }
}
void TcpSocket::InitializeContext(const std::string& context,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in)
{
- /* Create our context*/
- static std::map<std::string, SSL_CTX *> server_contexts;
- if (server_contexts.find(context) == server_contexts.end())
- {
- SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
- m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
- SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
- // session id
- if (!context.empty())
- SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
- else
- SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
- }
- else
- {
- m_ssl_ctx = server_contexts[context];
- }
-
- /* Load our keys and certificates*/
- if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
- {
- Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
- }
-
- m_password = password;
- SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
- SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
- if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
- {
- Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
- }
+ /* Create our context*/
+ static std::map<std::string, SSL_CTX *> server_contexts;
+ if (server_contexts.find(context) == server_contexts.end())
+ {
+ SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
+ m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
+ SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
+ // session id
+ if (!context.empty())
+ SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
+ else
+ SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
+ }
+ else
+ {
+ m_ssl_ctx = server_contexts[context];
+ }
+
+ /* Load our keys and certificates*/
+ if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
+ {
+ Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
+ }
+
+ m_password = password;
+ SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
+ SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
+ if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
+ {
+ Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
+ }
}
void TcpSocket::InitializeContext(const std::string& context,const std::string& certfile,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in)
{
- /* Create our context*/
- static std::map<std::string, SSL_CTX *> server_contexts;
- if (server_contexts.find(context) == server_contexts.end())
- {
- SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
- m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
- SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
- // session id
- if (context.size())
- SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
- else
- SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
- }
- else
- {
- m_ssl_ctx = server_contexts[context];
- }
-
- /* Load our keys and certificates*/
- if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM)))
- {
- Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
- }
-
- m_password = password;
- SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
- SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
- if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
- {
- Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
- }
+ /* Create our context*/
+ static std::map<std::string, SSL_CTX *> server_contexts;
+ if (server_contexts.find(context) == server_contexts.end())
+ {
+ SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method();
+ m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth);
+ SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY);
+ // session id
+ if (context.size())
+ SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size());
+ else
+ SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9);
+ }
+ else
+ {
+ m_ssl_ctx = server_contexts[context];
+ }
+
+ /* Load our keys and certificates*/
+ if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM)))
+ {
+ Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL);
+ }
+
+ m_password = password;
+ SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb);
+ SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this);
+ if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM)))
+ {
+ Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL);
+ }
}
int TcpSocket::SSL_password_cb(char *buf,int num,int rwflag,void *userdata)
{
- Socket *p0 = static_cast<Socket *>(userdata);
- TcpSocket *p = dynamic_cast<TcpSocket *>(p0);
- std::string pw = p ? p -> GetPassword() : "";
- if ( (size_t)num < pw.size() + 1)
- {
- return 0;
- }
- strcpy(buf,pw.c_str());
- return (int)pw.size();
+ Socket *p0 = static_cast<Socket *>(userdata);
+ TcpSocket *p = dynamic_cast<TcpSocket *>(p0);
+ std::string pw = p ? p -> GetPassword() : "";
+ if ( (size_t)num < pw.size() + 1)
+ {
+ return 0;
+ }
+ strcpy(buf,pw.c_str());
+ return (int)pw.size();
}
#endif // HAVE_OPENSSL
int TcpSocket::Close()
{
- if (GetSocket() == INVALID_SOCKET) // this could happen
- {
- Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING);
- return 0;
- }
- int n;
- SetNonblocking(true);
- if (!Lost() && IsConnected() && !(GetShutdown() & SHUT_WR))
- {
- if (shutdown(GetSocket(), SHUT_WR) == -1)
- {
- // failed...
- Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- }
- //
- char tmp[1000];
- if (!Lost() && (n = recv(GetSocket(),tmp,1000,0)) >= 0)
- {
- if (n)
- {
- Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING);
- }
- }
+ if (GetSocket() == INVALID_SOCKET) // this could happen
+ {
+ Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING);
+ return 0;
+ }
+ int n;
+ SetNonblocking(true);
+ if (!Lost() && IsConnected() && !(GetShutdown() & SHUT_WR))
+ {
+ if (shutdown(GetSocket(), SHUT_WR) == -1)
+ {
+ // failed...
+ Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ }
+ //
+ char tmp[1000];
+ if (!Lost() && (n = recv(GetSocket(),tmp,1000,0)) >= 0)
+ {
+ if (n)
+ {
+ Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING);
+ }
+ }
#ifdef HAVE_OPENSSL
- if (IsSSL() && m_ssl)
- SSL_shutdown(m_ssl);
- if (m_ssl)
- {
- SSL_free(m_ssl);
- m_ssl = NULL;
- }
+ if (IsSSL() && m_ssl)
+ SSL_shutdown(m_ssl);
+ if (m_ssl)
+ {
+ SSL_free(m_ssl);
+ m_ssl = NULL;
+ }
#endif
- return Socket::Close();
+ return Socket::Close();
}
#ifdef HAVE_OPENSSL
SSL_CTX *TcpSocket::GetSslContext()
{
- if (!m_ssl_ctx)
- Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
- return m_ssl_ctx;
+ if (!m_ssl_ctx)
+ Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
+ return m_ssl_ctx;
}
SSL *TcpSocket::GetSsl()
{
- if (!m_ssl)
- Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
- return m_ssl;
+ if (!m_ssl)
+ Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING);
+ return m_ssl;
}
#endif
@@ -1375,7 +1375,7 @@ SSL *TcpSocket::GetSsl()
#ifdef ENABLE_RECONNECT
void TcpSocket::SetReconnect(bool x)
{
- m_b_reconnect = x;
+ m_b_reconnect = x;
}
#endif
@@ -1387,50 +1387,50 @@ void TcpSocket::OnRawData(const char *buf_in,size_t len)
size_t TcpSocket::GetInputLength()
{
- return ibuf.GetLength();
+ return ibuf.GetLength();
}
size_t TcpSocket::GetOutputLength()
{
- return m_output_length;
+ return m_output_length;
}
uint64_t TcpSocket::GetBytesReceived(bool clear)
{
- uint64_t z = m_bytes_received;
- if (clear)
- m_bytes_received = 0;
- return z;
+ uint64_t z = m_bytes_received;
+ if (clear)
+ m_bytes_received = 0;
+ return z;
}
uint64_t TcpSocket::GetBytesSent(bool clear)
{
- uint64_t z = m_bytes_sent;
- if (clear)
- m_bytes_sent = 0;
- return z;
+ uint64_t z = m_bytes_sent;
+ if (clear)
+ m_bytes_sent = 0;
+ return z;
}
#ifdef ENABLE_RECONNECT
bool TcpSocket::Reconnect()
{
- return m_b_reconnect;
+ return m_b_reconnect;
}
void TcpSocket::SetIsReconnect(bool x)
{
- m_b_is_reconnect = x;
+ m_b_is_reconnect = x;
}
bool TcpSocket::IsReconnect()
{
- return m_b_is_reconnect;
+ return m_b_is_reconnect;
}
#endif
@@ -1438,48 +1438,48 @@ bool TcpSocket::IsReconnect()
#ifdef HAVE_OPENSSL
const std::string& TcpSocket::GetPassword()
{
- return m_password;
+ return m_password;
}
#endif
void TcpSocket::DisableInputBuffer(bool x)
{
- m_b_input_buffer_disabled = x;
+ m_b_input_buffer_disabled = x;
}
void TcpSocket::OnOptions(int family,int type,int protocol,SOCKET s)
{
-DEB( fprintf(stderr, "Socket::OnOptions()\n");)
+DEB( fprintf(stderr, "Socket::OnOptions()\n");)
#ifdef SO_NOSIGPIPE
- SetSoNosigpipe(true);
+ SetSoNosigpipe(true);
#endif
- SetSoReuseaddr(true);
- SetSoKeepalive(true);
+ SetSoReuseaddr(true);
+ SetSoKeepalive(true);
}
void TcpSocket::SetLineProtocol(bool x)
{
- StreamSocket::SetLineProtocol(x);
- DisableInputBuffer(x);
+ StreamSocket::SetLineProtocol(x);
+ DisableInputBuffer(x);
}
bool TcpSocket::SetTcpNodelay(bool x)
{
#ifdef TCP_NODELAY
- int optval = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1)
- {
- Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- return false;
- }
- return true;
+ int optval = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1)
+ {
+ Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ return false;
+ }
+ return true;
#else
- Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO);
- return false;
+ Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO);
+ return false;
#endif
}
@@ -1497,73 +1497,73 @@ TcpSocket::CircularBuffer::CircularBuffer(size_t size)
TcpSocket::CircularBuffer::~CircularBuffer()
{
- delete[] buf;
+ delete[] buf;
}
bool TcpSocket::CircularBuffer::Write(const char *s,size_t l)
{
- if (m_q + l > m_max)
- {
- return false; // overflow
- }
- m_count += (unsigned long)l;
- if (m_t + l > m_max) // block crosses circular border
- {
- size_t l1 = m_max - m_t; // size left until circular border crossing
- // always copy full block to buffer(buf) + top pointer(m_t)
- // because we have doubled the buffer size for performance reasons
- memcpy(buf + m_t, s, l);
- memcpy(buf, s + l1, l - l1);
- m_t = l - l1;
- m_q += l;
- }
- else
- {
- memcpy(buf + m_t, s, l);
- memcpy(buf + m_max + m_t, s, l);
- m_t += l;
- if (m_t >= m_max)
- m_t -= m_max;
- m_q += l;
- }
- return true;
+ if (m_q + l > m_max)
+ {
+ return false; // overflow
+ }
+ m_count += (unsigned long)l;
+ if (m_t + l > m_max) // block crosses circular border
+ {
+ size_t l1 = m_max - m_t; // size left until circular border crossing
+ // always copy full block to buffer(buf) + top pointer(m_t)
+ // because we have doubled the buffer size for performance reasons
+ memcpy(buf + m_t, s, l);
+ memcpy(buf, s + l1, l - l1);
+ m_t = l - l1;
+ m_q += l;
+ }
+ else
+ {
+ memcpy(buf + m_t, s, l);
+ memcpy(buf + m_max + m_t, s, l);
+ m_t += l;
+ if (m_t >= m_max)
+ m_t -= m_max;
+ m_q += l;
+ }
+ return true;
}
bool TcpSocket::CircularBuffer::Read(char *s,size_t l)
{
- if (l > m_q)
- {
- return false; // not enough chars
- }
- if (m_b + l > m_max) // block crosses circular border
- {
- size_t l1 = m_max - m_b;
- if (s)
- {
- memcpy(s, buf + m_b, l1);
- memcpy(s + l1, buf, l - l1);
- }
- m_b = l - l1;
- m_q -= l;
- }
- else
- {
- if (s)
- {
- memcpy(s, buf + m_b, l);
- }
- m_b += l;
- if (m_b >= m_max)
- m_b -= m_max;
- m_q -= l;
- }
- if (!m_q)
- {
- m_b = m_t = 0;
- }
- return true;
+ if (l > m_q)
+ {
+ return false; // not enough chars
+ }
+ if (m_b + l > m_max) // block crosses circular border
+ {
+ size_t l1 = m_max - m_b;
+ if (s)
+ {
+ memcpy(s, buf + m_b, l1);
+ memcpy(s + l1, buf, l - l1);
+ }
+ m_b = l - l1;
+ m_q -= l;
+ }
+ else
+ {
+ if (s)
+ {
+ memcpy(s, buf + m_b, l);
+ }
+ m_b += l;
+ if (m_b >= m_max)
+ m_b -= m_max;
+ m_q -= l;
+ }
+ if (!m_q)
+ {
+ m_b = m_t = 0;
+ }
+ return true;
}
bool TcpSocket::CircularBuffer::SoftRead(char *s, size_t l)
@@ -1593,144 +1593,144 @@ bool TcpSocket::CircularBuffer::SoftRead(char *s, size_t l)
bool TcpSocket::CircularBuffer::Remove(size_t l)
{
- return Read(NULL, l);
+ return Read(NULL, l);
}
size_t TcpSocket::CircularBuffer::GetLength()
{
- return m_q;
+ return m_q;
}
const char *TcpSocket::CircularBuffer::GetStart()
{
- return buf + m_b;
+ return buf + m_b;
}
size_t TcpSocket::CircularBuffer::GetL()
{
- return (m_b + m_q > m_max) ? m_max - m_b : m_q;
+ return (m_b + m_q > m_max) ? m_max - m_b : m_q;
}
size_t TcpSocket::CircularBuffer::Space()
{
- return m_max - m_q;
+ return m_max - m_q;
}
unsigned long TcpSocket::CircularBuffer::ByteCounter(bool clear)
{
- if (clear)
- {
- unsigned long x = m_count;
- m_count = 0;
- return x;
- }
- return m_count;
+ if (clear)
+ {
+ unsigned long x = m_count;
+ m_count = 0;
+ return x;
+ }
+ return m_count;
}
std::string TcpSocket::CircularBuffer::ReadString(size_t l)
{
- char *sz = new char[l + 1];
- if (!Read(sz, l)) // failed, debug printout in Read() method
- {
- delete[] sz;
- return "";
- }
- sz[l] = 0;
- std::string tmp = sz;
- delete[] sz;
- return tmp;
+ char *sz = new char[l + 1];
+ if (!Read(sz, l)) // failed, debug printout in Read() method
+ {
+ delete[] sz;
+ return "";
+ }
+ sz[l] = 0;
+ std::string tmp = sz;
+ delete[] sz;
+ return tmp;
}
void TcpSocket::OnConnectTimeout()
{
- Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL);
+ Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL);
#ifdef ENABLE_SOCKS4
- if (Socks4())
- {
- OnSocks4ConnectFailed();
- // retry direct connection
- }
- else
+ if (Socks4())
+ {
+ OnSocks4ConnectFailed();
+ // retry direct connection
+ }
+ else
#endif
- if (GetConnectionRetry() == -1 ||
- (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
- {
- IncreaseConnectionRetries();
- // ask socket via OnConnectRetry callback if we should continue trying
- if (OnConnectRetry())
- {
- SetRetryClientConnect();
- }
- else
- {
- SetCloseAndDelete( true );
- /// \todo state reason why connect failed
- OnConnectFailed();
- }
- }
- else
- {
- SetCloseAndDelete(true);
- /// \todo state reason why connect failed
- OnConnectFailed();
- }
- //
- SetConnecting(false);
+ if (GetConnectionRetry() == -1 ||
+ (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) )
+ {
+ IncreaseConnectionRetries();
+ // ask socket via OnConnectRetry callback if we should continue trying
+ if (OnConnectRetry())
+ {
+ SetRetryClientConnect();
+ }
+ else
+ {
+ SetCloseAndDelete( true );
+ /// \todo state reason why connect failed
+ OnConnectFailed();
+ }
+ }
+ else
+ {
+ SetCloseAndDelete(true);
+ /// \todo state reason why connect failed
+ OnConnectFailed();
+ }
+ //
+ SetConnecting(false);
}
#ifdef _WIN32
void TcpSocket::OnException()
{
- if (Connecting())
- {
+ if (Connecting())
+ {
#ifdef ENABLE_SOCKS4
- if (Socks4())
- OnSocks4ConnectFailed();
- else
+ if (Socks4())
+ OnSocks4ConnectFailed();
+ else
#endif
- if (GetConnectionRetry() == -1 ||
- (GetConnectionRetry() &&
- GetConnectionRetries() < GetConnectionRetry() ))
- {
- // even though the connection failed at once, only retry after
- // the connection timeout
- // should we even try to connect again, when CheckConnect returns
- // false it's because of a connection error - not a timeout...
- }
- else
- {
- SetConnecting(false); // tnx snibbe
- SetCloseAndDelete();
- OnConnectFailed();
- }
- return;
- }
- // %! exception doesn't always mean something bad happened, this code should be reworked
- // errno valid here?
- int err = SoError();
- Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ if (GetConnectionRetry() == -1 ||
+ (GetConnectionRetry() &&
+ GetConnectionRetries() < GetConnectionRetry() ))
+ {
+ // even though the connection failed at once, only retry after
+ // the connection timeout
+ // should we even try to connect again, when CheckConnect returns
+ // false it's because of a connection error - not a timeout...
+ }
+ else
+ {
+ SetConnecting(false); // tnx snibbe
+ SetCloseAndDelete();
+ OnConnectFailed();
+ }
+ return;
+ }
+ // %! exception doesn't always mean something bad happened, this code should be reworked
+ // errno valid here?
+ int err = SoError();
+ Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
}
#endif // _WIN32
int TcpSocket::Protocol()
{
- return IPPROTO_TCP;
+ return IPPROTO_TCP;
}
void TcpSocket::SetTransferLimit(size_t sz)
{
- m_transfer_limit = sz;
+ m_transfer_limit = sz;
}
diff --git a/dep/src/sockets/Thread.cpp b/dep/src/sockets/Thread.cpp
index 2717e32d016..e1834ab4a87 100644
--- a/dep/src/sockets/Thread.cpp
+++ b/dep/src/sockets/Thread.cpp
@@ -1,6 +1,6 @@
/** \file Thread.cpp
- ** \date 2004-10-30
- ** \author grymse@alhem.net
+ ** \date 2004-10-30
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -51,111 +51,111 @@ Thread::Thread(bool release)
,m_b_destructor(false)
{
#ifdef _WIN32
-// m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId);
- m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId);
+// m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId);
+ m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId);
#else
- pthread_attr_t attr;
-
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
- if (pthread_create(&m_thread,&attr, StartThread,this) == -1)
- {
- perror("Thread: create failed");
- SetRunning(false);
- }
-// pthread_attr_destroy(&attr);
+ pthread_attr_t attr;
+
+ pthread_attr_init(&attr);
+ pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
+ if (pthread_create(&m_thread,&attr, StartThread,this) == -1)
+ {
+ perror("Thread: create failed");
+ SetRunning(false);
+ }
+// pthread_attr_destroy(&attr);
#endif
- m_release = release;
+ m_release = release;
}
Thread::~Thread()
{
- m_b_destructor = true;
- if (m_running)
- {
- SetRelease(true);
- SetRunning(false);
+ m_b_destructor = true;
+ if (m_running)
+ {
+ SetRelease(true);
+ SetRunning(false);
#ifdef _WIN32
- Sleep(1000);
+ Sleep(1000);
#else
- sleep(1);
+ sleep(1);
#endif
- }
+ }
#ifdef _WIN32
- if (m_thread)
- ::CloseHandle(m_thread);
+ if (m_thread)
+ ::CloseHandle(m_thread);
#endif
}
threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz)
{
- Thread *p = (Thread *)zz;
+ Thread *p = (Thread *)zz;
- while (p -> m_running && !p -> m_release)
- {
+ while (p -> m_running && !p -> m_release)
+ {
#ifdef _WIN32
- Sleep(1000);
+ Sleep(1000);
#else
- sleep(1);
+ sleep(1);
#endif
- }
- if (p -> m_running)
- {
- p -> Run();
- }
- p -> SetRunning(false); // if return
- if (p -> DeleteOnExit() && !p -> IsDestructor())
- {
- delete p;
- }
+ }
+ if (p -> m_running)
+ {
+ p -> Run();
+ }
+ p -> SetRunning(false); // if return
+ if (p -> DeleteOnExit() && !p -> IsDestructor())
+ {
+ delete p;
+ }
#ifdef _WIN32
- _endthreadex(0);
+ _endthreadex(0);
#endif
- return (threadfunc_t)NULL;
+ return (threadfunc_t)NULL;
}
bool Thread::IsRunning()
{
- return m_running;
+ return m_running;
}
void Thread::SetRunning(bool x)
{
- m_running = x;
+ m_running = x;
}
bool Thread::IsReleased()
{
- return m_release;
+ return m_release;
}
void Thread::SetRelease(bool x)
{
- m_release = x;
+ m_release = x;
}
bool Thread::DeleteOnExit()
{
- return m_b_delete_on_exit;
+ return m_b_delete_on_exit;
}
void Thread::SetDeleteOnExit(bool x)
{
- m_b_delete_on_exit = x;
+ m_b_delete_on_exit = x;
}
bool Thread::IsDestructor()
{
- return m_b_destructor;
+ return m_b_destructor;
}
diff --git a/dep/src/sockets/UdpSocket.cpp b/dep/src/sockets/UdpSocket.cpp
index 5d949496b25..229a26414e5 100644
--- a/dep/src/sockets/UdpSocket.cpp
+++ b/dep/src/sockets/UdpSocket.cpp
@@ -1,6 +1,6 @@
/** \file UdpSocket.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -64,7 +64,7 @@ UdpSocket::UdpSocket(ISocketHandler& h, int ibufsz, bool ipv6, int retries) : So
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- SetIpv6(ipv6);
+ SetIpv6(ipv6);
#endif
#endif
}
@@ -72,8 +72,8 @@ UdpSocket::UdpSocket(ISocketHandler& h, int ibufsz, bool ipv6, int retries) : So
UdpSocket::~UdpSocket()
{
- Close();
- delete[] m_ibuf;
+ Close();
+ delete[] m_ibuf;
}
@@ -81,15 +81,15 @@ int UdpSocket::Bind(port_t &port, int range)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- Ipv6Address ad(port);
- return Bind(ad, range);
- }
+ if (IsIpv6())
+ {
+ Ipv6Address ad(port);
+ return Bind(ad, range);
+ }
#endif
#endif
- Ipv4Address ad(port);
- return Bind(ad, range);
+ Ipv4Address ad(port);
+ return Bind(ad, range);
}
@@ -97,32 +97,32 @@ int UdpSocket::Bind(const std::string& intf, port_t &port, int range)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- Ipv6Address ad(intf, port);
- if (ad.IsValid())
- {
- return Bind(ad, range);
- }
- SetCloseAndDelete();
- return -1;
- }
+ if (IsIpv6())
+ {
+ Ipv6Address ad(intf, port);
+ if (ad.IsValid())
+ {
+ return Bind(ad, range);
+ }
+ SetCloseAndDelete();
+ return -1;
+ }
#endif
#endif
- Ipv4Address ad(intf, port);
- if (ad.IsValid())
- {
- return Bind(ad, range);
- }
- SetCloseAndDelete();
- return -1;
+ Ipv4Address ad(intf, port);
+ if (ad.IsValid())
+ {
+ return Bind(ad, range);
+ }
+ SetCloseAndDelete();
+ return -1;
}
int UdpSocket::Bind(ipaddr_t a, port_t &port, int range)
{
- Ipv4Address ad(a, port);
- return Bind(ad, range);
+ Ipv4Address ad(a, port);
+ return Bind(ad, range);
}
@@ -130,8 +130,8 @@ int UdpSocket::Bind(ipaddr_t a, port_t &port, int range)
#ifdef IPPROTO_IPV6
int UdpSocket::Bind(in6_addr a, port_t &port, int range)
{
- Ipv6Address ad(a, port);
- return Bind(ad, range);
+ Ipv6Address ad(a, port);
+ return Bind(ad, range);
}
#endif
#endif
@@ -139,42 +139,42 @@ int UdpSocket::Bind(in6_addr a, port_t &port, int range)
int UdpSocket::Bind(SocketAddress& ad, int range)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
- }
- if (GetSocket() != INVALID_SOCKET)
- {
- SetNonblocking(true);
- int n = bind(GetSocket(), ad, ad);
- int tries = range;
- while (n == -1 && tries--)
- {
- ad.SetPort(ad.GetPort() + 1);
- n = bind(GetSocket(), ad, ad);
- }
- if (n == -1)
- {
- Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
+ }
+ if (GetSocket() != INVALID_SOCKET)
+ {
+ SetNonblocking(true);
+ int n = bind(GetSocket(), ad, ad);
+ int tries = range;
+ while (n == -1 && tries--)
+ {
+ ad.SetPort(ad.GetPort() + 1);
+ n = bind(GetSocket(), ad, ad);
+ }
+ if (n == -1)
+ {
+ Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
- throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range));
+ throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range));
#endif
- return -1;
- }
- m_bind_ok = true;
- m_port = ad.GetPort();
- return 0;
- }
- return -1;
+ return -1;
+ }
+ m_bind_ok = true;
+ m_port = ad.GetPort();
+ return 0;
+ }
+ return -1;
}
/** if you wish to use Send, first Open a connection */
bool UdpSocket::Open(ipaddr_t l, port_t port)
{
- Ipv4Address ad(l, port);
- return Open(ad);
+ Ipv4Address ad(l, port);
+ return Open(ad);
}
@@ -182,23 +182,23 @@ bool UdpSocket::Open(const std::string& host, port_t port)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- Ipv6Address ad(host, port);
- if (ad.IsValid())
- {
- return Open(ad);
- }
- return false;
- }
+ if (IsIpv6())
+ {
+ Ipv6Address ad(host, port);
+ if (ad.IsValid())
+ {
+ return Open(ad);
+ }
+ return false;
+ }
#endif
#endif
- Ipv4Address ad(host, port);
- if (ad.IsValid())
- {
- return Open(ad);
- }
- return false;
+ Ipv4Address ad(host, port);
+ if (ad.IsValid())
+ {
+ return Open(ad);
+ }
+ return false;
}
@@ -206,8 +206,8 @@ bool UdpSocket::Open(const std::string& host, port_t port)
#ifdef IPPROTO_IPV6
bool UdpSocket::Open(struct in6_addr& a, port_t port)
{
- Ipv6Address ad(a, port);
- return Open(ad);
+ Ipv6Address ad(a, port);
+ return Open(ad);
}
#endif
#endif
@@ -215,23 +215,23 @@ bool UdpSocket::Open(struct in6_addr& a, port_t port)
bool UdpSocket::Open(SocketAddress& ad)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
- }
- if (GetSocket() != INVALID_SOCKET)
- {
- SetNonblocking(true);
- if (connect(GetSocket(), ad, ad) == -1)
- {
- Handler().LogError(this, "connect", Errno, StrError(Errno), LOG_LEVEL_FATAL);
- SetCloseAndDelete();
- return false;
- }
- SetConnected();
- return true;
- }
- return false;
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
+ }
+ if (GetSocket() != INVALID_SOCKET)
+ {
+ SetNonblocking(true);
+ if (connect(GetSocket(), ad, ad) == -1)
+ {
+ Handler().LogError(this, "connect", Errno, StrError(Errno), LOG_LEVEL_FATAL);
+ SetCloseAndDelete();
+ return false;
+ }
+ SetConnected();
+ return true;
+ }
+ return false;
}
@@ -239,32 +239,32 @@ void UdpSocket::CreateConnection()
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- if (GetSocket() == INVALID_SOCKET)
- {
- SOCKET s = CreateSocket(AF_INET6, SOCK_DGRAM, "udp");
- if (s == INVALID_SOCKET)
- {
- return;
- }
- SetNonblocking(true, s);
- Attach(s);
- }
- return;
- }
-#endif
-#endif
- if (GetSocket() == INVALID_SOCKET)
- {
- SOCKET s = CreateSocket(AF_INET, SOCK_DGRAM, "udp");
- if (s == INVALID_SOCKET)
- {
- return;
- }
- SetNonblocking(true, s);
- Attach(s);
- }
+ if (IsIpv6())
+ {
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ SOCKET s = CreateSocket(AF_INET6, SOCK_DGRAM, "udp");
+ if (s == INVALID_SOCKET)
+ {
+ return;
+ }
+ SetNonblocking(true, s);
+ Attach(s);
+ }
+ return;
+ }
+#endif
+#endif
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ SOCKET s = CreateSocket(AF_INET, SOCK_DGRAM, "udp");
+ if (s == INVALID_SOCKET)
+ {
+ return;
+ }
+ SetNonblocking(true, s);
+ Attach(s);
+ }
}
@@ -273,30 +273,30 @@ void UdpSocket::SendToBuf(const std::string& h, port_t p, const char *data, int
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- Ipv6Address ad(h, p);
- if (ad.IsValid())
- {
- SendToBuf(ad, data, len, flags);
- }
- return;
- }
+ if (IsIpv6())
+ {
+ Ipv6Address ad(h, p);
+ if (ad.IsValid())
+ {
+ SendToBuf(ad, data, len, flags);
+ }
+ return;
+ }
#endif
#endif
- Ipv4Address ad(h, p);
- if (ad.IsValid())
- {
- SendToBuf(ad, data, len, flags);
- }
+ Ipv4Address ad(h, p);
+ if (ad.IsValid())
+ {
+ SendToBuf(ad, data, len, flags);
+ }
}
/** send to specified address */
void UdpSocket::SendToBuf(ipaddr_t a, port_t p, const char *data, int len, int flags)
{
- Ipv4Address ad(a, p);
- SendToBuf(ad, data, len, flags);
+ Ipv4Address ad(a, p);
+ SendToBuf(ad, data, len, flags);
}
@@ -304,8 +304,8 @@ void UdpSocket::SendToBuf(ipaddr_t a, port_t p, const char *data, int len, int f
#ifdef IPPROTO_IPV6
void UdpSocket::SendToBuf(in6_addr a, port_t p, const char *data, int len, int flags)
{
- Ipv6Address ad(a, p);
- SendToBuf(ad, data, len, flags);
+ Ipv6Address ad(a, p);
+ SendToBuf(ad, data, len, flags);
}
#endif
#endif
@@ -313,30 +313,30 @@ void UdpSocket::SendToBuf(in6_addr a, port_t p, const char *data, int len, int f
void UdpSocket::SendToBuf(SocketAddress& ad, const char *data, int len, int flags)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
- }
- if (GetSocket() != INVALID_SOCKET)
- {
- SetNonblocking(true);
- if ((m_last_size_written = sendto(GetSocket(), data, len, flags, ad, ad)) == -1)
- {
- Handler().LogError(this, "sendto", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
+ }
+ if (GetSocket() != INVALID_SOCKET)
+ {
+ SetNonblocking(true);
+ if ((m_last_size_written = sendto(GetSocket(), data, len, flags, ad, ad)) == -1)
+ {
+ Handler().LogError(this, "sendto", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ }
}
void UdpSocket::SendTo(const std::string& a, port_t p, const std::string& str, int flags)
{
- SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
+ SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
}
void UdpSocket::SendTo(ipaddr_t a, port_t p, const std::string& str, int flags)
{
- SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
+ SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
}
@@ -344,7 +344,7 @@ void UdpSocket::SendTo(ipaddr_t a, port_t p, const std::string& str, int flags)
#ifdef IPPROTO_IPV6
void UdpSocket::SendTo(in6_addr a, port_t p, const std::string& str, int flags)
{
- SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
+ SendToBuf(a, p, str.c_str(), (int)str.size(), flags);
}
#endif
#endif
@@ -352,93 +352,93 @@ void UdpSocket::SendTo(in6_addr a, port_t p, const std::string& str, int flags)
void UdpSocket::SendTo(SocketAddress& ad, const std::string& str, int flags)
{
- SendToBuf(ad, str.c_str(), (int)str.size(), flags);
+ SendToBuf(ad, str.c_str(), (int)str.size(), flags);
}
/** send to connected address */
void UdpSocket::SendBuf(const char *data, size_t len, int flags)
{
- if (!IsConnected())
- {
- Handler().LogError(this, "SendBuf", 0, "not connected", LOG_LEVEL_ERROR);
- return;
- }
- if ((m_last_size_written = send(GetSocket(), data, (int)len, flags)) == -1)
- {
- Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
+ if (!IsConnected())
+ {
+ Handler().LogError(this, "SendBuf", 0, "not connected", LOG_LEVEL_ERROR);
+ return;
+ }
+ if ((m_last_size_written = send(GetSocket(), data, (int)len, flags)) == -1)
+ {
+ Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
}
void UdpSocket::Send(const std::string& str, int flags)
{
- SendBuf(str.c_str(), (int)str.size(), flags);
+ SendBuf(str.c_str(), (int)str.size(), flags);
}
#if defined(LINUX) || defined(MACOSX)
int UdpSocket::ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts)
{
- struct msghdr msg;
- struct iovec vec[1];
- union {
- struct cmsghdr cm;
+ struct msghdr msg;
+ struct iovec vec[1];
+ union {
+ struct cmsghdr cm;
#ifdef MACOSX
#ifdef __DARWIN_UNIX03
#define ALIGNBYTES __DARWIN_ALIGNBYTES
#endif
#define myALIGN(p) (((unsigned int)(p) + ALIGNBYTES) &~ ALIGNBYTES)
#define myCMSG_SPACE(l) (myALIGN(sizeof(struct cmsghdr)) + myALIGN(l))
- char data[ myCMSG_SPACE(sizeof(struct timeval)) ];
+ char data[ myCMSG_SPACE(sizeof(struct timeval)) ];
#else
- char data[ CMSG_SPACE(sizeof(struct timeval)) ];
+ char data[ CMSG_SPACE(sizeof(struct timeval)) ];
#endif
- } cmsg_un;
- struct cmsghdr *cmsg;
- struct timeval *tv;
+ } cmsg_un;
+ struct cmsghdr *cmsg;
+ struct timeval *tv;
- vec[0].iov_base = ioBuf;
- vec[0].iov_len = inBufSize;
+ vec[0].iov_base = ioBuf;
+ vec[0].iov_len = inBufSize;
- memset(&msg, 0, sizeof(msg));
- memset(from, 0, fromlen);
- memset(ioBuf, 0, inBufSize);
- memset(&cmsg_un, 0, sizeof(cmsg_un));
+ memset(&msg, 0, sizeof(msg));
+ memset(from, 0, fromlen);
+ memset(ioBuf, 0, inBufSize);
+ memset(&cmsg_un, 0, sizeof(cmsg_un));
- msg.msg_name = (caddr_t)from;
- msg.msg_namelen = fromlen;
- msg.msg_iov = vec;
- msg.msg_iovlen = 1;
- msg.msg_control = cmsg_un.data;
- msg.msg_controllen = sizeof(cmsg_un.data);
- msg.msg_flags = 0;
+ msg.msg_name = (caddr_t)from;
+ msg.msg_namelen = fromlen;
+ msg.msg_iov = vec;
+ msg.msg_iovlen = 1;
+ msg.msg_control = cmsg_un.data;
+ msg.msg_controllen = sizeof(cmsg_un.data);
+ msg.msg_flags = 0;
- // Original version - for reference only
- //int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ // Original version - for reference only
+ //int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
- int n = recvmsg(GetSocket(), &msg, MSG_DONTWAIT);
+ int n = recvmsg(GetSocket(), &msg, MSG_DONTWAIT);
- // now ioBuf will contain the data, as if we used recvfrom
+ // now ioBuf will contain the data, as if we used recvfrom
- // Now get the time
- if(n != -1 && msg.msg_controllen >= sizeof(struct cmsghdr) && !(msg.msg_flags & MSG_CTRUNC))
- {
- tv = 0;
- for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg))
- {
- if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP)
- {
- tv = (struct timeval *)CMSG_DATA(cmsg);
- }
- }
- if (tv)
- {
- memcpy(ts, tv, sizeof(struct timeval));
- }
- }
- // The address is in network order, but that's OK right now
- return n;
+ // Now get the time
+ if(n != -1 && msg.msg_controllen >= sizeof(struct cmsghdr) && !(msg.msg_flags & MSG_CTRUNC))
+ {
+ tv = 0;
+ for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg))
+ {
+ if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP)
+ {
+ tv = (struct timeval *)CMSG_DATA(cmsg);
+ }
+ }
+ if (tv)
+ {
+ memcpy(ts, tv, sizeof(struct timeval));
+ }
+ }
+ // The address is in network order, but that's OK right now
+ return n;
}
#endif
@@ -447,324 +447,324 @@ void UdpSocket::OnRead()
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- struct sockaddr_in6 sa;
- socklen_t sa_len = sizeof(sa);
- if (m_b_read_ts)
- {
- struct timeval ts;
- Utility::GetTime(&ts);
+ if (IsIpv6())
+ {
+ struct sockaddr_in6 sa;
+ socklen_t sa_len = sizeof(sa);
+ if (m_b_read_ts)
+ {
+ struct timeval ts;
+ Utility::GetTime(&ts);
#if !defined(LINUX) && !defined(MACOSX)
- int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
#else
- int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts);
-#endif
- if (n > 0)
- {
- this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts);
- }
- else
- if (n == -1)
- {
+ int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts);
+#endif
+ if (n > 0)
+ {
+ this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts);
+ }
+ else
+ if (n == -1)
+ {
#ifdef _WIN32
- if (Errno != WSAEWOULDBLOCK)
+ if (Errno != WSAEWOULDBLOCK)
#else
- if (Errno != EWOULDBLOCK)
-#endif
- Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- return;
- }
- int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
- int q = m_retries; // receive max 10 at one cycle
- while (n > 0)
- {
- if (sa_len != sizeof(sa))
- {
- Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING);
- }
- this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len);
- if (!q--)
- break;
- //
- n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
- }
- if (n == -1)
- {
+ if (Errno != EWOULDBLOCK)
+#endif
+ Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ return;
+ }
+ int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ int q = m_retries; // receive max 10 at one cycle
+ while (n > 0)
+ {
+ if (sa_len != sizeof(sa))
+ {
+ Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING);
+ }
+ this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len);
+ if (!q--)
+ break;
+ //
+ n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ }
+ if (n == -1)
+ {
#ifdef _WIN32
- if (Errno != WSAEWOULDBLOCK)
+ if (Errno != WSAEWOULDBLOCK)
#else
- if (Errno != EWOULDBLOCK)
+ if (Errno != EWOULDBLOCK)
#endif
- Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- return;
- }
+ Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ return;
+ }
#endif
#endif
- struct sockaddr_in sa;
- socklen_t sa_len = sizeof(sa);
- if (m_b_read_ts)
- {
- struct timeval ts;
- Utility::GetTime(&ts);
+ struct sockaddr_in sa;
+ socklen_t sa_len = sizeof(sa);
+ if (m_b_read_ts)
+ {
+ struct timeval ts;
+ Utility::GetTime(&ts);
#if !defined(LINUX) && !defined(MACOSX)
- int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
#else
- int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts);
-#endif
- if (n > 0)
- {
- this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts);
- }
- else
- if (n == -1)
- {
+ int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts);
+#endif
+ if (n > 0)
+ {
+ this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts);
+ }
+ else
+ if (n == -1)
+ {
#ifdef _WIN32
- if (Errno != WSAEWOULDBLOCK)
+ if (Errno != WSAEWOULDBLOCK)
#else
- if (Errno != EWOULDBLOCK)
-#endif
- Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
- return;
- }
- int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
- int q = m_retries;
- while (n > 0)
- {
- if (sa_len != sizeof(sa))
- {
- Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING);
- }
- this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len);
- if (!q--)
- break;
- //
- n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
- }
- if (n == -1)
- {
+ if (Errno != EWOULDBLOCK)
+#endif
+ Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
+ return;
+ }
+ int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ int q = m_retries;
+ while (n > 0)
+ {
+ if (sa_len != sizeof(sa))
+ {
+ Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING);
+ }
+ this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len);
+ if (!q--)
+ break;
+ //
+ n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len);
+ }
+ if (n == -1)
+ {
#ifdef _WIN32
- if (Errno != WSAEWOULDBLOCK)
+ if (Errno != WSAEWOULDBLOCK)
#else
- if (Errno != EWOULDBLOCK)
+ if (Errno != EWOULDBLOCK)
#endif
- Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
- }
+ Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR);
+ }
}
void UdpSocket::SetBroadcast(bool b)
{
- int one = 1;
- int zero = 0;
-
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (b)
- {
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof(one)) == -1)
- {
- Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
- else
- {
- if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &zero, sizeof(zero)) == -1)
- {
- Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
+ int one = 1;
+ int zero = 0;
+
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (b)
+ {
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof(one)) == -1)
+ {
+ Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
+ else
+ {
+ if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &zero, sizeof(zero)) == -1)
+ {
+ Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
}
bool UdpSocket::IsBroadcast()
{
- int is_broadcast = 0;
- socklen_t size;
+ int is_broadcast = 0;
+ socklen_t size;
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1)
- {
- Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return is_broadcast != 0;
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1)
+ {
+ Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return is_broadcast != 0;
}
void UdpSocket::SetMulticastTTL(int ttl)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1)
- {
- Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1)
+ {
+ Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
}
int UdpSocket::GetMulticastTTL()
{
- int ttl = 0;
- socklen_t size = sizeof(int);
+ int ttl = 0;
+ socklen_t size = sizeof(int);
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1)
- {
- Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return ttl;
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1)
+ {
+ Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return ttl;
}
void UdpSocket::SetMulticastLoop(bool x)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- int val = x ? 1 : 0;
- if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
- {
- Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return;
- }
+ if (IsIpv6())
+ {
+ int val = x ? 1 : 0;
+ if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
+ {
+ Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return;
+ }
#endif
#endif
- int val = x ? 1 : 0;
- if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
- {
- Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
+ int val = x ? 1 : 0;
+ if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
+ {
+ Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
}
bool UdpSocket::IsMulticastLoop()
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- int is_loop = 0;
- socklen_t size = sizeof(int);
- if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
- {
- Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return is_loop ? true : false;
- }
+ if (IsIpv6())
+ {
+ int is_loop = 0;
+ socklen_t size = sizeof(int);
+ if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
+ {
+ Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return is_loop ? true : false;
+ }
#endif
#endif
- int is_loop = 0;
- socklen_t size = sizeof(int);
- if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
- {
- Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return is_loop ? true : false;
+ int is_loop = 0;
+ socklen_t size = sizeof(int);
+ if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
+ {
+ Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return is_loop ? true : false;
}
void UdpSocket::AddMulticastMembership(const std::string& group, const std::string& local_if, int if_index)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- struct ipv6_mreq x;
- struct in6_addr addr;
- if (Utility::u2ip( group, addr ))
- {
- x.ipv6mr_multiaddr = addr;
- x.ipv6mr_interface = if_index;
- if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1)
- {
- Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
- return;
- }
-#endif
-#endif
- struct ip_mreq x; // ip_mreqn
- ipaddr_t addr;
- if (Utility::u2ip( group, addr ))
- {
- memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr));
- Utility::u2ip( local_if, addr);
- memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr));
-// x.imr_ifindex = if_index;
- if (setsockopt(GetSocket(), SOL_IP, IP_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1)
- {
- Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
+ if (IsIpv6())
+ {
+ struct ipv6_mreq x;
+ struct in6_addr addr;
+ if (Utility::u2ip( group, addr ))
+ {
+ x.ipv6mr_multiaddr = addr;
+ x.ipv6mr_interface = if_index;
+ if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1)
+ {
+ Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
+ return;
+ }
+#endif
+#endif
+ struct ip_mreq x; // ip_mreqn
+ ipaddr_t addr;
+ if (Utility::u2ip( group, addr ))
+ {
+ memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr));
+ Utility::u2ip( local_if, addr);
+ memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr));
+// x.imr_ifindex = if_index;
+ if (setsockopt(GetSocket(), SOL_IP, IP_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1)
+ {
+ Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
}
void UdpSocket::DropMulticastMembership(const std::string& group, const std::string& local_if, int if_index)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (IsIpv6())
- {
- struct ipv6_mreq x;
- struct in6_addr addr;
- if (Utility::u2ip( group, addr ))
- {
- x.ipv6mr_multiaddr = addr;
- x.ipv6mr_interface = if_index;
- if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1)
- {
- Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
- return;
- }
-#endif
-#endif
- struct ip_mreq x; // ip_mreqn
- ipaddr_t addr;
- if (Utility::u2ip( group, addr ))
- {
- memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr));
- Utility::u2ip( local_if, addr);
- memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr));
-// x.imr_ifindex = if_index;
- if (setsockopt(GetSocket(), SOL_IP, IP_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1)
- {
- Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- }
+ if (IsIpv6())
+ {
+ struct ipv6_mreq x;
+ struct in6_addr addr;
+ if (Utility::u2ip( group, addr ))
+ {
+ x.ipv6mr_multiaddr = addr;
+ x.ipv6mr_interface = if_index;
+ if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1)
+ {
+ Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
+ return;
+ }
+#endif
+#endif
+ struct ip_mreq x; // ip_mreqn
+ ipaddr_t addr;
+ if (Utility::u2ip( group, addr ))
+ {
+ memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr));
+ Utility::u2ip( local_if, addr);
+ memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr));
+// x.imr_ifindex = if_index;
+ if (setsockopt(GetSocket(), SOL_IP, IP_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1)
+ {
+ Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ }
}
@@ -772,40 +772,40 @@ void UdpSocket::DropMulticastMembership(const std::string& group, const std::str
#ifdef IPPROTO_IPV6
void UdpSocket::SetMulticastHops(int hops)
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (!IsIpv6())
- {
- Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR);
- return;
- }
- if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, sizeof(int)) == -1)
- {
- Handler().LogError(this, "SetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (!IsIpv6())
+ {
+ Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR);
+ return;
+ }
+ if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, sizeof(int)) == -1)
+ {
+ Handler().LogError(this, "SetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
}
int UdpSocket::GetMulticastHops()
{
- if (GetSocket() == INVALID_SOCKET)
- {
- CreateConnection();
- }
- if (!IsIpv6())
- {
- Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR);
- return -1;
- }
- int hops = 0;
- socklen_t size = sizeof(int);
- if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, &size) == -1)
- {
- Handler().LogError(this, "GetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING);
- }
- return hops;
+ if (GetSocket() == INVALID_SOCKET)
+ {
+ CreateConnection();
+ }
+ if (!IsIpv6())
+ {
+ Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR);
+ return -1;
+ }
+ int hops = 0;
+ socklen_t size = sizeof(int);
+ if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, &size) == -1)
+ {
+ Handler().LogError(this, "GetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING);
+ }
+ return hops;
}
#endif // IPPROTO_IPV6
#endif
@@ -813,7 +813,7 @@ int UdpSocket::GetMulticastHops()
bool UdpSocket::IsBound()
{
- return m_bind_ok;
+ return m_bind_ok;
}
@@ -829,19 +829,19 @@ void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, sock
port_t UdpSocket::GetPort()
{
- return m_port;
+ return m_port;
}
int UdpSocket::GetLastSizeWritten()
{
- return m_last_size_written;
+ return m_last_size_written;
}
void UdpSocket::SetTimestamp(bool x)
{
- m_b_read_ts = x;
+ m_b_read_ts = x;
}
diff --git a/dep/src/sockets/Utility.cpp b/dep/src/sockets/Utility.cpp
index c1327035d7a..e552da3b6e7 100644
--- a/dep/src/sockets/Utility.cpp
+++ b/dep/src/sockets/Utility.cpp
@@ -1,6 +1,6 @@
/** \file Utility.cpp
- ** \date 2004-02-13
- ** \author grymse@alhem.net
+ ** \date 2004-02-13
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -71,69 +71,69 @@ std::string Utility::m_local_addr6;
std::string Utility::base64(const std::string& str_in)
{
- std::string str;
- Base64 m_b;
- m_b.encode(str_in, str, false); // , false == do not add cr/lf
- return str;
+ std::string str;
+ Base64 m_b;
+ m_b.encode(str_in, str, false); // , false == do not add cr/lf
+ return str;
}
std::string Utility::base64d(const std::string& str_in)
{
- std::string str;
- Base64 m_b;
- m_b.decode(str_in, str);
- return str;
+ std::string str;
+ Base64 m_b;
+ m_b.decode(str_in, str);
+ return str;
}
std::string Utility::l2string(long l)
{
- std::string str;
- char tmp[100];
- sprintf(tmp,"%ld",l);
- str = tmp;
- return str;
+ std::string str;
+ char tmp[100];
+ sprintf(tmp,"%ld",l);
+ str = tmp;
+ return str;
}
std::string Utility::bigint2string(uint64_t l)
{
- std::string str;
- uint64_t tmp = l;
- while (tmp)
- {
- uint64_t a = tmp % 10;
- str = (char)(a + 48) + str;
- tmp /= 10;
- }
- if (str.empty())
- {
- str = "0";
- }
- return str;
+ std::string str;
+ uint64_t tmp = l;
+ while (tmp)
+ {
+ uint64_t a = tmp % 10;
+ str = (char)(a + 48) + str;
+ tmp /= 10;
+ }
+ if (str.empty())
+ {
+ str = "0";
+ }
+ return str;
}
-uint64_t Utility::atoi64(const std::string& str)
+uint64_t Utility::atoi64(const std::string& str)
{
- uint64_t l = 0;
- for (size_t i = 0; i < str.size(); i++)
- {
- l = l * 10 + str[i] - 48;
- }
- return l;
+ uint64_t l = 0;
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ l = l * 10 + str[i] - 48;
+ }
+ return l;
}
unsigned int Utility::hex2unsigned(const std::string& str)
{
- unsigned int r = 0;
- for (size_t i = 0; i < str.size(); i++)
- {
- r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0);
- }
- return r;
+ unsigned int r = 0;
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0);
+ }
+ return r;
}
@@ -143,28 +143,28 @@ unsigned int Utility::hex2unsigned(const std::string& str)
*/
std::string Utility::rfc1738_encode(const std::string& src)
{
-static char hex[] = "0123456789ABCDEF";
- std::string dst;
- for (size_t i = 0; i < src.size(); i++)
- {
- if (isalnum(src[i]))
- {
- dst += src[i];
- }
- else
- if (src[i] == ' ')
- {
- dst += '+';
- }
- else
- {
- unsigned char c = static_cast<unsigned char>(src[i]);
- dst += '%';
- dst += hex[c / 16];
- dst += hex[c % 16];
- }
- }
- return dst;
+static char hex[] = "0123456789ABCDEF";
+ std::string dst;
+ for (size_t i = 0; i < src.size(); i++)
+ {
+ if (isalnum(src[i]))
+ {
+ dst += src[i];
+ }
+ else
+ if (src[i] == ' ')
+ {
+ dst += '+';
+ }
+ else
+ {
+ unsigned char c = static_cast<unsigned char>(src[i]);
+ dst += '%';
+ dst += hex[c / 16];
+ dst += hex[c % 16];
+ }
+ }
+ return dst;
} // rfc1738_encode
@@ -174,95 +174,95 @@ static char hex[] = "0123456789ABCDEF";
*/
std::string Utility::rfc1738_decode(const std::string& src)
{
- std::string dst;
- for (size_t i = 0; i < src.size(); i++)
- {
- if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2]))
- {
- char c1 = src[++i];
- char c2 = src[++i];
- c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
- c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
- dst += (char)(c1 * 16 + c2);
- }
- else
- if (src[i] == '+')
- {
- dst += ' ';
- }
- else
- {
- dst += src[i];
- }
- }
- return dst;
+ std::string dst;
+ for (size_t i = 0; i < src.size(); i++)
+ {
+ if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2]))
+ {
+ char c1 = src[++i];
+ char c2 = src[++i];
+ c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
+ c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
+ dst += (char)(c1 * 16 + c2);
+ }
+ else
+ if (src[i] == '+')
+ {
+ dst += ' ';
+ }
+ else
+ {
+ dst += src[i];
+ }
+ }
+ return dst;
} // rfc1738_decode
bool Utility::isipv4(const std::string& str)
{
- int dots = 0;
- // %! ignore :port?
- for (size_t i = 0; i < str.size(); i++)
- {
- if (str[i] == '.')
- dots++;
- else
- if (!isdigit(str[i]))
- return false;
- }
- if (dots != 3)
- return false;
- return true;
+ int dots = 0;
+ // %! ignore :port?
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ if (str[i] == '.')
+ dots++;
+ else
+ if (!isdigit(str[i]))
+ return false;
+ }
+ if (dots != 3)
+ return false;
+ return true;
}
bool Utility::isipv6(const std::string& str)
{
- size_t qc = 0;
- size_t qd = 0;
- for (size_t i = 0; i < str.size(); i++)
- {
- qc += (str[i] == ':') ? 1 : 0;
- qd += (str[i] == '.') ? 1 : 0;
- }
- if (qc > 7)
- {
- return false;
- }
- if (qd && qd != 3)
- {
- return false;
- }
- Parse pa(str,":.");
- std::string tmp = pa.getword();
- while (!tmp.empty())
- {
- if (tmp.size() > 4)
- {
- return false;
- }
- for (size_t i = 0; i < tmp.size(); i++)
- {
- if (tmp[i] < '0' || (tmp[i] > '9' && tmp[i] < 'A') ||
- (tmp[i] > 'F' && tmp[i] < 'a') || tmp[i] > 'f')
- {
- return false;
- }
- }
- //
- tmp = pa.getword();
- }
- return true;
+ size_t qc = 0;
+ size_t qd = 0;
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ qc += (str[i] == ':') ? 1 : 0;
+ qd += (str[i] == '.') ? 1 : 0;
+ }
+ if (qc > 7)
+ {
+ return false;
+ }
+ if (qd && qd != 3)
+ {
+ return false;
+ }
+ Parse pa(str,":.");
+ std::string tmp = pa.getword();
+ while (!tmp.empty())
+ {
+ if (tmp.size() > 4)
+ {
+ return false;
+ }
+ for (size_t i = 0; i < tmp.size(); i++)
+ {
+ if (tmp[i] < '0' || (tmp[i] > '9' && tmp[i] < 'A') ||
+ (tmp[i] > 'F' && tmp[i] < 'a') || tmp[i] > 'f')
+ {
+ return false;
+ }
+ }
+ //
+ tmp = pa.getword();
+ }
+ return true;
}
bool Utility::u2ip(const std::string& str, ipaddr_t& l)
{
- struct sockaddr_in sa;
- bool r = Utility::u2ip(str, sa);
- memcpy(&l, &sa.sin_addr, sizeof(l));
- return r;
+ struct sockaddr_in sa;
+ bool r = Utility::u2ip(str, sa);
+ memcpy(&l, &sa.sin_addr, sizeof(l));
+ return r;
}
@@ -270,10 +270,10 @@ bool Utility::u2ip(const std::string& str, ipaddr_t& l)
#ifdef IPPROTO_IPV6
bool Utility::u2ip(const std::string& str, struct in6_addr& l)
{
- struct sockaddr_in6 sa;
- bool r = Utility::u2ip(str, sa);
- l = sa.sin6_addr;
- return r;
+ struct sockaddr_in6 sa;
+ bool r = Utility::u2ip(str, sa);
+ l = sa.sin6_addr;
+ return r;
}
#endif
#endif
@@ -281,21 +281,21 @@ bool Utility::u2ip(const std::string& str, struct in6_addr& l)
void Utility::l2ip(const ipaddr_t ip, std::string& str)
{
- struct sockaddr_in sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- memcpy(&sa.sin_addr, &ip, sizeof(sa.sin_addr));
- Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
+ struct sockaddr_in sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
+ memcpy(&sa.sin_addr, &ip, sizeof(sa.sin_addr));
+ Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
}
void Utility::l2ip(const in_addr& ip, std::string& str)
{
- struct sockaddr_in sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- sa.sin_addr = ip;
- Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
+ struct sockaddr_in sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
+ sa.sin_addr = ip;
+ Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
}
@@ -303,61 +303,61 @@ void Utility::l2ip(const in_addr& ip, std::string& str)
#ifdef IPPROTO_IPV6
void Utility::l2ip(const struct in6_addr& ip, std::string& str,bool mixed)
{
- char slask[100]; // l2ip temporary
- *slask = 0;
- unsigned int prev = 0;
- bool skipped = false;
- bool ok_to_skip = true;
- if (mixed)
- {
- unsigned short x;
- unsigned short addr16[8];
- memcpy(addr16, &ip, sizeof(addr16));
- for (size_t i = 0; i < 6; i++)
- {
- x = ntohs(addr16[i]);
- if (*slask && (x || !ok_to_skip || prev))
- strcat(slask,":");
- if (x || !ok_to_skip)
- {
- sprintf(slask + strlen(slask),"%x", x);
- if (x && skipped)
- ok_to_skip = false;
- }
- else
- {
- skipped = true;
- }
- prev = x;
- }
- x = ntohs(addr16[6]);
- sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255);
- x = ntohs(addr16[7]);
- sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255);
- }
- else
- {
- struct sockaddr_in6 sa;
- memset(&sa, 0, sizeof(sa));
- sa.sin6_family = AF_INET6;
- sa.sin6_addr = ip;
- Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
- return;
- }
- str = slask;
+ char slask[100]; // l2ip temporary
+ *slask = 0;
+ unsigned int prev = 0;
+ bool skipped = false;
+ bool ok_to_skip = true;
+ if (mixed)
+ {
+ unsigned short x;
+ unsigned short addr16[8];
+ memcpy(addr16, &ip, sizeof(addr16));
+ for (size_t i = 0; i < 6; i++)
+ {
+ x = ntohs(addr16[i]);
+ if (*slask && (x || !ok_to_skip || prev))
+ strcat(slask,":");
+ if (x || !ok_to_skip)
+ {
+ sprintf(slask + strlen(slask),"%x", x);
+ if (x && skipped)
+ ok_to_skip = false;
+ }
+ else
+ {
+ skipped = true;
+ }
+ prev = x;
+ }
+ x = ntohs(addr16[6]);
+ sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255);
+ x = ntohs(addr16[7]);
+ sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255);
+ }
+ else
+ {
+ struct sockaddr_in6 sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin6_family = AF_INET6;
+ sa.sin6_addr = ip;
+ Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST);
+ return;
+ }
+ str = slask;
}
int Utility::in6_addr_compare(in6_addr a,in6_addr b)
{
- for (size_t i = 0; i < 16; i++)
- {
- if (a.s6_addr[i] < b.s6_addr[i])
- return -1;
- if (a.s6_addr[i] > b.s6_addr[i])
- return 1;
- }
- return 0;
+ for (size_t i = 0; i < 16; i++)
+ {
+ if (a.s6_addr[i] < b.s6_addr[i])
+ return -1;
+ if (a.s6_addr[i] > b.s6_addr[i])
+ return 1;
+ }
+ return 0;
}
#endif
#endif
@@ -365,60 +365,60 @@ int Utility::in6_addr_compare(in6_addr a,in6_addr b)
void Utility::ResolveLocal()
{
- char h[256];
-
- // get local hostname and translate into ip-address
- *h = 0;
- gethostname(h,255);
- {
- if (Utility::u2ip(h, m_ip))
- {
- Utility::l2ip(m_ip, m_addr);
- }
- }
+ char h[256];
+
+ // get local hostname and translate into ip-address
+ *h = 0;
+ gethostname(h,255);
+ {
+ if (Utility::u2ip(h, m_ip))
+ {
+ Utility::l2ip(m_ip, m_addr);
+ }
+ }
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- memset(&m_local_ip6, 0, sizeof(m_local_ip6));
- {
- if (Utility::u2ip(h, m_local_ip6))
- {
- Utility::l2ip(m_local_ip6, m_local_addr6);
- }
- }
+ memset(&m_local_ip6, 0, sizeof(m_local_ip6));
+ {
+ if (Utility::u2ip(h, m_local_ip6))
+ {
+ Utility::l2ip(m_local_ip6, m_local_addr6);
+ }
+ }
#endif
#endif
- m_host = h;
- m_local_resolved = true;
+ m_host = h;
+ m_local_resolved = true;
}
const std::string& Utility::GetLocalHostname()
{
- if (!m_local_resolved)
- {
- ResolveLocal();
- }
- return m_host;
+ if (!m_local_resolved)
+ {
+ ResolveLocal();
+ }
+ return m_host;
}
ipaddr_t Utility::GetLocalIP()
{
- if (!m_local_resolved)
- {
- ResolveLocal();
- }
- return m_ip;
+ if (!m_local_resolved)
+ {
+ ResolveLocal();
+ }
+ return m_ip;
}
const std::string& Utility::GetLocalAddress()
{
- if (!m_local_resolved)
- {
- ResolveLocal();
- }
- return m_addr;
+ if (!m_local_resolved)
+ {
+ ResolveLocal();
+ }
+ return m_addr;
}
@@ -426,21 +426,21 @@ const std::string& Utility::GetLocalAddress()
#ifdef IPPROTO_IPV6
const struct in6_addr& Utility::GetLocalIP6()
{
- if (!m_local_resolved)
- {
- ResolveLocal();
- }
- return m_local_ip6;
+ if (!m_local_resolved)
+ {
+ ResolveLocal();
+ }
+ return m_local_ip6;
}
const std::string& Utility::GetLocalAddress6()
{
- if (!m_local_resolved)
- {
- ResolveLocal();
- }
- return m_local_addr6;
+ if (!m_local_resolved)
+ {
+ ResolveLocal();
+ }
+ return m_local_addr6;
}
#endif
#endif
@@ -449,23 +449,23 @@ const std::string& Utility::GetLocalAddress6()
void Utility::SetEnv(const std::string& var,const std::string& value)
{
#if (defined(SOLARIS8) || defined(SOLARIS))
- {
- static std::map<std::string, char *> vmap;
- if (vmap.find(var) != vmap.end())
- {
- delete[] vmap[var];
- }
- vmap[var] = new char[var.size() + 1 + value.size() + 1];
- sprintf(vmap[var], "%s=%s", var.c_str(), value.c_str());
- putenv( vmap[var] );
- }
+ {
+ static std::map<std::string, char *> vmap;
+ if (vmap.find(var) != vmap.end())
+ {
+ delete[] vmap[var];
+ }
+ vmap[var] = new char[var.size() + 1 + value.size() + 1];
+ sprintf(vmap[var], "%s=%s", var.c_str(), value.c_str());
+ putenv( vmap[var] );
+ }
#elif defined _WIN32
- {
- std::string slask = var + "=" + value;
- _putenv( (char *)slask.c_str());
- }
+ {
+ std::string slask = var + "=" + value;
+ _putenv( (char *)slask.c_str());
+ }
#else
- setenv(var.c_str(), value.c_str(), 1);
+ setenv(var.c_str(), value.c_str(), 1);
#endif
}
@@ -474,160 +474,160 @@ std::string Utility::Sa2String(struct sockaddr *sa)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- if (sa -> sa_family == AF_INET6)
- {
- struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
- std::string tmp;
- Utility::l2ip(sa6 -> sin6_addr, tmp);
- return tmp + ":" + Utility::l2string(ntohs(sa6 -> sin6_port));
- }
+ if (sa -> sa_family == AF_INET6)
+ {
+ struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
+ std::string tmp;
+ Utility::l2ip(sa6 -> sin6_addr, tmp);
+ return tmp + ":" + Utility::l2string(ntohs(sa6 -> sin6_port));
+ }
#endif
#endif
- if (sa -> sa_family == AF_INET)
- {
- struct sockaddr_in *sa4 = (struct sockaddr_in *)sa;
- ipaddr_t a;
- memcpy(&a, &sa4 -> sin_addr, 4);
- std::string tmp;
- Utility::l2ip(a, tmp);
- return tmp + ":" + Utility::l2string(ntohs(sa4 -> sin_port));
- }
- return "";
+ if (sa -> sa_family == AF_INET)
+ {
+ struct sockaddr_in *sa4 = (struct sockaddr_in *)sa;
+ ipaddr_t a;
+ memcpy(&a, &sa4 -> sin_addr, 4);
+ std::string tmp;
+ Utility::l2ip(a, tmp);
+ return tmp + ":" + Utility::l2string(ntohs(sa4 -> sin_port));
+ }
+ return "";
}
void Utility::GetTime(struct timeval *p)
{
#ifdef _WIN32
- FILETIME ft; // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
- GetSystemTimeAsFileTime(&ft);
- uint64_t tt;
- memcpy(&tt, &ft, sizeof(tt));
- tt /= 10; // make it usecs
- p->tv_sec = (long)tt / 1000000;
- p->tv_usec = (long)tt % 1000000;
+ FILETIME ft; // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
+ GetSystemTimeAsFileTime(&ft);
+ uint64_t tt;
+ memcpy(&tt, &ft, sizeof(tt));
+ tt /= 10; // make it usecs
+ p->tv_sec = (long)tt / 1000000;
+ p->tv_usec = (long)tt % 1000000;
#else
- gettimeofday(p, NULL);
+ gettimeofday(p, NULL);
#endif
}
std::auto_ptr<SocketAddress> Utility::CreateAddress(struct sockaddr *sa,socklen_t sa_len)
{
- switch (sa -> sa_family)
- {
- case AF_INET:
- if (sa_len == sizeof(struct sockaddr_in))
- {
- struct sockaddr_in *p = (struct sockaddr_in *)sa;
- return std::auto_ptr<SocketAddress>(new Ipv4Address(*p));
- }
- break;
+ switch (sa -> sa_family)
+ {
+ case AF_INET:
+ if (sa_len == sizeof(struct sockaddr_in))
+ {
+ struct sockaddr_in *p = (struct sockaddr_in *)sa;
+ return std::auto_ptr<SocketAddress>(new Ipv4Address(*p));
+ }
+ break;
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
- case AF_INET6:
- if (sa_len == sizeof(struct sockaddr_in6))
- {
- struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa;
- return std::auto_ptr<SocketAddress>(new Ipv6Address(*p));
- }
- break;
+ case AF_INET6:
+ if (sa_len == sizeof(struct sockaddr_in6))
+ {
+ struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa;
+ return std::auto_ptr<SocketAddress>(new Ipv6Address(*p));
+ }
+ break;
#endif
#endif
- }
- return std::auto_ptr<SocketAddress>(NULL);
+ }
+ return std::auto_ptr<SocketAddress>(NULL);
}
bool Utility::u2ip(const std::string& host, struct sockaddr_in& sa, int ai_flags)
{
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
#ifdef NO_GETADDRINFO
- if ((ai_flags & AI_NUMERICHOST) != 0 || isipv4(host))
- {
- Parse pa((char *)host.c_str(), ".");
- union {
- struct {
- unsigned char b1;
- unsigned char b2;
- unsigned char b3;
- unsigned char b4;
- } a;
- ipaddr_t l;
- } u;
- u.a.b1 = static_cast<unsigned char>(pa.getvalue());
- u.a.b2 = static_cast<unsigned char>(pa.getvalue());
- u.a.b3 = static_cast<unsigned char>(pa.getvalue());
- u.a.b4 = static_cast<unsigned char>(pa.getvalue());
- memcpy(&sa.sin_addr, &u.l, sizeof(sa.sin_addr));
- return true;
- }
+ if ((ai_flags & AI_NUMERICHOST) != 0 || isipv4(host))
+ {
+ Parse pa((char *)host.c_str(), ".");
+ union {
+ struct {
+ unsigned char b1;
+ unsigned char b2;
+ unsigned char b3;
+ unsigned char b4;
+ } a;
+ ipaddr_t l;
+ } u;
+ u.a.b1 = static_cast<unsigned char>(pa.getvalue());
+ u.a.b2 = static_cast<unsigned char>(pa.getvalue());
+ u.a.b3 = static_cast<unsigned char>(pa.getvalue());
+ u.a.b4 = static_cast<unsigned char>(pa.getvalue());
+ memcpy(&sa.sin_addr, &u.l, sizeof(sa.sin_addr));
+ return true;
+ }
#ifndef LINUX
- struct hostent *he = gethostbyname( host.c_str() );
- if (!he)
- {
- return false;
- }
- memcpy(&sa.sin_addr, he -> h_addr, sizeof(sa.sin_addr));
+ struct hostent *he = gethostbyname( host.c_str() );
+ if (!he)
+ {
+ return false;
+ }
+ memcpy(&sa.sin_addr, he -> h_addr, sizeof(sa.sin_addr));
#else
- struct hostent he;
- struct hostent *result = NULL;
- int myerrno = 0;
- char buf[2000];
- int n = gethostbyname_r(host.c_str(), &he, buf, sizeof(buf), &result, &myerrno);
- if (n || !result)
- {
- return false;
- }
- if (he.h_addr_list && he.h_addr_list[0])
- memcpy(&sa.sin_addr, he.h_addr, 4);
- else
- return false;
+ struct hostent he;
+ struct hostent *result = NULL;
+ int myerrno = 0;
+ char buf[2000];
+ int n = gethostbyname_r(host.c_str(), &he, buf, sizeof(buf), &result, &myerrno);
+ if (n || !result)
+ {
+ return false;
+ }
+ if (he.h_addr_list && he.h_addr_list[0])
+ memcpy(&sa.sin_addr, he.h_addr, 4);
+ else
+ return false;
#endif
- return true;
+ return true;
#else
- struct addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- // AI_NUMERICHOST
- // AI_CANONNAME
- // AI_PASSIVE - server
- // AI_ADDRCONFIG
- // AI_V4MAPPED
- // AI_ALL
- // AI_NUMERICSERV
- hints.ai_flags = ai_flags;
- hints.ai_family = AF_INET;
- hints.ai_socktype = 0;
- hints.ai_protocol = 0;
- struct addrinfo *res;
- if (Utility::isipv4(host))
- hints.ai_flags |= AI_NUMERICHOST;
- int n = getaddrinfo(host.c_str(), NULL, &hints, &res);
- if (!n)
- {
- std::vector<struct addrinfo *> vec;
- struct addrinfo *ai = res;
- while (ai)
- {
- if (ai -> ai_addrlen == sizeof(sa))
- vec.push_back( ai );
- ai = ai -> ai_next;
- }
- if (vec.empty())
- return false;
- ai = vec[Utility::Rnd() % vec.size()];
- {
- memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen);
- }
- freeaddrinfo(res);
- return true;
- }
- std::string error = "Error: ";
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ // AI_NUMERICHOST
+ // AI_CANONNAME
+ // AI_PASSIVE - server
+ // AI_ADDRCONFIG
+ // AI_V4MAPPED
+ // AI_ALL
+ // AI_NUMERICSERV
+ hints.ai_flags = ai_flags;
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = 0;
+ hints.ai_protocol = 0;
+ struct addrinfo *res;
+ if (Utility::isipv4(host))
+ hints.ai_flags |= AI_NUMERICHOST;
+ int n = getaddrinfo(host.c_str(), NULL, &hints, &res);
+ if (!n)
+ {
+ std::vector<struct addrinfo *> vec;
+ struct addrinfo *ai = res;
+ while (ai)
+ {
+ if (ai -> ai_addrlen == sizeof(sa))
+ vec.push_back( ai );
+ ai = ai -> ai_next;
+ }
+ if (vec.empty())
+ return false;
+ ai = vec[Utility::Rnd() % vec.size()];
+ {
+ memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen);
+ }
+ freeaddrinfo(res);
+ return true;
+ }
+ std::string error = "Error: ";
#ifndef __CYGWIN__
- error += gai_strerror(n);
+ error += gai_strerror(n);
#endif
- return false;
+ return false;
#endif // NO_GETADDRINFO
}
@@ -636,112 +636,112 @@ bool Utility::u2ip(const std::string& host, struct sockaddr_in& sa, int ai_flags
#ifdef IPPROTO_IPV6
bool Utility::u2ip(const std::string& host, struct sockaddr_in6& sa, int ai_flags)
{
- memset(&sa, 0, sizeof(sa));
- sa.sin6_family = AF_INET6;
+ memset(&sa, 0, sizeof(sa));
+ sa.sin6_family = AF_INET6;
#ifdef NO_GETADDRINFO
- if ((ai_flags & AI_NUMERICHOST) != 0 || isipv6(host))
- {
- std::list<std::string> vec;
- size_t x = 0;
- for (size_t i = 0; i <= host.size(); i++)
- {
- if (i == host.size() || host[i] == ':')
- {
- std::string s = host.substr(x, i - x);
- //
- if (strstr(s.c_str(),".")) // x.x.x.x
- {
- Parse pa(s,".");
- char slask[100]; // u2ip temporary hex2string conversion
- unsigned long b0 = static_cast<unsigned long>(pa.getvalue());
- unsigned long b1 = static_cast<unsigned long>(pa.getvalue());
- unsigned long b2 = static_cast<unsigned long>(pa.getvalue());
- unsigned long b3 = static_cast<unsigned long>(pa.getvalue());
- sprintf(slask,"%lx",b0 * 256 + b1);
- vec.push_back(slask);
- sprintf(slask,"%lx",b2 * 256 + b3);
- vec.push_back(slask);
- }
- else
- {
- vec.push_back(s);
- }
- //
- x = i + 1;
- }
- }
- size_t sz = vec.size(); // number of byte pairs
- size_t i = 0; // index in in6_addr.in6_u.u6_addr16[] ( 0 .. 7 )
- unsigned short addr16[8];
- for (std::list<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
- {
- std::string bytepair = *it;
- if (!bytepair.empty())
- {
- addr16[i++] = htons(Utility::hex2unsigned(bytepair));
- }
- else
- {
- addr16[i++] = 0;
- while (sz++ < 8)
- {
- addr16[i++] = 0;
- }
- }
- }
- memcpy(&sa.sin6_addr, addr16, sizeof(addr16));
- return true;
- }
+ if ((ai_flags & AI_NUMERICHOST) != 0 || isipv6(host))
+ {
+ std::list<std::string> vec;
+ size_t x = 0;
+ for (size_t i = 0; i <= host.size(); i++)
+ {
+ if (i == host.size() || host[i] == ':')
+ {
+ std::string s = host.substr(x, i - x);
+ //
+ if (strstr(s.c_str(),".")) // x.x.x.x
+ {
+ Parse pa(s,".");
+ char slask[100]; // u2ip temporary hex2string conversion
+ unsigned long b0 = static_cast<unsigned long>(pa.getvalue());
+ unsigned long b1 = static_cast<unsigned long>(pa.getvalue());
+ unsigned long b2 = static_cast<unsigned long>(pa.getvalue());
+ unsigned long b3 = static_cast<unsigned long>(pa.getvalue());
+ sprintf(slask,"%lx",b0 * 256 + b1);
+ vec.push_back(slask);
+ sprintf(slask,"%lx",b2 * 256 + b3);
+ vec.push_back(slask);
+ }
+ else
+ {
+ vec.push_back(s);
+ }
+ //
+ x = i + 1;
+ }
+ }
+ size_t sz = vec.size(); // number of byte pairs
+ size_t i = 0; // index in in6_addr.in6_u.u6_addr16[] ( 0 .. 7 )
+ unsigned short addr16[8];
+ for (std::list<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
+ {
+ std::string bytepair = *it;
+ if (!bytepair.empty())
+ {
+ addr16[i++] = htons(Utility::hex2unsigned(bytepair));
+ }
+ else
+ {
+ addr16[i++] = 0;
+ while (sz++ < 8)
+ {
+ addr16[i++] = 0;
+ }
+ }
+ }
+ memcpy(&sa.sin6_addr, addr16, sizeof(addr16));
+ return true;
+ }
#ifdef SOLARIS
- int errnum = 0;
- struct hostent *he = getipnodebyname( host.c_str(), AF_INET6, 0, &errnum );
+ int errnum = 0;
+ struct hostent *he = getipnodebyname( host.c_str(), AF_INET6, 0, &errnum );
#else
- struct hostent *he = gethostbyname2( host.c_str(), AF_INET6 );
+ struct hostent *he = gethostbyname2( host.c_str(), AF_INET6 );
#endif
- if (!he)
- {
- return false;
- }
- memcpy(&sa.sin6_addr,he -> h_addr_list[0],he -> h_length);
+ if (!he)
+ {
+ return false;
+ }
+ memcpy(&sa.sin6_addr,he -> h_addr_list[0],he -> h_length);
#ifdef SOLARIS
- free(he);
+ free(he);
#endif
- return true;
+ return true;
#else
- struct addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- hints.ai_flags = ai_flags;
- hints.ai_family = AF_INET6;
- hints.ai_socktype = 0;
- hints.ai_protocol = 0;
- struct addrinfo *res;
- if (Utility::isipv6(host))
- hints.ai_flags |= AI_NUMERICHOST;
- int n = getaddrinfo(host.c_str(), NULL, &hints, &res);
- if (!n)
- {
- std::vector<struct addrinfo *> vec;
- struct addrinfo *ai = res;
- while (ai)
- {
- if (ai -> ai_addrlen == sizeof(sa))
- vec.push_back( ai );
- ai = ai -> ai_next;
- }
- if (vec.empty())
- return false;
- ai = vec[Utility::Rnd() % vec.size()];
- {
- memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen);
- }
- freeaddrinfo(res);
- return true;
- }
- std::string error = "Error: ";
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_flags = ai_flags;
+ hints.ai_family = AF_INET6;
+ hints.ai_socktype = 0;
+ hints.ai_protocol = 0;
+ struct addrinfo *res;
+ if (Utility::isipv6(host))
+ hints.ai_flags |= AI_NUMERICHOST;
+ int n = getaddrinfo(host.c_str(), NULL, &hints, &res);
+ if (!n)
+ {
+ std::vector<struct addrinfo *> vec;
+ struct addrinfo *ai = res;
+ while (ai)
+ {
+ if (ai -> ai_addrlen == sizeof(sa))
+ vec.push_back( ai );
+ ai = ai -> ai_next;
+ }
+ if (vec.empty())
+ return false;
+ ai = vec[Utility::Rnd() % vec.size()];
+ {
+ memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen);
+ }
+ freeaddrinfo(res);
+ return true;
+ }
+ std::string error = "Error: ";
#ifndef __CYGWIN__
- error += gai_strerror(n);
+ error += gai_strerror(n);
#endif
- return false;
+ return false;
#endif // NO_GETADDRINFO
}
#endif // IPPROTO_IPV6
@@ -750,123 +750,123 @@ bool Utility::u2ip(const std::string& host, struct sockaddr_in6& sa, int ai_flag
bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, int flags)
{
- std::string service;
- return Utility::reverse(sa, sa_len, hostname, service, flags);
+ std::string service;
+ return Utility::reverse(sa, sa_len, hostname, service, flags);
}
bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags)
{
- hostname = "";
- service = "";
+ hostname = "";
+ service = "";
#ifdef NO_GETADDRINFO
- switch (sa -> sa_family)
- {
- case AF_INET:
- if (flags & NI_NUMERICHOST)
- {
- union {
- struct {
- unsigned char b1;
- unsigned char b2;
- unsigned char b3;
- unsigned char b4;
- } a;
- ipaddr_t l;
- } u;
- struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
- memcpy(&u.l, &sa_in -> sin_addr, sizeof(u.l));
- char tmp[100];
- sprintf(tmp, "%u.%u.%u.%u", u.a.b1, u.a.b2, u.a.b3, u.a.b4);
- hostname = tmp;
- return true;
- }
- else
- {
- struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
- struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin_addr, sizeof(sa_in -> sin_addr), AF_INET);
- if (h)
- {
- hostname = h -> h_name;
- return true;
- }
- }
- break;
+ switch (sa -> sa_family)
+ {
+ case AF_INET:
+ if (flags & NI_NUMERICHOST)
+ {
+ union {
+ struct {
+ unsigned char b1;
+ unsigned char b2;
+ unsigned char b3;
+ unsigned char b4;
+ } a;
+ ipaddr_t l;
+ } u;
+ struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
+ memcpy(&u.l, &sa_in -> sin_addr, sizeof(u.l));
+ char tmp[100];
+ sprintf(tmp, "%u.%u.%u.%u", u.a.b1, u.a.b2, u.a.b3, u.a.b4);
+ hostname = tmp;
+ return true;
+ }
+ else
+ {
+ struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
+ struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin_addr, sizeof(sa_in -> sin_addr), AF_INET);
+ if (h)
+ {
+ hostname = h -> h_name;
+ return true;
+ }
+ }
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- if (flags & NI_NUMERICHOST)
- {
- char slask[100]; // l2ip temporary
- *slask = 0;
- unsigned int prev = 0;
- bool skipped = false;
- bool ok_to_skip = true;
- {
- unsigned short addr16[8];
- struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa;
- memcpy(addr16, &sa_in6 -> sin6_addr, sizeof(addr16));
- for (size_t i = 0; i < 8; i++)
- {
- unsigned short x = ntohs(addr16[i]);
- if (*slask && (x || !ok_to_skip || prev))
- strcat(slask,":");
- if (x || !ok_to_skip)
- {
- sprintf(slask + strlen(slask),"%x", x);
- if (x && skipped)
- ok_to_skip = false;
- }
- else
- {
- skipped = true;
- }
- prev = x;
- }
- }
- if (!*slask)
- strcpy(slask, "::");
- hostname = slask;
- return true;
- }
- else
- {
- // %! TODO: ipv6 reverse lookup
- struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa;
- struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin6_addr, sizeof(sa_in -> sin6_addr), AF_INET6);
- if (h)
- {
- hostname = h -> h_name;
- return true;
- }
- }
- break;
+ case AF_INET6:
+ if (flags & NI_NUMERICHOST)
+ {
+ char slask[100]; // l2ip temporary
+ *slask = 0;
+ unsigned int prev = 0;
+ bool skipped = false;
+ bool ok_to_skip = true;
+ {
+ unsigned short addr16[8];
+ struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa;
+ memcpy(addr16, &sa_in6 -> sin6_addr, sizeof(addr16));
+ for (size_t i = 0; i < 8; i++)
+ {
+ unsigned short x = ntohs(addr16[i]);
+ if (*slask && (x || !ok_to_skip || prev))
+ strcat(slask,":");
+ if (x || !ok_to_skip)
+ {
+ sprintf(slask + strlen(slask),"%x", x);
+ if (x && skipped)
+ ok_to_skip = false;
+ }
+ else
+ {
+ skipped = true;
+ }
+ prev = x;
+ }
+ }
+ if (!*slask)
+ strcpy(slask, "::");
+ hostname = slask;
+ return true;
+ }
+ else
+ {
+ // %! TODO: ipv6 reverse lookup
+ struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa;
+ struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin6_addr, sizeof(sa_in -> sin6_addr), AF_INET6);
+ if (h)
+ {
+ hostname = h -> h_name;
+ return true;
+ }
+ }
+ break;
#endif
- }
- return false;
+ }
+ return false;
#else
- char host[NI_MAXHOST];
- char serv[NI_MAXSERV];
- // NI_NOFQDN
- // NI_NUMERICHOST
- // NI_NAMEREQD
- // NI_NUMERICSERV
- // NI_DGRAM
- int n = getnameinfo(sa, sa_len, host, sizeof(host), serv, sizeof(serv), flags);
- if (n)
- {
- // EAI_AGAIN
- // EAI_BADFLAGS
- // EAI_FAIL
- // EAI_FAMILY
- // EAI_MEMORY
- // EAI_NONAME
- // EAI_OVERFLOW
- // EAI_SYSTEM
- return false;
- }
- hostname = host;
- service = serv;
- return true;
+ char host[NI_MAXHOST];
+ char serv[NI_MAXSERV];
+ // NI_NOFQDN
+ // NI_NUMERICHOST
+ // NI_NAMEREQD
+ // NI_NUMERICSERV
+ // NI_DGRAM
+ int n = getnameinfo(sa, sa_len, host, sizeof(host), serv, sizeof(serv), flags);
+ if (n)
+ {
+ // EAI_AGAIN
+ // EAI_BADFLAGS
+ // EAI_FAIL
+ // EAI_FAMILY
+ // EAI_MEMORY
+ // EAI_NONAME
+ // EAI_OVERFLOW
+ // EAI_SYSTEM
+ return false;
+ }
+ hostname = host;
+ service = serv;
+ return true;
#endif // NO_GETADDRINFO
}
@@ -874,32 +874,32 @@ bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostna
bool Utility::u2service(const std::string& name, int& service, int ai_flags)
{
#ifdef NO_GETADDRINFO
- // %!
- return false;
+ // %!
+ return false;
#else
- struct addrinfo hints;
- service = 0;
- memset(&hints, 0, sizeof(hints));
- // AI_NUMERICHOST
- // AI_CANONNAME
- // AI_PASSIVE - server
- // AI_ADDRCONFIG
- // AI_V4MAPPED
- // AI_ALL
- // AI_NUMERICSERV
- hints.ai_flags = ai_flags;
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = 0;
- hints.ai_protocol = 0;
- struct addrinfo *res;
- int n = getaddrinfo(NULL, name.c_str(), &hints, &res);
- if (!n)
- {
- service = res -> ai_protocol;
- freeaddrinfo(res);
- return true;
- }
- return false;
+ struct addrinfo hints;
+ service = 0;
+ memset(&hints, 0, sizeof(hints));
+ // AI_NUMERICHOST
+ // AI_CANONNAME
+ // AI_PASSIVE - server
+ // AI_ADDRCONFIG
+ // AI_V4MAPPED
+ // AI_ALL
+ // AI_NUMERICSERV
+ hints.ai_flags = ai_flags;
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = 0;
+ hints.ai_protocol = 0;
+ struct addrinfo *res;
+ int n = getaddrinfo(NULL, name.c_str(), &hints, &res);
+ if (!n)
+ {
+ service = res -> ai_protocol;
+ freeaddrinfo(res);
+ return true;
+ }
+ return false;
#endif // NO_GETADDRINFO
}
@@ -907,90 +907,90 @@ bool Utility::u2service(const std::string& name, int& service, int ai_flags)
unsigned long Utility::ThreadID()
{
#ifdef _WIN32
- return GetCurrentThreadId();
+ return GetCurrentThreadId();
#else
- return (unsigned long)pthread_self();
+ return (unsigned long)pthread_self();
#endif
}
std::string Utility::ToLower(const std::string& str)
{
- std::string r;
- for (size_t i = 0; i < str.size(); i++)
- {
- if (str[i] >= 'A' && str[i] <= 'Z')
- r += str[i] | 32;
- else
- r += str[i];
- }
- return r;
+ std::string r;
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ if (str[i] >= 'A' && str[i] <= 'Z')
+ r += str[i] | 32;
+ else
+ r += str[i];
+ }
+ return r;
}
std::string Utility::ToUpper(const std::string& str)
{
- std::string r;
- for (size_t i = 0; i < str.size(); i++)
- {
- if (str[i] >= 'a' && str[i] <= 'z')
- r += (char)(str[i] - 32);
- else
- r += str[i];
- }
- return r;
+ std::string r;
+ for (size_t i = 0; i < str.size(); i++)
+ {
+ if (str[i] >= 'a' && str[i] <= 'z')
+ r += (char)(str[i] - 32);
+ else
+ r += str[i];
+ }
+ return r;
}
std::string Utility::ToString(double d)
{
- char tmp[100];
- sprintf(tmp, "%f", d);
- return tmp;
+ char tmp[100];
+ sprintf(tmp, "%f", d);
+ return tmp;
}
unsigned long Utility::Rnd()
{
-static Utility::Rng generator( (unsigned long)time(NULL) );
- return generator.Get();
+static Utility::Rng generator( (unsigned long)time(NULL) );
+ return generator.Get();
}
Utility::Rng::Rng(unsigned long seed) : m_value( 0 )
{
- m_tmp[0]= seed & 0xffffffffUL;
- for (int i = 1; i < TWIST_LEN; i++)
- {
- m_tmp[i] = (1812433253UL * (m_tmp[i - 1] ^ (m_tmp[i - 1] >> 30)) + i);
- }
+ m_tmp[0]= seed & 0xffffffffUL;
+ for (int i = 1; i < TWIST_LEN; i++)
+ {
+ m_tmp[i] = (1812433253UL * (m_tmp[i - 1] ^ (m_tmp[i - 1] >> 30)) + i);
+ }
}
-
+
unsigned long Utility::Rng::Get()
{
- unsigned long val = m_tmp[m_value];
- ++m_value;
- if (m_value == TWIST_LEN)
- {
- for (int i = 0; i < TWIST_IB; ++i)
- {
- unsigned long s = TWIST(m_tmp, i, i + 1);
- m_tmp[i] = m_tmp[i + TWIST_IA] ^ (s >> 1) ^ MAGIC_TWIST(s);
- }
- {
- for (int i = 0; i < TWIST_LEN - 1; ++i)
- {
- unsigned long s = TWIST(m_tmp, i, i + 1);
- m_tmp[i] = m_tmp[i - TWIST_IB] ^ (s >> 1) ^ MAGIC_TWIST(s);
- }
- }
- unsigned long s = TWIST(m_tmp, TWIST_LEN - 1, 0);
- m_tmp[TWIST_LEN - 1] = m_tmp[TWIST_IA - 1] ^ (s >> 1) ^ MAGIC_TWIST(s);
-
- m_value = 0;
- }
- return val;
+ unsigned long val = m_tmp[m_value];
+ ++m_value;
+ if (m_value == TWIST_LEN)
+ {
+ for (int i = 0; i < TWIST_IB; ++i)
+ {
+ unsigned long s = TWIST(m_tmp, i, i + 1);
+ m_tmp[i] = m_tmp[i + TWIST_IA] ^ (s >> 1) ^ MAGIC_TWIST(s);
+ }
+ {
+ for (int i = 0; i < TWIST_LEN - 1; ++i)
+ {
+ unsigned long s = TWIST(m_tmp, i, i + 1);
+ m_tmp[i] = m_tmp[i - TWIST_IB] ^ (s >> 1) ^ MAGIC_TWIST(s);
+ }
+ }
+ unsigned long s = TWIST(m_tmp, TWIST_LEN - 1, 0);
+ m_tmp[TWIST_LEN - 1] = m_tmp[TWIST_IA - 1] ^ (s >> 1) ^ MAGIC_TWIST(s);
+
+ m_value = 0;
+ }
+ return val;
}
#ifdef SOCKETS_NAMESPACE
diff --git a/dep/src/sockets/socket_include.cpp b/dep/src/sockets/socket_include.cpp
index 07b986b02b7..6f08e8e16ab 100644
--- a/dep/src/sockets/socket_include.cpp
+++ b/dep/src/sockets/socket_include.cpp
@@ -1,6 +1,6 @@
/** \file socket_include.cpp
- ** \date 2004-11-28
- ** \author grymse@alhem.net
+ ** \date 2004-11-28
+ ** \author grymse@alhem.net
**/
/*
Copyright (C) 2004-2007 Anders Hedstrom
@@ -8,7 +8,7 @@ Copyright (C) 2004-2007 Anders Hedstrom
This library is made available under the terms of the GNU GPL.
If you would like to use this library in a closed-source application,
-a separate license agreement is available. For information about
+a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
email license@alhem.net.
@@ -30,60 +30,60 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <stdio.h>
// only to be included in win32 projects
-const char *StrError(int x)
+const char *StrError(int x)
{
-static char tmp[100];
- switch (x)
- {
- case 10004: return "Interrupted function call.";
- case 10013: return "Permission denied.";
- case 10014: return "Bad address.";
- case 10022: return "Invalid argument.";
- case 10024: return "Too many open files.";
- case 10035: return "Resource temporarily unavailable.";
- case 10036: return "Operation now in progress.";
- case 10037: return "Operation already in progress.";
- case 10038: return "Socket operation on nonsocket.";
- case 10039: return "Destination address required.";
- case 10040: return "Message too long.";
- case 10041: return "Protocol wrong type for socket.";
- case 10042: return "Bad protocol option.";
- case 10043: return "Protocol not supported.";
- case 10044: return "Socket type not supported.";
- case 10045: return "Operation not supported.";
- case 10046: return "Protocol family not supported.";
- case 10047: return "Address family not supported by protocol family.";
- case 10048: return "Address already in use.";
- case 10049: return "Cannot assign requested address.";
- case 10050: return "Network is down.";
- case 10051: return "Network is unreachable.";
- case 10052: return "Network dropped connection on reset.";
- case 10053: return "Software caused connection abort.";
- case 10054: return "Connection reset by peer.";
- case 10055: return "No buffer space available.";
- case 10056: return "Socket is already connected.";
- case 10057: return "Socket is not connected.";
- case 10058: return "Cannot send after socket shutdown.";
- case 10060: return "Connection timed out.";
- case 10061: return "Connection refused.";
- case 10064: return "Host is down.";
- case 10065: return "No route to host.";
- case 10067: return "Too many processes.";
- case 10091: return "Network subsystem is unavailable.";
- case 10092: return "Winsock.dll version out of range.";
- case 10093: return "Successful WSAStartup not yet performed.";
- case 10101: return "Graceful shutdown in progress.";
- case 10109: return "Class type not found.";
- case 11001: return "Host not found.";
- case 11002: return "Nonauthoritative host not found.";
- case 11003: return "This is a nonrecoverable error.";
- case 11004: return "Valid name, no data record of requested type.";
+static char tmp[100];
+ switch (x)
+ {
+ case 10004: return "Interrupted function call.";
+ case 10013: return "Permission denied.";
+ case 10014: return "Bad address.";
+ case 10022: return "Invalid argument.";
+ case 10024: return "Too many open files.";
+ case 10035: return "Resource temporarily unavailable.";
+ case 10036: return "Operation now in progress.";
+ case 10037: return "Operation already in progress.";
+ case 10038: return "Socket operation on nonsocket.";
+ case 10039: return "Destination address required.";
+ case 10040: return "Message too long.";
+ case 10041: return "Protocol wrong type for socket.";
+ case 10042: return "Bad protocol option.";
+ case 10043: return "Protocol not supported.";
+ case 10044: return "Socket type not supported.";
+ case 10045: return "Operation not supported.";
+ case 10046: return "Protocol family not supported.";
+ case 10047: return "Address family not supported by protocol family.";
+ case 10048: return "Address already in use.";
+ case 10049: return "Cannot assign requested address.";
+ case 10050: return "Network is down.";
+ case 10051: return "Network is unreachable.";
+ case 10052: return "Network dropped connection on reset.";
+ case 10053: return "Software caused connection abort.";
+ case 10054: return "Connection reset by peer.";
+ case 10055: return "No buffer space available.";
+ case 10056: return "Socket is already connected.";
+ case 10057: return "Socket is not connected.";
+ case 10058: return "Cannot send after socket shutdown.";
+ case 10060: return "Connection timed out.";
+ case 10061: return "Connection refused.";
+ case 10064: return "Host is down.";
+ case 10065: return "No route to host.";
+ case 10067: return "Too many processes.";
+ case 10091: return "Network subsystem is unavailable.";
+ case 10092: return "Winsock.dll version out of range.";
+ case 10093: return "Successful WSAStartup not yet performed.";
+ case 10101: return "Graceful shutdown in progress.";
+ case 10109: return "Class type not found.";
+ case 11001: return "Host not found.";
+ case 11002: return "Nonauthoritative host not found.";
+ case 11003: return "This is a nonrecoverable error.";
+ case 11004: return "Valid name, no data record of requested type.";
- default:
- break;
- }
- sprintf(tmp, "Winsock error code: %d", x);
- return tmp;
+ default:
+ break;
+ }
+ sprintf(tmp, "Winsock error code: %d", x);
+ return tmp;
}
diff --git a/dep/src/zthread/ConditionImpl.h b/dep/src/zthread/ConditionImpl.h
index eeeaba10bbc..ad1503ef197 100644
--- a/dep/src/zthread/ConditionImpl.h
+++ b/dep/src/zthread/ConditionImpl.h
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
-
+
#ifndef __ZTCONDITIONIMPL_H__
#define __ZTCONDITIONIMPL_H__
@@ -39,16 +39,16 @@ namespace ZThread {
*
* The ConditionImpl template allows how waiter lists are sorted
* to be parameteized
- */
-template <typename List>
+ */
+template <typename List>
class ConditionImpl {
-
+
//! Waiters currently blocked
List _waiters;
//! Serialize access to this object
FastLock _lock;
-
+
//! External lock
Lockable& _predicateLock;
@@ -80,7 +80,7 @@ class ConditionImpl {
};
-template <typename List>
+template <typename List>
ConditionImpl<List>::~ConditionImpl() {
#ifndef NDEBUG
@@ -89,7 +89,7 @@ ConditionImpl<List>::~ConditionImpl() {
if(!_waiters.empty()) {
ZTDEBUG("** You are destroying a condition variable which still has waiting threads. **\n");
- assert(0);
+ assert(0);
}
@@ -101,14 +101,14 @@ ConditionImpl<List>::~ConditionImpl() {
/**
* Signal the condition variable, waking one thread if any.
*/
-template <typename List>
+template <typename List>
void ConditionImpl<List>::signal() {
Guard<FastLock> g1(_lock);
// Try to find a waiter with a backoff & retry scheme
for(;;) {
-
+
// Go through the list, attempt to notify() a waiter.
for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
@@ -117,28 +117,28 @@ void ConditionImpl<List>::signal() {
Monitor& m = impl->getMonitor();
if(m.tryAcquire()) {
-
+
// Notify the monitor & remove from the waiter list so time isn't
// wasted checking it again.
i = _waiters.erase(i);
-
- // If notify() is not sucessful, it is because the wait() has already
+
+ // If notify() is not sucessful, it is because the wait() has already
// been ended (killed/interrupted/notify'd)
bool woke = m.notify();
-
+
m.release();
-
+
// Once notify() succeeds, return
- if(woke)
+ if(woke)
return;
-
+
} else ++i;
-
+
}
-
+
if(_waiters.empty())
return;
-
+
{ // Backoff and try again
Guard<FastLock, UnlockedScope> g2(g1);
@@ -154,14 +154,14 @@ void ConditionImpl<List>::signal() {
* Broadcast to the condition variable, waking all threads waiting at the time of
* the broadcast.
*/
-template <typename List>
+template <typename List>
void ConditionImpl<List>::broadcast() {
Guard<FastLock> g1(_lock);
// Try to find a waiter with a backoff & retry scheme
for(;;) {
-
+
// Go through the list, attempt to notify() a waiter.
for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
@@ -170,21 +170,21 @@ void ConditionImpl<List>::broadcast() {
Monitor& m = impl->getMonitor();
if(m.tryAcquire()) {
-
+
// Notify the monitor & remove from the waiter list so time isn't
// wasted checking it again.
i = _waiters.erase(i);
-
+
// Try to wake the waiter, it doesn't matter if this is successful
- // or not (only fails when the monitor is already going to stop waiting).
+ // or not (only fails when the monitor is already going to stop waiting).
m.notify();
-
+
m.release();
-
+
} else ++i;
-
+
}
-
+
if(_waiters.empty())
return;
@@ -199,16 +199,16 @@ void ConditionImpl<List>::broadcast() {
}
-/**
+/**
* Cause the currently executing thread to block until this ConditionImpl has
* been signaled, the threads state changes.
*
- * @param predicate Lockable&
+ * @param predicate Lockable&
*
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
-template <typename List>
+template <typename List>
void ConditionImpl<List>::wait() {
// Get the monitor for the current thread
@@ -220,13 +220,13 @@ void ConditionImpl<List>::wait() {
{
Guard<FastLock> g1(_lock);
-
- // Release the _predicateLock
+
+ // Release the _predicateLock
_predicateLock.release();
-
+
// Stuff the waiter into the list
_waiters.insert(self);
-
+
// Move to the monitor's lock
m.acquire();
@@ -234,12 +234,12 @@ void ConditionImpl<List>::wait() {
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait();
-
+
}
// Move back to the Condition's lock
m.release();
-
+
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -247,7 +247,7 @@ void ConditionImpl<List>::wait() {
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
-
+
}
// Defer interruption until the external lock is acquire()d
@@ -265,16 +265,16 @@ void ConditionImpl<List>::wait() {
}
switch(state) {
-
+
case Monitor::SIGNALED:
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
default:
throw Synchronization_Exception();
- }
+ }
}
@@ -283,7 +283,7 @@ void ConditionImpl<List>::wait() {
* Cause the currently executing thread to block until this ConditionImpl has
* been signaled, or the timeout expires or the threads state changes.
*
- * @param _predicateLock Lockable&
+ * @param _predicateLock Lockable&
* @param timeout maximum milliseconds to block.
*
* @return bool
@@ -291,9 +291,9 @@ void ConditionImpl<List>::wait() {
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
-template <typename List>
+template <typename List>
bool ConditionImpl<List>::wait(unsigned long timeout) {
-
+
// Get the monitor for the current thread
ThreadImpl* self = ThreadImpl::current();
Monitor& m = self->getMonitor();
@@ -303,18 +303,18 @@ bool ConditionImpl<List>::wait(unsigned long timeout) {
{
Guard<FastLock> g1(_lock);
-
- // Release the _predicateLock
+
+ // Release the _predicateLock
_predicateLock.release();
-
+
// Stuff the waiter into the list
_waiters.insert(self);
-
+
state = Monitor::TIMEDOUT;
-
+
// Don't bother waiting if the timeout is 0
if(timeout) {
-
+
m.acquire();
{
@@ -325,9 +325,9 @@ bool ConditionImpl<List>::wait(unsigned long timeout) {
}
m.release();
-
+
}
-
+
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -335,7 +335,7 @@ bool ConditionImpl<List>::wait(unsigned long timeout) {
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
-
+
}
@@ -354,19 +354,19 @@ bool ConditionImpl<List>::wait(unsigned long timeout) {
}
switch(state) {
-
+
case Monitor::SIGNALED:
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
case Monitor::TIMEDOUT:
return false;
default:
throw Synchronization_Exception();
- }
+ }
return true;
diff --git a/dep/src/zthread/Debug.h b/dep/src/zthread/Debug.h
index 484b37f7d6f..1762de22fe3 100644
--- a/dep/src/zthread/Debug.h
+++ b/dep/src/zthread/Debug.h
@@ -26,7 +26,7 @@
# include <stdio.h>
# define ZTDEBUG printf
#else
-# define ZTDEBUG(x)
+# define ZTDEBUG(x)
#endif
#endif
diff --git a/dep/src/zthread/DeferredInterruptionScope.h b/dep/src/zthread/DeferredInterruptionScope.h
index 041d1e427f6..5205c80ca58 100644
--- a/dep/src/zthread/DeferredInterruptionScope.h
+++ b/dep/src/zthread/DeferredInterruptionScope.h
@@ -34,14 +34,14 @@ namespace ZThread {
* @date <2003-07-16T19:45:18-0400>
* @version 2.3.0
*
- * Locking policy for a Guard that will defer any state reported
- * for the reported Status of a thread except SIGNALED until the
+ * Locking policy for a Guard that will defer any state reported
+ * for the reported Status of a thread except SIGNALED until the
* scope has ended. This allows a Guard to be used to create an
- * uninterruptible region in code.
+ * uninterruptible region in code.
*/
class DeferredInterruptionScope {
public:
-
+
template <class LockType>
static void createScope(LockHolder<LockType>& l) {
diff --git a/dep/src/zthread/FastRecursiveLock.h b/dep/src/zthread/FastRecursiveLock.h
index 0a36f62d5f8..96b66ebe675 100644
--- a/dep/src/zthread/FastRecursiveLock.h
+++ b/dep/src/zthread/FastRecursiveLock.h
@@ -33,11 +33,11 @@
// Select the correct FastRecusriveLock implementation based on
// what the compilation environment has defined
-#if defined(ZTHREAD_DUAL_LOCKS)
+#if defined(ZTHREAD_DUAL_LOCKS)
# include "vanilla/DualMutexRecursiveLock.h"
#else
-# ifndef ZT_VANILLA
+# ifndef ZT_VANILLA
# if defined(ZT_POSIX)
@@ -50,7 +50,7 @@
# include "linux/FastRecursiveLock.h"
# elif defined(HAVE_MUTEXATTR_SETTYPE)
# include "solaris/FastRecursiveLock.h"
-# elif defined(ZTHREAD_CONDITION_LOCKS)
+# elif defined(ZTHREAD_CONDITION_LOCKS)
# include "posix/ConditionRecursiveLock.h"
# endif
diff --git a/dep/src/zthread/IntrusivePtr.h b/dep/src/zthread/IntrusivePtr.h
index 47d5afbfcb8..189ebaf8ad7 100644
--- a/dep/src/zthread/IntrusivePtr.h
+++ b/dep/src/zthread/IntrusivePtr.h
@@ -35,16 +35,16 @@ namespace ZThread {
* @version 2.2.0
*
* This template creates an intrusively reference counted object
- * an IntrusivePtr starts out with a 1 count, which is updated as references are
- * added and removed. When the reference count drops to 0, the
- * IntrusivePtr will delete itself.
+ * an IntrusivePtr starts out with a 1 count, which is updated as references are
+ * added and removed. When the reference count drops to 0, the
+ * IntrusivePtr will delete itself.
*/
template <typename T, class LockType>
class IntrusivePtr : NonCopyable {
-
+
//! Intrusive reference count
size_t _count;
-
+
//! Synchornization object
LockType _lock;
@@ -54,7 +54,7 @@ public:
* Create an IntrusivePtr with a count.
*/
IntrusivePtr(size_t InitialCount=1) : _count(InitialCount) { }
-
+
/**
* Destroy an IntrusivePtr
*/
@@ -67,7 +67,7 @@ public:
void addReference() {
Guard<LockType, LockedScope> g(_lock);
- _count++;
+ _count++;
}
diff --git a/dep/src/zthread/Monitor.h b/dep/src/zthread/Monitor.h
index 6f9492fe32c..1170982292e 100644
--- a/dep/src/zthread/Monitor.h
+++ b/dep/src/zthread/Monitor.h
@@ -29,7 +29,7 @@
# error "Reserved symbol defined"
#endif
-// Include the dependencies for a Montior
+// Include the dependencies for a Montior
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
diff --git a/dep/src/zthread/MutexImpl.h b/dep/src/zthread/MutexImpl.h
index 10a9160ce5a..21338ba289c 100644
--- a/dep/src/zthread/MutexImpl.h
+++ b/dep/src/zthread/MutexImpl.h
@@ -58,14 +58,14 @@ protected:
* @version 2.2.11
* @class MutexImpl
*
- * The MutexImpl template allows how waiter lists are sorted, and
+ * The MutexImpl template allows how waiter lists are sorted, and
* what actions are taken when a thread interacts with the mutex
* to be parametized.
*/
-template <typename List, typename Behavior>
+template <typename List, typename Behavior>
class MutexImpl : Behavior {
- //! List of Events that are waiting for notification
+ //! List of Events that are waiting for notification
List _waiters;
//! Serialize access to this Mutex
@@ -75,7 +75,7 @@ class MutexImpl : Behavior {
volatile ThreadImpl* _owner;
public:
-
+
/**
* Create a new MutexImpl
@@ -84,11 +84,11 @@ class MutexImpl : Behavior {
* properly allocated
*/
MutexImpl() : _owner(0) { }
-
+
~MutexImpl();
void acquire();
-
+
void release();
bool tryAcquire(unsigned long timeout);
@@ -98,20 +98,20 @@ class MutexImpl : Behavior {
/**
* Destroy this MutexImpl and release its resources
*/
-template<typename List, typename Behavior>
+template<typename List, typename Behavior>
MutexImpl<List, Behavior>::~MutexImpl() {
#ifndef NDEBUG
// It is an error to destroy a mutex that has not been released
- if(_owner != 0) {
+ if(_owner != 0) {
ZTDEBUG("** You are destroying a mutex which was never released. **\n");
assert(0); // Destroyed mutex while in use
}
- if(!_waiters.empty()) {
+ if(!_waiters.empty()) {
ZTDEBUG("** You are destroying a mutex which is blocking %d threads. **\n", _waiters.size());
assert(0); // Destroyed mutex while in use
@@ -125,7 +125,7 @@ MutexImpl<List, Behavior>::~MutexImpl() {
/**
* Acquire a lock on the mutex. If this operation succeeds the calling
- * thread holds an exclusive lock on this mutex, otherwise it is blocked
+ * thread holds an exclusive lock on this mutex, otherwise it is blocked
* until the lock can be acquired.
*
* @exception Deadlock_Exception thrown when the caller attempts to acquire() more
@@ -133,7 +133,7 @@ MutexImpl<List, Behavior>::~MutexImpl() {
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
-template<typename List, typename Behavior>
+template<typename List, typename Behavior>
void MutexImpl<List, Behavior>::acquire() {
ThreadImpl* self = ThreadImpl::current();
@@ -142,41 +142,41 @@ void MutexImpl<List, Behavior>::acquire() {
Monitor::STATE state;
Guard<FastLock> g1(_lock);
-
- // Deadlock will occur if the current thread is the owner
+
+ // Deadlock will occur if the current thread is the owner
// and there is no entry count.
- if(_owner == self)
+ if(_owner == self)
throw Deadlock_Exception();
-
+
// Acquire the lock if it is free and there are no waiting threads
if(_owner == 0 && _waiters.empty()) {
_owner = self;
this->ownerAcquired(self);
-
+
}
// Otherwise, wait for a signal from a thread releasing its
// ownership of the lock
- else {
-
+ else {
+
_waiters.insert(self);
m.acquire();
this->waiterArrived(self);
- {
-
+ {
+
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait();
-
+
}
this->waiterDeparted(self);
m.release();
-
+
// Remove from waiter list, regardless of wether release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -185,26 +185,26 @@ void MutexImpl<List, Behavior>::acquire() {
if(i != _waiters.end())
_waiters.erase(i);
- // If awoke due to a notify(), take ownership.
+ // If awoke due to a notify(), take ownership.
switch(state) {
case Monitor::SIGNALED:
assert(_owner == 0);
- _owner = self;
+ _owner = self;
this->ownerAcquired(self);
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
default:
throw Synchronization_Exception();
- }
-
+ }
+
}
-
+
}
@@ -218,17 +218,17 @@ void MutexImpl<List, Behavior>::acquire() {
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
-template<typename List, typename Behavior>
+template<typename List, typename Behavior>
bool MutexImpl<List, Behavior>::tryAcquire(unsigned long timeout) {
-
+
ThreadImpl* self = ThreadImpl::current();
Monitor& m = self->getMonitor();
Guard<FastLock> g1(_lock);
-
- // Deadlock will occur if the current thread is the owner
+
+ // Deadlock will occur if the current thread is the owner
// and there is no entry count.
- if(_owner == self)
+ if(_owner == self)
throw Deadlock_Exception();
// Acquire the lock if it is free and there are no waiting threads
@@ -237,38 +237,38 @@ bool MutexImpl<List, Behavior>::tryAcquire(unsigned long timeout) {
_owner = self;
this->ownerAcquired(self);
-
+
}
// Otherwise, wait for a signal from a thread releasing its
// ownership of the lock
else {
-
+
_waiters.insert(self);
-
+
Monitor::STATE state = Monitor::TIMEDOUT;
-
+
// Don't bother waiting if the timeout is 0
if(timeout) {
-
+
m.acquire();
this->waiterArrived(self);
-
+
{
-
+
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait(timeout);
-
+
}
this->waiterDeparted(self);
-
+
m.release();
-
+
}
-
-
+
+
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -276,50 +276,50 @@ bool MutexImpl<List, Behavior>::tryAcquire(unsigned long timeout) {
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
-
- // If awoke due to a notify(), take ownership.
+
+ // If awoke due to a notify(), take ownership.
switch(state) {
case Monitor::SIGNALED:
-
+
assert(0 == _owner);
_owner = self;
this->ownerAcquired(self);
-
+
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
case Monitor::TIMEDOUT:
return false;
-
+
default:
throw Synchronization_Exception();
- }
-
+ }
+
}
-
+
return true;
-
+
}
/**
* Release a lock on the mutex. If this operation succeeds the calling
- * thread no longer holds an exclusive lock on this mutex. If there are
- * waiting threads, one will be selected, assigned ownership and specifically
+ * thread no longer holds an exclusive lock on this mutex. If there are
+ * waiting threads, one will be selected, assigned ownership and specifically
* awakened.
*
- * @exception InvalidOp_Exception - thrown if an attempt is made to
+ * @exception InvalidOp_Exception - thrown if an attempt is made to
* release a mutex not owned by the calling thread.
*/
-template<typename List, typename Behavior>
+template<typename List, typename Behavior>
void MutexImpl<List, Behavior>::release() {
ThreadImpl* impl = ThreadImpl::current();
Guard<FastLock> g1(_lock);
-
+
// Make sure the operation is valid
if(_owner != impl)
throw InvalidOp_Exception();
@@ -327,45 +327,45 @@ void MutexImpl<List, Behavior>::release() {
_owner = 0;
this->ownerReleased(impl);
-
+
// Try to find a waiter with a backoff & retry scheme
for(;;) {
-
+
// Go through the list, attempt to notify() a waiter.
for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
-
+
// Try the monitor lock, if it cant be locked skip to the next waiter
impl = *i;
Monitor& m = impl->getMonitor();
if(m.tryAcquire()) {
-
- // If notify() is not sucessful, it is because the wait() has already
+
+ // If notify() is not sucessful, it is because the wait() has already
// been ended (killed/interrupted/notify'd)
bool woke = m.notify();
-
+
m.release();
-
+
// Once notify() succeeds, return
if(woke)
return;
-
+
} else ++i;
-
+
}
-
+
if(_waiters.empty())
return;
{ // Backoff and try again
-
+
Guard<FastLock, UnlockedScope> g2(g1);
ThreadImpl::yield();
}
}
-
+
}
} // namespace ZThread
diff --git a/dep/src/zthread/RecursiveMutexImpl.h b/dep/src/zthread/RecursiveMutexImpl.h
index 9e1ae050c5b..1e477136f52 100644
--- a/dep/src/zthread/RecursiveMutexImpl.h
+++ b/dep/src/zthread/RecursiveMutexImpl.h
@@ -39,14 +39,14 @@ namespace ZThread {
* @date <2003-07-16T19:58:26-0400>
* @version 2.1.6
*
- * This synchronization object provides serialized access
- * through an acquire/release protocol.
+ * This synchronization object provides serialized access
+ * through an acquire/release protocol.
*/
class ZTHREAD_API RecursiveMutexImpl {
-
- typedef std::vector<Monitor*> List;
- //! List of Events that are waiting for notification
+ typedef std::vector<Monitor*> List;
+
+ //! List of Events that are waiting for notification
List _waiters;
//! Serialize access to this Mutex
@@ -55,24 +55,24 @@ namespace ZThread {
//! Current owning Event object
Monitor* _owner;
- //! Entry count
+ //! Entry count
size_t _count;
public:
-
- RecursiveMutexImpl();
+
+ RecursiveMutexImpl();
virtual ~RecursiveMutexImpl();
-
+
void acquire();
-
+
bool tryAcquire(unsigned long);
-
- void release();
+
+ void release();
}; /* RecursiveMutexImpl */
-};
+};
#endif
diff --git a/dep/src/zthread/Scheduling.h b/dep/src/zthread/Scheduling.h
index b12f7fff0b6..00061341d62 100644
--- a/dep/src/zthread/Scheduling.h
+++ b/dep/src/zthread/Scheduling.h
@@ -52,7 +52,7 @@ namespace ZThread {
* @struct priority_order
*/
struct priority_order : public std::binary_function<ThreadImpl*, ThreadImpl*, bool> {
-
+
std::less<const ThreadImpl*> id;
bool operator()(const ThreadImpl* t0, const ThreadImpl* t1) const {
@@ -66,7 +66,7 @@ namespace ZThread {
return id(t0, t1);
}
-
+
};
@@ -76,15 +76,15 @@ namespace ZThread {
* @version 2.2.0
* @class priority_list
*/
- class priority_list : public std::deque<ThreadImpl*> {
+ class priority_list : public std::deque<ThreadImpl*> {
priority_order comp;
public:
- void insert(const value_type& val) {
+ void insert(const value_type& val) {
- push_back(val);
+ push_back(val);
std::sort(begin(), end(), comp);
}
diff --git a/dep/src/zthread/SemaphoreImpl.h b/dep/src/zthread/SemaphoreImpl.h
index 086c4333fd0..7f1b866c387 100644
--- a/dep/src/zthread/SemaphoreImpl.h
+++ b/dep/src/zthread/SemaphoreImpl.h
@@ -44,7 +44,7 @@ namespace ZThread {
* The SemaphoreImpl template allows how waiter lists are sorted
* to be parameteized
*/
- template <typename List>
+ template <typename List>
class SemaphoreImpl {
//! List of waiting events
@@ -58,7 +58,7 @@ namespace ZThread {
//! Maximum count if any
volatile int _maxCount;
-
+
//! Flag for bounded or unbounded count
volatile bool _checked;
@@ -66,41 +66,41 @@ namespace ZThread {
volatile int _entryCount;
public:
-
-
+
+
/**
- * Create a new SemaphoreImpl. Initialzes one pthreads mutex for
+ * Create a new SemaphoreImpl. Initialzes one pthreads mutex for
* internal use.
*
* @exception Initialization_Exception thrown if resources could not be
* properly allocated
*/
- SemaphoreImpl(int count, unsigned int maxCount, bool checked)
+ SemaphoreImpl(int count, unsigned int maxCount, bool checked)
: _count(count), _maxCount(maxCount), _checked(checked), _entryCount(0) { }
~SemaphoreImpl();
void acquire();
-
+
void release();
bool tryAcquire(unsigned long timeout);
-
+
int count();
- };
+ };
/**
- * Destroy this SemaphoreImpl and release its resources.
+ * Destroy this SemaphoreImpl and release its resources.
*/
- template <typename List>
+ template <typename List>
SemaphoreImpl<List>::~SemaphoreImpl() {
#ifndef NDEBUG
- if(!_waiters.empty()) {
+ if(!_waiters.empty()) {
ZTDEBUG("** You are destroying a semaphore which is blocking %d threads. **\n", _waiters.size());
assert(0); // Destroyed semaphore while in use
@@ -117,21 +117,21 @@ namespace ZThread {
*
* @return int
*/
- template <typename List>
+ template <typename List>
int SemaphoreImpl<List>::count() {
Guard<FastLock> g(_lock);
return _count;
-
+
}
/**
* Decrement the count, blocking when that count becomes 0 or less.
- *
+ *
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
- template <typename List>
+ template <typename List>
void SemaphoreImpl<List>::acquire() {
// Get the monitor for the current thread
@@ -155,14 +155,14 @@ namespace ZThread {
m.acquire();
{
-
+
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait();
-
+
}
m.release();
-
+
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -170,38 +170,38 @@ namespace ZThread {
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
-
+
--_entryCount;
switch(state) {
// If awoke due to a notify(), update the count
case Monitor::SIGNALED:
-
- _count--;
+
+ _count--;
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
default:
throw Synchronization_Exception();
- }
-
+ }
+
}
}
/**
* Decrement the count, blocking when it that count is 0 or less. If the timeout
- * expires before the count is raise above 0, the thread will stop blocking
+ * expires before the count is raise above 0, the thread will stop blocking
* and return.
- *
+ *
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
- template <typename List>
+ template <typename List>
bool SemaphoreImpl<List>::tryAcquire(unsigned long timeout) {
-
+
// Get the monitor for the current thread
ThreadImpl* self = ThreadImpl::current();
Monitor& m = self->getMonitor();
@@ -214,7 +214,7 @@ namespace ZThread {
// Otherwise, wait() for the lock by placing the waiter in the list
else {
-
+
++_entryCount;
_waiters.push_back(self);
@@ -222,20 +222,20 @@ namespace ZThread {
// Don't bother waiting if the timeout is 0
if(timeout) {
-
+
m.acquire();
{
-
+
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait(timeout);
-
+
}
m.release();
-
+
}
-
+
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
@@ -243,26 +243,26 @@ namespace ZThread {
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
-
+
--_entryCount;
switch(state) {
// If awoke due to a notify(), update the count
case Monitor::SIGNALED:
-
- _count--;
+
+ _count--;
break;
-
+
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
-
+
case Monitor::TIMEDOUT:
return false;
default:
throw Synchronization_Exception();
- }
-
+ }
+
}
return true;
@@ -272,18 +272,18 @@ namespace ZThread {
/**
* Increment the count and release a waiter if there are any. If the semaphore
* is checked, then an exception will be raised if the maximum count is about to
- * be exceeded.
+ * be exceeded.
*
* @exception InvalidOp_Exception thrown if the maximum count is exceeded while
* the checked flag is set.
*/
- template <typename List>
+ template <typename List>
void SemaphoreImpl<List>::release() {
Guard<FastLock> g1(_lock);
// Make sure the operation is valid
- if(_checked && _count == _maxCount)
+ if(_checked && _count == _maxCount)
throw InvalidOp_Exception();
// Increment the count
@@ -291,7 +291,7 @@ namespace ZThread {
// Try to find a waiter with a backoff & retry scheme
for(;;) {
-
+
// Go through the list, attempt to notify() a waiter.
for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
@@ -300,43 +300,43 @@ namespace ZThread {
Monitor& m = impl->getMonitor();
if(m.tryAcquire()) {
-
+
// Notify the monitor & remove from the waiter list so time isn't
// wasted checking it again.
i = _waiters.erase(i);
-
- // If notify() is not sucessful, it is because the wait() has already
+
+ // If notify() is not sucessful, it is because the wait() has already
// been ended (killed/interrupted/notify'd)
bool woke = m.notify();
-
+
m.release();
-
+
// Once notify() succeeds, return
- if(woke)
+ if(woke)
return;
-
+
} else ++i;
-
+
}
-
+
if(_waiters.empty())
return;
-
+
{ // Backoff and try again
-
+
Guard<FastLock, UnlockedScope> g2(g1);
ThreadImpl::yield();
}
}
-
+
}
- class FifoSemaphoreImpl : public SemaphoreImpl<fifo_list> {
+ class FifoSemaphoreImpl : public SemaphoreImpl<fifo_list> {
public:
- FifoSemaphoreImpl(int count, unsigned int maxCount, bool checked)
+ FifoSemaphoreImpl(int count, unsigned int maxCount, bool checked)
/* throw(Synchronization_Exception) */
: SemaphoreImpl<fifo_list>(count, maxCount, checked) { }
diff --git a/dep/src/zthread/State.h b/dep/src/zthread/State.h
index 85279f4bde8..96697c9d4bd 100644
--- a/dep/src/zthread/State.h
+++ b/dep/src/zthread/State.h
@@ -26,7 +26,7 @@
namespace ZThread {
/**
- * @class State
+ * @class State
* @author Eric Crahen <http://www.code-foo.com>
* @date <2003-07-16T20:04:01-0400>
* @version 2.2.1
@@ -52,7 +52,7 @@ class State {
}
/**
- * Test for the JOINED state. A task has completed and
+ * Test for the JOINED state. A task has completed and
* the thread is join()ed.
*
* @return bool
diff --git a/dep/src/zthread/Status.h b/dep/src/zthread/Status.h
index 4735e352861..a56d505a8f4 100644
--- a/dep/src/zthread/Status.h
+++ b/dep/src/zthread/Status.h
@@ -37,22 +37,22 @@ namespace ZThread {
class Status {
public:
//! Aggregate of pending status changes
- volatile unsigned short _pending;
-
- //! Interest mask
+ volatile unsigned short _pending;
+
+ //! Interest mask
volatile unsigned short _mask;
public:
-
+
//! State for the monitor
typedef enum {
-
+
// Default
INVALID = 0x00,
// Valid states
SIGNALED = 0x01,
- INTERRUPTED = 0x02,
+ INTERRUPTED = 0x02,
TIMEDOUT = 0x04,
CANCELED = 0x08,
@@ -62,10 +62,10 @@ namespace ZThread {
} STATE;
Status() : _pending((unsigned short)INVALID), _mask((unsigned short)ANYTHING) { }
-
+
/**
* Set the mask for the STATE's that next() will report.
- * STATE's not covered by the interest mask can still be
+ * STATE's not covered by the interest mask can still be
* set, they just aren't reported until the mask is changed
* to cover that STATE.
*
@@ -87,19 +87,19 @@ namespace ZThread {
*
* @param unsigned short
* @pre accessed ONLY by the owning thread.
- */
+ */
bool pending(unsigned short mask) {
-
+
assert(mask != INVALID);
return ((_pending & _mask) & mask) != INVALID;
}
/**
- * Check the state without the interest mask.
+ * Check the state without the interest mask.
*
- * @param state
- * @return true if the flag is set
+ * @param state
+ * @return true if the flag is set
* @pre access must be serial
*/
bool examine(STATE state) {
@@ -113,12 +113,12 @@ namespace ZThread {
* @pre access must be serial
*/
void push(STATE interest) {
- _pending |= interest;
+ _pending |= interest;
}
/**
* Clear the flags from the current state
- *
+ *
* @param interest - the flags to clear from the current state.
* @pre access must be serial
*/
@@ -129,16 +129,16 @@ namespace ZThread {
assert(interest != CANCELED);
_pending &= ~interest;
-
+
}
/**
* Get the next state from set that has accumulated. The order STATES are
- * reported in is SIGNALED, TIMEOUT, or INTERRUPTED. Setting the
- * intrest mask allows certain state to be selectively ignored for
+ * reported in is SIGNALED, TIMEOUT, or INTERRUPTED. Setting the
+ * intrest mask allows certain state to be selectively ignored for
* a time - but not lost. The states will become visible again as soon
- * as the interest mask is changed appropriately. The interest mask is
- * generally used to create uninterruptable waits (waiting for threads
+ * as the interest mask is changed appropriately. The interest mask is
+ * generally used to create uninterruptable waits (waiting for threads
* to start, reacquiring a conditions predicate lock, etc)
*
* @return STATE
@@ -147,29 +147,29 @@ namespace ZThread {
STATE next() {
STATE state = INVALID;
-
+
if(((_pending & _mask) & SIGNALED) != 0) {
-
+
// Absorb the timeout if it happens when a signal
// is available at the same time
_pending &= ~(SIGNALED|TIMEDOUT);
state = SIGNALED;
-
+
} else if(((_pending & _mask) & TIMEDOUT) != 0) {
_pending &= ~TIMEDOUT;
state = TIMEDOUT;
} else if(((_pending & _mask) & INTERRUPTED) != 0) {
-
+
_pending &= ~INTERRUPTED;
state = INTERRUPTED;
-
- }
-
+
+ }
+
assert(state != INVALID);
return state;
-
+
}
};
diff --git a/dep/src/zthread/ThreadImpl.h b/dep/src/zthread/ThreadImpl.h
index ae2c8f23960..f464242918c 100644
--- a/dep/src/zthread/ThreadImpl.h
+++ b/dep/src/zthread/ThreadImpl.h
@@ -53,7 +53,7 @@ class ThreadImpl : public IntrusivePtr<ThreadImpl, FastLock>, public ThreadOps {
//! The Monitor for controlling this thread
Monitor _monitor;
-
+
//! Current state for the thread
State _state;
@@ -61,11 +61,11 @@ class ThreadImpl : public IntrusivePtr<ThreadImpl, FastLock>, public ThreadOps {
List _joiners;
public:
-
+
typedef std::map<const ThreadLocalImpl*, ThreadLocalImpl::ValuePtr > ThreadLocalMap;
private:
-
+
ThreadLocalMap _tls;
//! Cached thread priority
@@ -73,7 +73,7 @@ class ThreadImpl : public IntrusivePtr<ThreadImpl, FastLock>, public ThreadOps {
//! Request cancel() when main() goes out of scope
bool _autoCancel;
-
+
void start(const Task& task);
public:
@@ -82,7 +82,7 @@ class ThreadImpl : public IntrusivePtr<ThreadImpl, FastLock>, public ThreadOps {
ThreadImpl(const Task&, bool);
- ~ThreadImpl();
+ ~ThreadImpl();
Monitor& getMonitor();
@@ -99,24 +99,24 @@ class ThreadImpl : public IntrusivePtr<ThreadImpl, FastLock>, public ThreadOps {
// ThreadLocalMap& getThreadLocalMap();
ThreadLocalMap& getThreadLocalMap() { return _tls; }
- bool join(unsigned long);
-
+ bool join(unsigned long);
+
void setPriority(Priority);
bool isActive();
bool isReference();
- static void sleep(unsigned long);
+ static void sleep(unsigned long);
static void yield();
-
+
static ThreadImpl* current();
static void dispatch(ThreadImpl*, ThreadImpl*, Task);
};
-} // namespace ZThread
+} // namespace ZThread
#endif // __ZTTHREADIMPL_H__
diff --git a/dep/src/zthread/ThreadOps.h b/dep/src/zthread/ThreadOps.h
index eef9f3c6e31..d8737158e3e 100644
--- a/dep/src/zthread/ThreadOps.h
+++ b/dep/src/zthread/ThreadOps.h
@@ -39,9 +39,9 @@
#elif defined(ZT_WIN32) || defined(ZT_WIN9X)
// Visual C provides the _beginthreadex function, other compilers
-// might not have this if they don't use Microsoft's C runtime.
-// _beginthreadex is similar to in effect defining REENTRANT on a
-// POSIX system. CreateThreadEx doesn't use reentrant parts of the
+// might not have this if they don't use Microsoft's C runtime.
+// _beginthreadex is similar to in effect defining REENTRANT on a
+// POSIX system. CreateThreadEx doesn't use reentrant parts of the
// Microsfot C runtime, but if your not using that runtime, no problem.
# if !defined(HAVE_BEGINTHREADEX)
diff --git a/dep/src/zthread/ThreadQueue.h b/dep/src/zthread/ThreadQueue.h
index 044f8263026..72049fda3b2 100644
--- a/dep/src/zthread/ThreadQueue.h
+++ b/dep/src/zthread/ThreadQueue.h
@@ -31,7 +31,7 @@
namespace ZThread {
class ThreadImpl;
-
+
/**
* @class ThreadQueue
* @version 2.3.0
@@ -41,7 +41,7 @@ namespace ZThread {
* A ThreadQueue accumulates references to user and reference threads.
* These are threads that are running outside the scope of the Thread
* object that created them. ZThreads doesn't have a central manager for
- * all threads (partly why I renamed the ThreadManager to someting more
+ * all threads (partly why I renamed the ThreadManager to someting more
* appropriate). Instead, ZThreads will discover threads it did not create
* and create a reference thread that allows ZThreads to interact with it.
* Non user threads that are created by the user never have to touch the
@@ -56,19 +56,19 @@ namespace ZThread {
ThreadList _pendingThreads;
ThreadList _referenceThreads;
ThreadList _userThreads;
-
+
//! Shutdown handlers
TaskList _shutdownTasks;
//! Serilize access to the thread list
FastLock _lock;
-
+
//! Reference thread waiting to cleanup any user & reference threads
ThreadImpl* _waiter;
public:
- ThreadQueue();
+ ThreadQueue();
/**
* The thread destroys a ThreadQueue will be a reference thread,
@@ -84,16 +84,16 @@ namespace ZThread {
*
* User-threads are known to be executing thier tasks and will be cancel()ed
* as the ThreadQueue is destroyed when main() goes out of scope. This sends
- * a request to the task to complete soon. Once the task exits, the thread is
+ * a request to the task to complete soon. Once the task exits, the thread is
* transitioned to pending-thread status.
*/
void insertUserThread(ThreadImpl*);
/**
- * Insert a pending-thread into the queue.
- *
- * Pending-threads are known to have completed thier tasks and thier
- * resources are reclaimed (lazily) as more threads are started or as the
+ * Insert a pending-thread into the queue.
+ *
+ * Pending-threads are known to have completed thier tasks and thier
+ * resources are reclaimed (lazily) as more threads are started or as the
* ThreadQueue is destroyed.
*/
void insertPendingThread(ThreadImpl*);
@@ -106,8 +106,8 @@ namespace ZThread {
void insertReferenceThread(ThreadImpl*);
/**
- * Insert a task to be run before threads are joined.
- * Any items inserted after the ThreadQueue desctructor has begun to
+ * Insert a task to be run before threads are joined.
+ * Any items inserted after the ThreadQueue desctructor has begun to
* execute will be run() immediately.
*/
void insertShutdownTask(Task&);
@@ -126,7 +126,7 @@ namespace ZThread {
void pollReferenceThreads();
};
-
+
} // namespace ZThread
diff --git a/dep/src/zthread/TimeStrategy.h b/dep/src/zthread/TimeStrategy.h
index 0b9ad1e22ba..249d8ab5a64 100644
--- a/dep/src/zthread/TimeStrategy.h
+++ b/dep/src/zthread/TimeStrategy.h
@@ -65,7 +65,7 @@
# include "macos/UpTimeStrategy.h"
#elif defined(HAVE_PERFORMANCECOUNTER)
-
+
# include "win32/PerformanceCounterStrategy.h"
#elif defined(HAVE_FTIME)
diff --git a/dep/src/zthread/config.h b/dep/src/zthread/config.h
index 0b630dcc36c..4ef2ca213d1 100644
--- a/dep/src/zthread/config.h
+++ b/dep/src/zthread/config.h
@@ -23,22 +23,22 @@
#define HAVE_MEMORY_H 1
/* defined when pthreads is available */
-#define HAVE_POSIX_THREADS
+#define HAVE_POSIX_THREADS
/* Defined if pthread_keycreate() is available */
/* #undef HAVE_PTHREADKEYCREATE */
/* Defined if pthread_key_create() is available */
-#define HAVE_PTHREADKEY_CREATE
+#define HAVE_PTHREADKEY_CREATE
/* Defined if pthread_yield() is available */
-#define HAVE_PTHREAD_YIELD
+#define HAVE_PTHREAD_YIELD
/* Defined if -lrt is needed for RT scheduling */
-#define HAVE_SCHED_RT
+#define HAVE_SCHED_RT
/* Defined if sched_yield() is available */
-#define HAVE_SCHED_YIELD
+#define HAVE_SCHED_YIELD
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
diff --git a/dep/src/zthread/linux/AtomicFastLock.h b/dep/src/zthread/linux/AtomicFastLock.h
index b9aa1babcd6..a416fef67cb 100644
--- a/dep/src/zthread/linux/AtomicFastLock.h
+++ b/dep/src/zthread/linux/AtomicFastLock.h
@@ -44,31 +44,31 @@ namespace ZThread {
* This implementation of a FastLock uses the atomic operations that
* linux provides with its kernel sources. This demonstrates how to implement
* a spinlock with a decrement and test primative.
- */
+ */
class FastLock : private NonCopyable {
-
+
atomic_t _value;
-
+
#if !defined(NDEBUG)
pthread_t _owner;
#endif
public:
-
+
inline FastLock() {
-
+
atomic_t tmp = ATOMIC_INIT(1);
_value = tmp;
}
-
+
inline ~FastLock() {
assert(atomic_read(&_value) == 1);
assert(_owner == 0);
}
-
+
inline void acquire() {
while(!atomic_dec_and_test(&_value)) {
@@ -77,14 +77,14 @@ public:
ThreadOps::yield();
}
-
+
#if !defined(NDEBUG)
_owner = pthread_self();
#endif
}
inline void release() {
-
+
#if !defined(NDEBUG)
assert(pthread_equal(_owner, pthread_self()) != 0);
#endif
@@ -93,9 +93,9 @@ public:
_owner = 0;
}
-
+
inline bool tryAcquire(unsigned long timeout=0) {
-
+
bool wasLocked = atomic_dec_and_test(&_value);
if(!wasLocked)
atomic_inc(&_value);
@@ -106,9 +106,9 @@ public:
#endif
return wasLocked;
-
+
}
-
+
}; /* FastLock */
diff --git a/dep/src/zthread/linux/FastRecursiveLock.h b/dep/src/zthread/linux/FastRecursiveLock.h
index d253652cb53..a9a74d21521 100644
--- a/dep/src/zthread/linux/FastRecursiveLock.h
+++ b/dep/src/zthread/linux/FastRecursiveLock.h
@@ -36,45 +36,45 @@ namespace ZThread {
* @version 2.2.0
*
* This implementation of a FastRecursiveLock uses the recursive mutex
- * that linux pthreads provides.
- */
+ * that linux pthreads provides.
+ */
class FastRecursiveLock : private NonCopyable {
-
+
pthread_mutex_t _mtx;
-
+
public:
-
+
inline FastRecursiveLock() {
-
+
static const pthread_mutexattr_t attr = { PTHREAD_MUTEX_RECURSIVE_NP };
pthread_mutex_init(&_mtx, &attr);
}
-
+
inline ~FastRecursiveLock() {
pthread_mutex_destroy(&_mtx);
}
-
+
inline void acquire() {
-
+
pthread_mutex_lock(&_mtx);
}
inline void release() {
-
+
pthread_mutex_unlock(&_mtx);
-
+
}
-
+
inline bool tryAcquire(unsigned long timeout=0) {
return (pthread_mutex_trylock(&_mtx) == 0);
}
-
+
}; /* FastRecursiveLock */
diff --git a/dep/src/zthread/macos/FastLock.h b/dep/src/zthread/macos/FastLock.h
index bae5c482903..0bd40e1f2fd 100644
--- a/dep/src/zthread/macos/FastLock.h
+++ b/dep/src/zthread/macos/FastLock.h
@@ -39,48 +39,48 @@ namespace ZThread {
* @date <2003-07-16T23:25:31-0400>
* @version 2.1.6
*
- */
+ */
class FastLock : private NonCopyable {
-
+
MPCriticalRegionID _mtx;
public:
-
+
/**
* Create a new FastLock. No safety or state checks are performed.
*
* @exception Initialization_Exception - not thrown
*/
inline FastLock() {
-
+
// Apple TN1071
static bool init = MPLibraryIsLoaded();
-
+
if(!init || MPCreateCriticalRegion(&_mtx) != noErr) {
assert(0);
throw Initialization_Exception();
}
}
-
+
/**
* Destroy a FastLock. No safety or state checks are performed.
*/
inline ~FastLock() throw () {
OSStatus status = MPDeleteCriticalRegion(_mtx);
- if(status != noErr)
+ if(status != noErr)
assert(false);
}
-
+
/**
* Acquire an exclusive lock. No safety or state checks are performed.
*
* @exception Synchronization_Exception - not thrown
*/
inline void acquire() {
-
+
if(MPEnterCriticalRegion(_mtx, kDurationForever) != noErr)
throw Synchronization_Exception();
@@ -96,38 +96,38 @@ class FastLock : private NonCopyable {
*/
inline bool tryAcquire(unsigned long timeout=0) {
- OSStatus status =
+ OSStatus status =
MPEnterCriticalRegion(_mtx, kDurationMillisecond * timeout);
switch(status) {
case kMPTimeoutErr:
return false;
-
+
case noErr:
return true;
-
- }
-
+
+ }
+
assert(0);
throw Synchronization_Exception();
}
-
+
/**
* Release an exclusive lock. No safety or state checks are performed.
- * The caller should have already acquired the lock, and release it
+ * The caller should have already acquired the lock, and release it
* only once.
- *
+ *
* @exception Synchronization_Exception - not thrown
*/
inline void release() {
-
+
if(MPExitCriticalRegion(_mtx) != noErr)
throw Synchronization_Exception();
}
-
-
+
+
}; /* FastLock */
diff --git a/dep/src/zthread/macos/Monitor.h b/dep/src/zthread/macos/Monitor.h
index f4312d7b7ee..9fa3c9a5aa2 100644
--- a/dep/src/zthread/macos/Monitor.h
+++ b/dep/src/zthread/macos/Monitor.h
@@ -49,40 +49,40 @@ class Monitor : public Status, private NonCopyable {
MPTaskID _owner;
//! Waiting flag, to avoid uneccessary signals
- volatile bool _waiting;
+ volatile bool _waiting;
//! Waiting flag, to avoid too many signals
- volatile bool _pending;
+ volatile bool _pending;
//! State of the monitor
volatile int _state;
-
+
public:
-
+
//! Create a new monitor.
Monitor();
//! Destroy the monitor.
~Monitor() throw();
- //! Acquire the external lock for this monitor.
+ //! Acquire the external lock for this monitor.
inline void acquire() {
_lock.acquire();
}
- //! Try to acquire the external lock for this monitor.
+ //! Try to acquire the external lock for this monitor.
inline bool tryAcquire() {
return _lock.tryAcquire();
}
- //! Release the external lock for this monitor.
+ //! Release the external lock for this monitor.
inline void release() {
_lock.release();
}
-
+
/**
* Wait for a state change and atomically unlock the external lock.
- * Blocks for an indefinent amount of time.
+ * Blocks for an indefinent amount of time.
*
* @return INTERRUPTED if the wait was ended by a interrupt()
* or SIGNALED if the wait was ended by a notify()
@@ -95,11 +95,11 @@ class Monitor : public Status, private NonCopyable {
/**
* Wait for a state change and atomically unlock the external lock.
- * May blocks for an indefinent amount of time.
+ * May blocks for an indefinent amount of time.
*
* @param timeout - maximum time to block (milliseconds) or 0 to
* block indefinently
- *
+ *
* @return INTERRUPTED if the wait was ended by a interrupt()
* or TIMEDOUT if the maximum wait time expired.
* or SIGNALED if the wait was ended by a notify()
@@ -119,9 +119,9 @@ class Monitor : public Status, private NonCopyable {
/**
* Notify this monitor. If there is a thread blocked on this monitor object
- * it will be signaled and released. If there is no waiter, a flag is set and
- * the next attempt to wait() will return SIGNALED w/o blocking, if no other
- * flag is set.
+ * it will be signaled and released. If there is no waiter, a flag is set and
+ * the next attempt to wait() will return SIGNALED w/o blocking, if no other
+ * flag is set.
*
* @return false if the thread was previously INTERRUPTED.
*/
diff --git a/dep/src/zthread/macos/TSS.h b/dep/src/zthread/macos/TSS.h
index 3f9805d0f7c..1be90c5f278 100644
--- a/dep/src/zthread/macos/TSS.h
+++ b/dep/src/zthread/macos/TSS.h
@@ -38,7 +38,7 @@ namespace ZThread {
* @date <2003-07-27T14:19:10-0400>
* @version 2.1.6
*
- * An abstraction for dealing with POSIX thread specific storage (tss).
+ * An abstraction for dealing with POSIX thread specific storage (tss).
* Provides get/set and creation/destruction.
*/
template <typename T>
@@ -49,13 +49,13 @@ namespace ZThread {
public:
/**
- * Create a new object for accessing tss.
+ * Create a new object for accessing tss.
*/
TSS() {
// Apple TN1071
static bool init = MPLibraryIsLoaded();
-
+
if(!init || MPAllocateTaskStorageIndex(&_key) != noErr) {
assert(0);
throw Initialization_Exception();
@@ -64,17 +64,17 @@ namespace ZThread {
}
/**
- * Destroy the underlying supoprt for accessing tss with this
+ * Destroy the underlying supoprt for accessing tss with this
* object.
*/
~TSS() {
-
+
OSStatus status = MPDeallocateTaskStorageIndex(_key);
- if(status != noErr)
+ if(status != noErr)
assert(0);
}
-
+
/**
* Get the value stored in tss.
*
@@ -85,8 +85,8 @@ namespace ZThread {
T get() const {
return reinterpret_cast<T>(MPGetTaskStorageValue(_key));
}
-
-
+
+
/**
* Store a value in tss.
*
@@ -99,18 +99,18 @@ namespace ZThread {
T oldValue = get();
- OSStatus status =
+ OSStatus status =
MPSetTaskStorageValue(_key, reinterpret_cast<TaskStorageValue>(value));
-
+
if(status != noErr) {
assert(0);
throw Synchronization_Exception();
}
return oldValue;
-
+
}
-
+
};
}
diff --git a/dep/src/zthread/macos/ThreadOps.h b/dep/src/zthread/macos/ThreadOps.h
index c100fcfefe5..5c4eb044e73 100644
--- a/dep/src/zthread/macos/ThreadOps.h
+++ b/dep/src/zthread/macos/ThreadOps.h
@@ -33,14 +33,14 @@
namespace ZThread {
class Runnable;
-
+
/**
* @class ThreadOps
* @author Eric Crahen <http://www.code-foo.com>
* @date <2003-07-16T23:26:01-0400>
* @version 2.2.0
*
- * This class is an abstraction used to perform various operations on a
+ * This class is an abstraction used to perform various operations on a
* native POSIX thread.
*/
class ThreadOps {
@@ -55,10 +55,10 @@ class ThreadOps {
public:
- const static ThreadOps INVALID;
+ const static ThreadOps INVALID;
/**
- * Create a new ThreadOps to manipulate a native thread.
+ * Create a new ThreadOps to manipulate a native thread.
*/
ThreadOps();
@@ -84,20 +84,20 @@ public:
}
/**
- * Activating an instance of ThreadOps will map it onto the currently
+ * Activating an instance of ThreadOps will map it onto the currently
* executing thread.
- */
+ */
static void activate(ThreadOps* ops) {
assert(ops);
assert(ops->_tid == 0);
ops->_tid = MPCurrentTaskID();
-
+
}
/**
- * Test if this object represents the currently executing
+ * Test if this object represents the currently executing
* native thread.
*
* @return bool true if successful
@@ -119,7 +119,7 @@ public:
static bool join(ThreadOps*);
/**
- * Force the current native thread to yield, letting the scheduler
+ * Force the current native thread to yield, letting the scheduler
* give the CPU time to another thread.
*
* @return bool true if successful, false if the operation can't
@@ -128,7 +128,7 @@ public:
static bool yield();
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param PRIORITY requested priority
@@ -137,7 +137,7 @@ public:
static bool setPriority(ThreadOps*, Priority);
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param Thread::PRIORITY& current priority
diff --git a/dep/src/zthread/macos/UpTimeStrategy.h b/dep/src/zthread/macos/UpTimeStrategy.h
index f2056e14ca2..0f7962d7eca 100644
--- a/dep/src/zthread/macos/UpTimeStrategy.h
+++ b/dep/src/zthread/macos/UpTimeStrategy.h
@@ -40,7 +40,7 @@ class TimeStrategy {
unsigned long _s;
public:
-
+
TimeStrategy() {
// Get the absolute time in milliseconds relative to the program startup
@@ -53,12 +53,12 @@ class TimeStrategy {
_ms = now % 1000;
}
-
+
inline unsigned long seconds() const {
return _s;
}
- inline unsigned long milliseconds() const {
+ inline unsigned long milliseconds() const {
return _ms;
}
diff --git a/dep/src/zthread/posix/ConditionRecursiveLock.h b/dep/src/zthread/posix/ConditionRecursiveLock.h
index a46ed35548c..2be55c13797 100644
--- a/dep/src/zthread/posix/ConditionRecursiveLock.h
+++ b/dep/src/zthread/posix/ConditionRecursiveLock.h
@@ -38,13 +38,13 @@ namespace ZThread {
* @version 2.2.0
*
* This is an implementation of a FastRecursiveLock for any vannila
- * POSIX system. It is based on a condition variable and a mutex;
+ * POSIX system. It is based on a condition variable and a mutex;
* because of this it is important to not that its waiting properties
* are not the same as other mutex implementations that generally
* based on spin locks. Under high contention, this implementation may
* be preferable to a spin lock, although refactoring the design of
* code that puts a mutex under alot of preasure may be worth investigating.
- */
+ */
class FastRecursiveLock : private NonCopyable {
//! Serialize state
@@ -62,25 +62,25 @@ class FastRecursiveLock : private NonCopyable {
public:
inline FastRecursiveLock() : _owner(0), _count(0) {
-
+
pthread_mutex_init(&_mtx, 0);
if(pthread_cond_init(&_cond, 0) != 0) {
assert(0);
}
}
-
+
inline ~FastRecursiveLock() {
pthread_mutex_destroy(&_mtx);
if(pthread_cond_destroy(&_cond) != 0) {
- assert(0);
+ assert(0);
}
-
+
}
-
+
inline void acquire() {
-
+
pthread_t self = pthread_self();
pthread_mutex_lock(&_mtx);
@@ -91,14 +91,14 @@ public:
do { // ignore signals
status = pthread_cond_wait(&_cond, &_mtx);
} while(status == EINTR && _owner == 0);
-
+
}
-
+
_owner = self;
_count++;
pthread_mutex_unlock(&_mtx);
-
+
}
inline bool tryAcquire(unsigned long timeout=0) {
@@ -109,10 +109,10 @@ public:
// If the caller owns the lock, or there is no owner update the count
bool success = (_owner == 0 || pthread_equal(_owner, self));
if(success) {
-
+
_owner = self;
_count++;
-
+
}
pthread_mutex_unlock(&_mtx);
@@ -122,7 +122,7 @@ public:
}
inline void release() {
-
+
assert(pthread_equal(_owner, pthread_self()));
pthread_mutex_lock(&_mtx);
@@ -134,13 +134,13 @@ public:
}
pthread_mutex_unlock(&_mtx);
-
+
}
-
-
+
+
}; /* FastRecursiveLock */
-} // namespace ZThread
+} // namespace ZThread
#endif
diff --git a/dep/src/zthread/posix/FastLock.h b/dep/src/zthread/posix/FastLock.h
index 87faf34d4ff..261fd7c893a 100644
--- a/dep/src/zthread/posix/FastLock.h
+++ b/dep/src/zthread/posix/FastLock.h
@@ -39,16 +39,16 @@ namespace ZThread {
*
* This is the smallest and fastest synchronization object in the library.
* It is an implementation of fast mutex, an all or nothing exclusive
- * lock. It should be used only where you need speed and are willing
+ * lock. It should be used only where you need speed and are willing
* to sacrifice all the state & safety checking provided by the framework
* for speed.
- */
+ */
class FastLock : private NonCopyable {
-
+
pthread_mutex_t _mtx;
public:
-
+
/**
* Create a new FastLock. No safety or state checks are performed.
*
@@ -60,7 +60,7 @@ class FastLock : private NonCopyable {
throw Initialization_Exception();
}
-
+
/**
* Destroy a FastLock. No safety or state checks are performed.
*/
@@ -71,14 +71,14 @@ class FastLock : private NonCopyable {
}
}
-
+
/**
* Acquire an exclusive lock. No safety or state checks are performed.
*
* @exception Synchronization_Exception - not thrown
*/
inline void acquire() {
-
+
if(pthread_mutex_lock(&_mtx) != 0)
throw Synchronization_Exception();
@@ -97,22 +97,22 @@ class FastLock : private NonCopyable {
return (pthread_mutex_trylock(&_mtx) == 0);
}
-
+
/**
* Release an exclusive lock. No safety or state checks are performed.
- * The caller should have already acquired the lock, and release it
+ * The caller should have already acquired the lock, and release it
* only once.
- *
+ *
* @exception Synchronization_Exception - not thrown
*/
inline void release() {
-
+
if(pthread_mutex_unlock(&_mtx) != 0)
throw Synchronization_Exception();
}
-
-
+
+
}; /* FastLock */
diff --git a/dep/src/zthread/posix/FtimeStrategy.h b/dep/src/zthread/posix/FtimeStrategy.h
index 5e703970c5c..5e8d33b6c9b 100644
--- a/dep/src/zthread/posix/FtimeStrategy.h
+++ b/dep/src/zthread/posix/FtimeStrategy.h
@@ -55,8 +55,8 @@ public:
return (unsigned long)_value.time;
}
- inline unsigned long milliseconds() const {
- return _value.millitm;
+ inline unsigned long milliseconds() const {
+ return _value.millitm;
}
unsigned long seconds(unsigned long s) {
diff --git a/dep/src/zthread/posix/Monitor.h b/dep/src/zthread/posix/Monitor.h
index 945c879f421..fe6c8b559e3 100644
--- a/dep/src/zthread/posix/Monitor.h
+++ b/dep/src/zthread/posix/Monitor.h
@@ -50,7 +50,7 @@ class Monitor : public Status, private NonCopyable {
pthread_t _owner;
//! Waiting flag, to avoid uneccessary signals
- volatile bool _waiting;
+ volatile bool _waiting;
public:
@@ -62,12 +62,12 @@ class Monitor : public Status, private NonCopyable {
//! Destroy the monitor.
~Monitor();
- //! Acquire the lock for this monitor.
+ //! Acquire the lock for this monitor.
inline void acquire() {
_lock.acquire();
}
- //! Acquire the lock for this monitor.
+ //! Acquire the lock for this monitor.
inline bool tryAcquire() {
return _lock.tryAcquire();
}
@@ -79,7 +79,7 @@ class Monitor : public Status, private NonCopyable {
/**
* Wait for a state change and atomically unlock the external lock.
- * Blocks for an indefinent amount of time.
+ * Blocks for an indefinent amount of time.
*
* @return INTERRUPTED if the wait was ended by a interrupt()
* or SIGNALED if the wait was ended by a notify()
@@ -92,11 +92,11 @@ class Monitor : public Status, private NonCopyable {
/**
* Wait for a state change and atomically unlock the external lock.
- * May blocks for an indefinent amount of time.
+ * May blocks for an indefinent amount of time.
*
* @param timeout - maximum time to block (milliseconds) or 0 to
* block indefinently
- *
+ *
* @return INTERRUPTED if the wait was ended by a interrupt()
* or TIMEDOUT if the maximum wait time expired.
* or SIGNALED if the wait was ended by a notify()
@@ -116,9 +116,9 @@ class Monitor : public Status, private NonCopyable {
/**
* Notify this monitor. If there is a thread blocked on this monitor object
- * it will be signaled and released. If there is no waiter, a flag is set and
- * the next attempt to wait() will return SIGNALED w/o blocking, if no other
- * flag is set.
+ * it will be signaled and released. If there is no waiter, a flag is set and
+ * the next attempt to wait() will return SIGNALED w/o blocking, if no other
+ * flag is set.
*
* @return false if the thread was previously INTERRUPTED.
*/
diff --git a/dep/src/zthread/posix/PriorityOps.h b/dep/src/zthread/posix/PriorityOps.h
index 92da66a9cff..3a7f822711d 100644
--- a/dep/src/zthread/posix/PriorityOps.h
+++ b/dep/src/zthread/posix/PriorityOps.h
@@ -34,15 +34,15 @@ namespace ZThread {
* @date <2003-07-16T23:30:00-0400>
* @version 2.2.0
*
- * This class is an abstraction used to perform various operations on a
+ * This class is an abstraction used to perform various operations on a
* native POSIX thread.
*/
class PriorityOps {
-
+
public:
-
+
};
diff --git a/dep/src/zthread/posix/TSS.h b/dep/src/zthread/posix/TSS.h
index 931ff348b3d..c9c9c0e352a 100644
--- a/dep/src/zthread/posix/TSS.h
+++ b/dep/src/zthread/posix/TSS.h
@@ -35,18 +35,18 @@ namespace ZThread {
* @date <2003-07-27T14:18:37-0400>
* @version 2.3.0
*
- * An abstraction for dealing with POSIX thread specific storage (tss).
+ * An abstraction for dealing with POSIX thread specific storage (tss).
* Provides get/set and creation/destruction.
*/
template <typename T>
class TSS : private NonCopyable {
-
+
pthread_key_t _key;
public:
/**
- * Create a new object for accessing tss.
+ * Create a new object for accessing tss.
*/
TSS() {
@@ -57,15 +57,15 @@ namespace ZThread {
}
/**
- * Destroy the underlying supoprt for accessing tss with this
+ * Destroy the underlying supoprt for accessing tss with this
* object.
*/
~TSS() {
-
+
pthread_key_delete(_key);
-
+
}
-
+
/**
* Get the value stored in tss.
*
@@ -76,8 +76,8 @@ namespace ZThread {
T get() const {
return reinterpret_cast<T>(pthread_getspecific(_key));
}
-
-
+
+
/**
* Store a value in tss.
*
@@ -90,11 +90,11 @@ namespace ZThread {
T oldValue = get();
pthread_setspecific(_key, value);
-
+
return oldValue;
-
+
}
-
+
};
}
diff --git a/dep/src/zthread/posix/ThreadOps.h b/dep/src/zthread/posix/ThreadOps.h
index be754c2d659..8fef43bb3fd 100644
--- a/dep/src/zthread/posix/ThreadOps.h
+++ b/dep/src/zthread/posix/ThreadOps.h
@@ -31,7 +31,7 @@
namespace ZThread {
class Runnable;
-
+
//! Dispatch function for native pthreads required extern C
//! linkage.
extern "C" void* _dispatch(void*);
@@ -42,7 +42,7 @@ extern "C" void* _dispatch(void*);
* @date <2003-07-16T23:30:25-0400>
* @version 2.2.8
*
- * This class is an abstraction used to perform various operations on a
+ * This class is an abstraction used to perform various operations on a
* native POSIX thread.
*/
class ThreadOps {
@@ -54,10 +54,10 @@ class ThreadOps {
public:
- const static ThreadOps INVALID;
+ const static ThreadOps INVALID;
/**
- * Create a new ThreadOps to manipulate a native thread.
+ * Create a new ThreadOps to manipulate a native thread.
*/
ThreadOps() : _tid(0) { }
@@ -66,26 +66,26 @@ public:
return pthread_equal(_tid, ops._tid);
}
-
+
static ThreadOps self() {
return ThreadOps(pthread_self());
}
/**
- * Activating an instance of ThreadOps will map it onto the currently
+ * Activating an instance of ThreadOps will map it onto the currently
* executing thread.
- */
+ */
static void activate(ThreadOps* ops) {
assert(ops);
assert(ops->_tid == 0);
ops->_tid = pthread_self();
-
+
}
/**
- * Test if this object represents the currently executing
+ * Test if this object represents the currently executing
* native thread.
*
* @return bool true if successful
@@ -107,7 +107,7 @@ public:
static bool join(ThreadOps*);
/**
- * Force the current native thread to yield, letting the scheduler
+ * Force the current native thread to yield, letting the scheduler
* give the CPU time to another thread.
*
* @return bool true if successful, false if the operation can't
@@ -116,7 +116,7 @@ public:
static bool yield();
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param PRIORITY requested priority
@@ -125,7 +125,7 @@ public:
static bool setPriority(ThreadOps*, Priority);
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param Thread::PRIORITY& current priority
diff --git a/dep/src/zthread/solaris/FastRecursiveLock.h b/dep/src/zthread/solaris/FastRecursiveLock.h
index 956e1dbd3ad..2de0f8cd022 100644
--- a/dep/src/zthread/solaris/FastRecursiveLock.h
+++ b/dep/src/zthread/solaris/FastRecursiveLock.h
@@ -35,13 +35,13 @@ namespace ZThread {
* @date <2003-07-16T23:31:23-0400>
* @version 2.2.0
*
- * This FastRecursiveLock implementation uses pthreads mutex attribute
- * functions to create a recursive lock. This implementation is not
- * specific to solaris and will work on any system that supports
- * pthread_mutexattr_settype().
- */
+ * This FastRecursiveLock implementation uses pthreads mutex attribute
+ * functions to create a recursive lock. This implementation is not
+ * specific to solaris and will work on any system that supports
+ * pthread_mutexattr_settype().
+ */
class FastRecursiveLock : private NonCopyable {
-
+
pthread_mutex_t _mtx;
/**
@@ -50,7 +50,7 @@ class FastRecursiveLock : private NonCopyable {
* Utility class to maintain the attribute as long as it is needed.
*/
class Attribute {
-
+
pthread_mutexattr_t _attr;
public:
@@ -60,13 +60,13 @@ class FastRecursiveLock : private NonCopyable {
if(pthread_mutexattr_init(&_attr) != 0) {
assert(0);
}
-
+
if(pthread_mutexattr_settype(&_attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
assert(0);
}
}
-
+
~Attribute() {
if(pthread_mutexattr_destroy(&_attr) != 0) {
@@ -84,36 +84,36 @@ class FastRecursiveLock : private NonCopyable {
public:
inline FastRecursiveLock() {
-
+
static Attribute attr;
pthread_mutex_init(&_mtx, (pthread_mutexattr_t*)attr);
}
-
+
inline ~FastRecursiveLock() {
pthread_mutex_destroy(&_mtx);
}
-
+
inline void acquire() {
-
+
pthread_mutex_lock(&_mtx);
}
inline void release() {
-
+
pthread_mutex_unlock(&_mtx);
-
+
}
-
+
inline bool tryAcquire(unsigned long timeout=0) {
return (pthread_mutex_trylock(&_mtx) == 0);
}
-
+
}; /* FastRecursiveLock */
diff --git a/dep/src/zthread/vanilla/DualMutexRecursiveLock.h b/dep/src/zthread/vanilla/DualMutexRecursiveLock.h
index ddce7a3cd27..63214133c02 100644
--- a/dep/src/zthread/vanilla/DualMutexRecursiveLock.h
+++ b/dep/src/zthread/vanilla/DualMutexRecursiveLock.h
@@ -38,11 +38,11 @@ namespace ZThread {
*
* This is a vanilla FastRecursiveLock implementation for a
* system that doesn't provide recurisve locks. This implementation
- * is based on using a pair of mutexes, because of this, it performs
+ * is based on using a pair of mutexes, because of this, it performs
* roughly the same as a spin lock would.
- */
+ */
class FastRecursiveLock : private NonCopyable {
-
+
//! Lock for blocking
FastLock _blockingLock;
@@ -58,14 +58,14 @@ class FastRecursiveLock : private NonCopyable {
public:
inline FastRecursiveLock() : _owner(ThreadOps::INVALID), _count(0) { }
-
+
inline ~FastRecursiveLock() {
assert(_owner == ThreadOps::INVALID);
assert(_count == 0);
}
-
+
void acquire() {
ThreadOps self(ThreadOps::self());
@@ -73,7 +73,7 @@ class FastRecursiveLock : private NonCopyable {
// Try to lock the blocking mutex first
bool wasLocked = _blockingLock.tryAcquire();
if(!wasLocked) {
-
+
// Otherwise, grab the lock for the state
_stateLock.acquire();
@@ -82,30 +82,30 @@ class FastRecursiveLock : private NonCopyable {
_count++;
_stateLock.release();
-
+
if(wasLocked)
return;
// Try to be cooperative
ThreadOps::yield();
_blockingLock.acquire();
-
+
}
- // Serialze access to the state
+ // Serialze access to the state
_stateLock.acquire();
-
- // Take ownership
+
+ // Take ownership
assert(_owner == ThreadOps::INVALID || _owner == self);
_owner = self;
_count++;
-
+
_stateLock.release();
}
-
-
+
+
bool tryAcquire(unsigned long timeout = 0) {
ThreadOps self(ThreadOps::self());
@@ -113,7 +113,7 @@ class FastRecursiveLock : private NonCopyable {
// Try to lock the blocking mutex first
bool wasLocked = _blockingLock.tryAcquire();
if(!wasLocked) {
-
+
// Otherwise, grab the lock for the state
_stateLock.acquire();
@@ -122,52 +122,52 @@ class FastRecursiveLock : private NonCopyable {
_count++;
_stateLock.release();
-
+
return wasLocked;
-
+
}
- // Serialze access to the state
+ // Serialze access to the state
_stateLock.acquire();
-
- // Take ownership
+
+ // Take ownership
assert(_owner == ThreadOps::INVALID || _owner == self);
_owner = self;
_count++;
-
+
_stateLock.release();
-
+
return true;
}
-
+
void release() {
- // Assume that release is only used by the owning thread, as it
+ // Assume that release is only used by the owning thread, as it
// should be.
assert(_count != 0);
assert(_owner == ThreadOps::self());
-
+
_stateLock.acquire();
-
+
// If the lock was owned and the count has reached 0, give up
// ownership and release the blocking lock
if(--_count == 0) {
-
+
_owner = ThreadOps::INVALID;
_blockingLock.release();
-
+
}
-
+
_stateLock.release();
}
-
+
}; /* FastRecursiveLock */
-} // namespace ZThread
+} // namespace ZThread
#endif
diff --git a/dep/src/zthread/vanilla/SimpleRecursiveLock.h b/dep/src/zthread/vanilla/SimpleRecursiveLock.h
index f4f309218b6..6adf4154fc4 100644
--- a/dep/src/zthread/vanilla/SimpleRecursiveLock.h
+++ b/dep/src/zthread/vanilla/SimpleRecursiveLock.h
@@ -37,49 +37,49 @@ namespace ZThread {
* @version 2.2.8
*
* This implementation of a FastRecursiveLock uses the which ever FastLock
- * that is selected to create a recursive spin lock.
- */
+ * that is selected to create a recursive spin lock.
+ */
class FastRecursiveLock : private NonCopyable {
-
+
FastLock _lock;
ThreadOps _owner;
volatile unsigned int _count;
-
+
public:
-
+
inline FastRecursiveLock() : _owner(ThreadOps::INVALID), _count(0) {}
-
+
inline ~FastRecursiveLock() {
assert(_owner == ThreadOps::INVALID);
assert(_count == 0);
}
-
+
inline void acquire() {
ThreadOps self(ThreadOps::self());
bool wasLocked = false;
do {
-
+
_lock.acquire();
-
+
// If there is no owner, or the owner is the caller
// update the count
if(_owner == ThreadOps::INVALID || _owner == self) {
_owner = self;
_count++;
-
+
wasLocked = true;
-
+
}
_lock.release();
-
+
} while(!wasLocked);
assert(_owner == ThreadOps::self());
@@ -96,32 +96,32 @@ public:
_owner = ThreadOps::INVALID;
_lock.release();
-
+
}
-
+
inline bool tryAcquire(unsigned long timeout=0) {
ThreadOps self(ThreadOps::self());
bool wasLocked = false;
_lock.acquire();
-
+
if(_owner == ThreadOps::INVALID || _owner == self) {
-
+
_owner = self;
_count++;
-
+
wasLocked = true;
}
-
+
_lock.release();
assert(!wasLocked || _owner == ThreadOps::self());
- return wasLocked;
-
+ return wasLocked;
+
}
-
+
}; /* FastRecursiveLock */
diff --git a/dep/src/zthread/win32/AtomicFastLock.h b/dep/src/zthread/win32/AtomicFastLock.h
index a714c03789f..8d09f132a35 100644
--- a/dep/src/zthread/win32/AtomicFastLock.h
+++ b/dep/src/zthread/win32/AtomicFastLock.h
@@ -39,17 +39,17 @@ namespace ZThread {
*
* This is the smallest and fastest synchronization object in the library.
* It is an implementation of fast mutex, an all or nothing exclusive
- * lock. It should be used only where you need speed and are willing
+ * lock. It should be used only where you need speed and are willing
* to sacrifice all the state & safety checking provided by the framework
* for speed.
*
* The current Platform SDK defines:
*
* LONG InterlockedExchange(LPLONG, LONG)
- * LONG InterlockedCompareExchange(LPLONG, LONG, LONG, LONG)
+ * LONG InterlockedCompareExchange(LPLONG, LONG, LONG, LONG)
*
* If your compiler complains about LPLONG not being implicitly casted to
- * a PVOID, then you should get the SDK update from microsoft or use the
+ * a PVOID, then you should get the SDK update from microsoft or use the
* WIN9X implementation of this class.
*
* ----
@@ -57,21 +57,21 @@ namespace ZThread {
* don't all support the CMPXCHG function, and so Windows 95 an earlier dont support
* InterlockedCompareExchange. For this, you should use the win9x implementation
* of this class
- */
+ */
class FastLock : private NonCopyable {
#pragma pack(push, 8)
LONG volatile _lock;
#pragma pack(pop)
-
+
public:
-
+
/**
* Create a new FastLock
*/
inline FastLock() : _lock(0) { }
-
+
/**
* Destroy FastLock
*/
@@ -79,9 +79,9 @@ class FastLock : private NonCopyable {
/**
* Lock the fast Lock, no error check.
- *
+ *
* @exception None
- */
+ */
inline void acquire() {
while (::InterlockedCompareExchange(const_cast<LPLONG>(&_lock), 1, 0) != 0)
@@ -89,18 +89,18 @@ class FastLock : private NonCopyable {
}
-
+
/**
* Release the fast Lock, no error check.
- *
+ *
* @exception None
- */
+ */
inline void release() {
::InterlockedExchange(const_cast<LPLONG>(&_lock), (LONG)0);
}
-
+
/**
* Try to acquire an exclusive lock. No safety or state checks are performed.
* This function returns immediately regardless of the value of the timeout
@@ -110,11 +110,11 @@ class FastLock : private NonCopyable {
* @exception Synchronization_Exception - not thrown
*/
inline bool tryAcquire(unsigned long timeout=0) {
-
+
return ::InterlockedCompareExchange(const_cast<LPLONG>(&_lock), 1, 0) == 0;
}
-
+
}; /* FastLock */
diff --git a/dep/src/zthread/win32/AtomicFastRecursiveLock.h b/dep/src/zthread/win32/AtomicFastRecursiveLock.h
index c6a61b03b5d..a4dc3755265 100644
--- a/dep/src/zthread/win32/AtomicFastRecursiveLock.h
+++ b/dep/src/zthread/win32/AtomicFastRecursiveLock.h
@@ -37,36 +37,36 @@ namespace ZThread {
* @date <2003-07-16T23:32:34-0400>
* @version 2.1.6
*
- * This is the smaller and faster implementation of a RecursiveLock.
+ * This is the smaller and faster implementation of a RecursiveLock.
* A single thread can acquire the mutex any number of times, but it
* must perform a release for each acquire(). Other threads are blocked
* until a thread has released all of its locks on the mutex.
- *
- * This particular implementation performs fewer safety checks. Like
- * the FastLock implementation, any waiting caused by an acquire() request
+ *
+ * This particular implementation performs fewer safety checks. Like
+ * the FastLock implementation, any waiting caused by an acquire() request
* is not interruptable. This is so that the mutex can have the fastest
* response time for a time critical application while still having a good
* degree of reliability.
*
- * TryEnterCriticalSection() does not work at all on some systems, so its
+ * TryEnterCriticalSection() does not work at all on some systems, so its
* not used.
*
*
* The current Platform SDK defines:
*
* LONG InterlockedExchange(LPLONG, LONG)
- * LONG InterlockedCompareExchange(LPLONG, LONG, LONG, LONG)
+ * LONG InterlockedCompareExchange(LPLONG, LONG, LONG, LONG)
*
* If your compiler complains about LPLONG not being implicitly casted to
- * a PVOID, then you should get the SDK update from microsoft or use the
+ * a PVOID, then you should get the SDK update from microsoft or use the
* WIN9X implementation of this class.
*
* ----
* Because Windows 95 and earlier can run on processors prior to the 486, they
* don't all support the CMPXCHG function, and so Windows 95 an earlier dont support
- * InterlockedCompareExchange. If you define ZT_WIN9X, you'll get a version of the
+ * InterlockedCompareExchange. If you define ZT_WIN9X, you'll get a version of the
* FastLock that uses the XCHG instruction
- */
+ */
class FastRecursiveLock : private NonCopyable {
// Add def for mingw32 or other non-ms compiler to align on 64-bit
@@ -75,15 +75,15 @@ class FastRecursiveLock : private NonCopyable {
LONG volatile _lock;
#pragma pack(pop)
LONG _count;
-
+
public:
-
+
/**
* Create a new FastRecursiveLock
*/
inline FastRecursiveLock() : _lock(0), _count(0) { }
-
+
/**
* Destroy FastLock
*/
@@ -93,9 +93,9 @@ class FastRecursiveLock : private NonCopyable {
/**
* Lock the fast Lock, no error check.
- *
+ *
* @exception None
- */
+ */
inline void acquire() {
DWORD id = ::GetCurrentThreadId();
@@ -110,24 +110,24 @@ class FastRecursiveLock : private NonCopyable {
::Sleep(0);
} while(1);
-
+
_count++;
}
-
+
/**
* Release the fast Lock, no error check.
- *
+ *
* @exception None
- */
+ */
inline void release() {
if(--_count == 0)
::InterlockedExchange(const_cast<LPLONG>(&_lock), 0);
}
-
+
/**
* Try to acquire an exclusive lock. No safety or state checks are performed.
* This function returns immediately regardless of the value of the timeout
@@ -137,20 +137,20 @@ class FastRecursiveLock : private NonCopyable {
* @exception Synchronization_Exception - not thrown
*/
inline bool tryAcquire(unsigned long timeout=0) {
-
+
DWORD id = ::GetCurrentThreadId();
DWORD owner = (DWORD)::InterlockedCompareExchange(const_cast<LPLONG>(&_lock), id, 0);
-
+
if(owner == 0 || owner == id) {
_count++;
return true;
}
-
+
return false;
-
+
}
-
-
+
+
}; /* FastRecursiveLock */
diff --git a/dep/src/zthread/win32/FastLock.h b/dep/src/zthread/win32/FastLock.h
index 2e9fe829af6..3b212e1d891 100644
--- a/dep/src/zthread/win32/FastLock.h
+++ b/dep/src/zthread/win32/FastLock.h
@@ -39,10 +39,10 @@ namespace ZThread {
* @version 2.2.11
*
* This FastLock implementation is based on a Win32 Mutex
- * object. This will perform better under high contention,
+ * object. This will perform better under high contention,
* but will not be as fast as the spin lock under reasonable
* circumstances.
- */
+ */
class FastLock : private NonCopyable {
HANDLE _hMutex;
@@ -51,11 +51,11 @@ namespace ZThread {
#endif
public:
-
+
/**
* Create a new FastLock
*/
- FastLock() {
+ FastLock() {
#ifndef NDEBUG
_locked = false;
@@ -68,11 +68,11 @@ namespace ZThread {
}
-
+
~FastLock() {
::CloseHandle(_hMutex);
}
-
+
void acquire() {
if(::WaitForSingleObject(_hMutex, INFINITE) != WAIT_OBJECT_0) {
@@ -113,7 +113,7 @@ namespace ZThread {
switch(::WaitForSingleObject(_hMutex, timeout)) {
case WAIT_OBJECT_0:
-
+
#ifndef NDEBUG
// Simulate deadlock to provide consistent behavior. This
@@ -122,7 +122,7 @@ namespace ZThread {
while(_locked)
ThreadOps::yield();
-
+
_locked = true;
#endif
diff --git a/dep/src/zthread/win32/FastRecursiveLock.h b/dep/src/zthread/win32/FastRecursiveLock.h
index e1a6e7cd692..de556ac4aa8 100644
--- a/dep/src/zthread/win32/FastRecursiveLock.h
+++ b/dep/src/zthread/win32/FastRecursiveLock.h
@@ -39,21 +39,21 @@ namespace ZThread {
* @version 2.2.11
*
* This FastRecursiveLock implementation is based on a Win32 Mutex
- * object. This will perform better under high contention,
+ * object. This will perform better under high contention,
* but will not be as fast as the spin lock under reasonable
* circumstances.
- */
+ */
class FastRecursiveLock : private NonCopyable {
HANDLE _hMutex;
volatile unsigned int _count;
public:
-
+
/**
* Create a new FastRecursiveLock
*/
- FastRecursiveLock() : _count(0) {
+ FastRecursiveLock() : _count(0) {
_hMutex = ::CreateMutex(0, 0, 0);
assert(_hMutex != NULL);
@@ -62,12 +62,12 @@ class FastRecursiveLock : private NonCopyable {
}
-
+
~FastRecursiveLock() {
::CloseHandle(_hMutex);
}
-
+
void acquire() {
if(::WaitForSingleObject(_hMutex, INFINITE) != WAIT_OBJECT_0) {
diff --git a/dep/src/zthread/win32/Monitor.h b/dep/src/zthread/win32/Monitor.h
index 7073343b7f8..a527b8afff6 100644
--- a/dep/src/zthread/win32/Monitor.h
+++ b/dep/src/zthread/win32/Monitor.h
@@ -49,37 +49,37 @@ class Monitor : public Status, private NonCopyable {
DWORD _owner;
//! Waiting flag, to avoid uneccessary signals
- volatile bool _waiting;
+ volatile bool _waiting;
//! State of the monitor
volatile int _state;
public:
-
+
//! Create a new monitor.
Monitor();
//! Destroy the monitor.
~Monitor();
- //! Acquire the external lock for this monitor.
+ //! Acquire the external lock for this monitor.
inline void acquire() {
_lock.acquire();
}
- //! Try to acquire the external lock for this monitor.
+ //! Try to acquire the external lock for this monitor.
inline bool tryAcquire() {
return _lock.tryAcquire();
}
- //! Release the external lock for this monitor.
+ //! Release the external lock for this monitor.
inline void release() {
_lock.release();
}
-
+
/**
* Wait for a state change and atomically unlock the external lock.
- * Blocks for an indefinent amount of time.
+ * Blocks for an indefinent amount of time.
*
* @return INTERRUPTED if the wait was ended by a interrupt()
* or SIGNALED if the wait was ended by a notify()
@@ -92,11 +92,11 @@ class Monitor : public Status, private NonCopyable {
/**
* Wait for a state change and atomically unlock the external lock.
- * May blocks for an indefinent amount of time.
+ * May blocks for an indefinent amount of time.
*
* @param timeout - maximum time to block (milliseconds) or 0 to
* block indefinently
- *
+ *
* @return INTERRUPTED if the wait was ended by a interrupt()
* or TIMEDOUT if the maximum wait time expired.
* or SIGNALED if the wait was ended by a notify()
@@ -116,9 +116,9 @@ class Monitor : public Status, private NonCopyable {
/**
* Notify this monitor. If there is a thread blocked on this monitor object
- * it will be signaled and released. If there is no waiter, a flag is set and
- * the next attempt to wait() will return SIGNALED w/o blocking, if no other
- * flag is set.
+ * it will be signaled and released. If there is no waiter, a flag is set and
+ * the next attempt to wait() will return SIGNALED w/o blocking, if no other
+ * flag is set.
*
* @return false if the thread was previously INTERRUPTED.
*/
diff --git a/dep/src/zthread/win32/PerformanceCounterStrategy.h b/dep/src/zthread/win32/PerformanceCounterStrategy.h
index 95b526830b3..4c657af0c8a 100644
--- a/dep/src/zthread/win32/PerformanceCounterStrategy.h
+++ b/dep/src/zthread/win32/PerformanceCounterStrategy.h
@@ -31,19 +31,19 @@ namespace ZThread {
/**
* @class PerformanceCounterStrategy
*
- * Implement a strategy for time operatons based on
- * Windows QueryPerformanceXXX() functions.
+ * Implement a strategy for time operatons based on
+ * Windows QueryPerformanceXXX() functions.
* This only (erroneously) considers the lower 32 bits.
*/
class TimeStrategy {
unsigned long _secs;
unsigned long _millis;
-
+
public:
TimeStrategy() {
-
+
// Keep track of the relative time the program started
static LARGE_INTEGER i;
static BOOL valid(::QueryPerformanceCounter(&i));
@@ -52,22 +52,22 @@ public:
LARGE_INTEGER j;
::QueryPerformanceCounter(&j);
-
+
j.LowPart -= i.LowPart;
j.LowPart /= frequency();
- // Mask off the high bits
+ // Mask off the high bits
_millis = (unsigned long)j.LowPart / 1000;
_secs = (unsigned long)j.LowPart - _millis;
}
-
+
unsigned long seconds() const {
return _secs;
}
- unsigned long milliseconds() const {
- return _millis;
+ unsigned long milliseconds() const {
+ return _millis;
}
unsigned long seconds(unsigned long s) {
diff --git a/dep/src/zthread/win32/TSS.h b/dep/src/zthread/win32/TSS.h
index 2400830f06a..d1307a51e2a 100644
--- a/dep/src/zthread/win32/TSS.h
+++ b/dep/src/zthread/win32/TSS.h
@@ -33,12 +33,12 @@ namespace ZThread {
* @date <2003-07-27T14:18:43-0400>
* @version 2.3.0
*
- * An abstraction for dealing with WIN32 thread specific storage (tss).
+ * An abstraction for dealing with WIN32 thread specific storage (tss).
* Provides get/set and creation/destruction.
*/
template <typename T>
class TSS {
-
+
DWORD _key;
bool _valid;
@@ -55,16 +55,16 @@ namespace ZThread {
}
/**
- * Destroy the underlying supoprt for accessing tss with this
+ * Destroy the underlying supoprt for accessing tss with this
* object.
*/
virtual ~TSS() {
-
- if(_valid)
+
+ if(_valid)
::TlsFree(_key);
-
+
}
-
+
/**
* Get the value stored in tss.
*
@@ -97,8 +97,8 @@ namespace ZThread {
return oldValue;
}
-
-
+
+
};
}
diff --git a/dep/src/zthread/win32/ThreadOps.h b/dep/src/zthread/win32/ThreadOps.h
index 4a3eeac2ed9..1b3a0bfa174 100644
--- a/dep/src/zthread/win32/ThreadOps.h
+++ b/dep/src/zthread/win32/ThreadOps.h
@@ -37,7 +37,7 @@ class Runnable;
* @date <2003-07-16T23:33:59-0400>
* @version 2.2.8
*
- * This class is an abstraction used to perform various operations on a
+ * This class is an abstraction used to perform various operations on a
* native WIN32 thread.
*/
class ThreadOps {
@@ -53,11 +53,11 @@ class ThreadOps {
public:
- const static ThreadOps INVALID;
+ const static ThreadOps INVALID;
/**
- * Create a new ThreadOps to represent a native thread.
- */
+ * Create a new ThreadOps to represent a native thread.
+ */
ThreadOps() : _tid(0), _hThread(NULL) {}
@@ -65,7 +65,7 @@ class ThreadOps {
return _tid == ops._tid;
}
-
+
static ThreadOps self() {
return ThreadOps(::GetCurrentThreadId());
}
@@ -73,7 +73,7 @@ class ThreadOps {
/**
* Update the native tid for this thread so it matches the current
* thread.
- */
+ */
static void activate(ThreadOps* ops) {
assert(ops);
@@ -84,7 +84,7 @@ class ThreadOps {
}
/**
- * Test if this object representative of the currently executing
+ * Test if this object representative of the currently executing
* native thread.
*
* @return bool true if successful
@@ -105,7 +105,7 @@ class ThreadOps {
static bool join(ThreadOps*);
/**
- * Force the current native thread to yield, letting the scheduler
+ * Force the current native thread to yield, letting the scheduler
* give the CPU time to another thread.
*
* @return bool true if successful
@@ -113,7 +113,7 @@ class ThreadOps {
static bool yield();
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param PRIORITY requested priority
@@ -122,7 +122,7 @@ class ThreadOps {
static bool setPriority(ThreadOps*, Priority);
/**
- * Set the priority for the native thread if supported by the
+ * Set the priority for the native thread if supported by the
* system.
*
* @param Thread::PRIORITY& current priority
diff --git a/dep/src/zthread/win9x/AtomicFastLock.h b/dep/src/zthread/win9x/AtomicFastLock.h
index 5b50a9c7337..7723b7077d8 100644
--- a/dep/src/zthread/win9x/AtomicFastLock.h
+++ b/dep/src/zthread/win9x/AtomicFastLock.h
@@ -48,22 +48,22 @@ namespace ZThread {
* This is asm inlined for microsoft visual c, it needs to be changed in order to
* compile with gcc, or another win32 compiler - but more likely than not you'll
* be using the Win32 version on those compilers and this won't be a problem.
- */
+ */
class FastLock : private NonCopyable {
// Add def for mingw32 or other non-ms compiler to align on 32-bit boundary
#pragma pack(push, 4)
unsigned char volatile _lock;
#pragma pack(pop)
-
+
public:
-
+
/**
* Create a new FastLock
*/
inline FastLock() : _lock(0) { }
-
+
inline ~FastLock() {
assert(_lock == 0);
}
@@ -77,7 +77,7 @@ class FastLock : private NonCopyable {
mov al, 1
mov esi, dw
- xchg [esi], al
+ xchg [esi], al
and al,al
jz spin_locked
}
@@ -95,15 +95,15 @@ class FastLock : private NonCopyable {
DWORD dw = (DWORD)&_lock;
- _asm {
+ _asm {
mov al, 0
mov esi, dw
- xchg [esi], al
+ xchg [esi], al
}
}
-
+
inline bool tryAcquire(unsigned long timeout=0) {
volatile DWORD dw = (DWORD)&_lock;
@@ -113,16 +113,16 @@ class FastLock : private NonCopyable {
mov al, 1
mov esi, dw
- xchg [esi], al
+ xchg [esi], al
and al,al
mov esi, result
- xchg [esi], al
+ xchg [esi], al
}
return result == 0;
}
-
+
}; /* Fast Lock */
} // namespace ZThread