адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
@@ -0,0 +1,478 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/** Union used to split a 16-bit unsigned integer into 2 8-bit unsigned integers or vice-versa */
union IPAddressByteUnion
{
uint16 combined;
uint8 split[2];
};
static void zeroUnusedBytes (uint8* address) noexcept
{
for (int i = 4; i < 16; ++i)
address[i] = 0;
}
IPAddress::IPAddress() noexcept
{
for (int i = 0; i < 16; ++i)
address[i] = 0;
}
IPAddress::IPAddress (const uint8 bytes[], bool IPv6) noexcept : isIPv6 (IPv6)
{
for (int i = 0; i < (isIPv6 ? 16 : 4); ++i)
address[i] = bytes[i];
if (! isIPv6)
zeroUnusedBytes (address);
}
IPAddress::IPAddress (const uint16 bytes[8]) noexcept : isIPv6 (true)
{
IPAddressByteUnion temp;
for (int i = 0; i < 8; ++i)
{
temp.combined = bytes[i];
address[i * 2] = temp.split[0];
address[i * 2 + 1] = temp.split[1];
}
}
IPAddress::IPAddress (uint8 a0, uint8 a1, uint8 a2, uint8 a3) noexcept : isIPv6 (false)
{
address[0] = a0; address[1] = a1;
address[2] = a2; address[3] = a3;
zeroUnusedBytes (address);
}
IPAddress::IPAddress (uint16 a1, uint16 a2, uint16 a3, uint16 a4,
uint16 a5, uint16 a6, uint16 a7, uint16 a8) noexcept : isIPv6 (true)
{
uint16 array[8] = { a1, a2, a3, a4, a5, a6, a7, a8 };
IPAddressByteUnion temp;
for (int i = 0; i < 8; ++i)
{
temp.combined = array[i];
address[i * 2] = temp.split[0];
address[i * 2 + 1] = temp.split[1];
}
}
IPAddress::IPAddress (uint32 n) noexcept : isIPv6 (false)
{
address[0] = static_cast<uint8> (n >> 24);
address[1] = static_cast<uint8> ((n >> 16) & 255);
address[2] = static_cast<uint8> ((n >> 8) & 255);
address[3] = static_cast<uint8> ((n & 255));
zeroUnusedBytes (address);
}
bool IPAddress::isNull() const
{
for (int i = 0; i < 16; ++i)
if (address[i] != 0)
return false;
return true;
}
static String removePort (const String& adr)
{
if (adr.containsAnyOf ("[]"))
return adr.fromFirstOccurrenceOf ("[", false, true).upToLastOccurrenceOf ("]", false, true);
if (adr.indexOf (":") == adr.lastIndexOf (":"))
return adr.upToLastOccurrenceOf (":", false, true);
return adr;
}
IPAddress::IPAddress (const String& adr)
{
auto ipAddress = removePort (adr);
isIPv6 = ipAddress.contains (":");
if (! isIPv6)
{
auto tokens = StringArray::fromTokens (ipAddress, ".", {});
for (int i = 0; i < 4; ++i)
address[i] = (uint8) tokens[i].getIntValue();
zeroUnusedBytes (address);
}
else
{
auto tokens = StringArray::fromTokens (ipAddress, ":", {});
if (tokens.contains ({})) // if :: shorthand has been used
{
auto idx = tokens.indexOf ({});
tokens.set (idx, "0");
tokens.removeEmptyStrings();
// mapped IPv4 address will be treated as a single token, so pad the end of the StringArray
if (tokens[tokens.size() - 1].containsChar ('.'))
tokens.add ({});
while (tokens.size() < 8)
tokens.insert (idx, "0");
}
for (int i = 0; i < 8; ++i)
{
if (i == 6 && isIPv4MappedAddress (IPAddress (address, true)))
{
IPAddress v4Address (tokens[i]);
address[12] = v4Address.address[0];
address[13] = v4Address.address[1];
address[14] = v4Address.address[2];
address[15] = v4Address.address[3];
break;
}
IPAddressByteUnion temp;
temp.combined = CharacterFunctions::HexParser<uint16>::parse (tokens[i].getCharPointer());
address[i * 2] = temp.split[0];
address[i * 2 + 1] = temp.split[1];
}
}
}
String IPAddress::toString() const
{
if (! isIPv6)
{
String s ((int) address[0]);
for (int i = 1; i < 4; ++i)
s << '.' << (int) address[i];
return s;
}
IPAddressByteUnion temp;
temp.split[0] = address[0];
temp.split[1] = address[1];
auto addressString = String::toHexString (temp.combined);
for (int i = 1; i < 8; ++i)
{
temp.split[0] = address[i * 2];
temp.split[1] = address[i * 2 + 1];
addressString << ':' << String::toHexString (temp.combined);
}
return getFormattedAddress (addressString);
}
bool IPAddress::operator== (const IPAddress& other) const noexcept { return compare (other) == 0; }
bool IPAddress::operator!= (const IPAddress& other) const noexcept { return compare (other) != 0; }
bool IPAddress::operator< (const IPAddress& other) const noexcept { return compare (other) < 0; }
bool IPAddress::operator<= (const IPAddress& other) const noexcept { return compare (other) <= 0; }
bool IPAddress::operator> (const IPAddress& other) const noexcept { return compare (other) > 0; }
bool IPAddress::operator>= (const IPAddress& other) const noexcept { return compare (other) >= 0; }
int IPAddress::compare (const IPAddress& other) const noexcept
{
if (isIPv6 != other.isIPv6)
{
if (isIPv6)
{
if (isIPv4MappedAddress (*this))
return convertIPv4MappedAddressToIPv4 (*this).compare (other);
return 1;
}
if (isIPv4MappedAddress (other))
return compare (convertIPv4MappedAddressToIPv4 (other));
return -1;
}
for (int i = 0; i < (isIPv6 ? 16 : 4); ++i)
{
if (address[i] > other.address[i]) return 1;
if (address[i] < other.address[i]) return -1;
}
return 0;
}
IPAddress IPAddress::any() noexcept { return IPAddress(); }
IPAddress IPAddress::broadcast() noexcept { return IPAddress (255, 255, 255, 255); }
IPAddress IPAddress::local (bool IPv6) noexcept { return IPv6 ? IPAddress (0, 0, 0, 0, 0, 0, 0, 1)
: IPAddress (127, 0, 0, 1); }
String IPAddress::getFormattedAddress (const String& unformattedAddress)
{
jassert (unformattedAddress.contains (":") && ! unformattedAddress.contains ("::")); // needs to be an unformatted IPv6 address!
auto portString = unformattedAddress.fromFirstOccurrenceOf ("]", false, true);
auto addressString = unformattedAddress.dropLastCharacters (portString.length()).removeCharacters ("[]");
auto tokens = StringArray::fromTokens (addressString, ":", {});
int numZeros = 0;
int numZerosTemp = 0;
bool isFirst = false;
bool isLast = false;
for (int i = 0; i < tokens.size(); ++i)
{
auto& t = tokens.getReference (i);
if (t.getHexValue32() == 0x0000)
{
++numZeros;
if (i == 0)
isFirst = true;
else if (i == tokens.size() - 1 && numZeros > numZerosTemp)
isLast = true;
if (t.length() > 1)
addressString = addressString.replace (String::repeatedString ("0", t.length()), "0");
if (isFirst && numZerosTemp != 0 && numZeros > numZerosTemp)
isFirst = false;
}
else
{
addressString = addressString.replace (t, t.trimCharactersAtStart ("0").toLowerCase());
if (numZeros > 0)
{
if (numZeros > numZerosTemp)
numZerosTemp = numZeros;
numZeros = 0;
}
}
}
if (numZerosTemp > numZeros)
numZeros = numZerosTemp;
if (numZeros > 1)
{
if (numZeros == tokens.size())
{
addressString = "::,";
}
else
{
auto zeroString = isFirst ? "0" + String::repeatedString (":0", numZeros - 1)
: String::repeatedString (":0", numZeros);
addressString = addressString.replaceFirstOccurrenceOf (zeroString, ":");
if (isLast)
addressString << ':';
}
}
if (portString.isNotEmpty())
addressString = "[" + addressString + "]" + portString;
return addressString;
}
bool IPAddress::isIPv4MappedAddress (const IPAddress& mappedAddress)
{
if (! mappedAddress.isIPv6)
return false;
for (int i = 0; i < 10; ++i)
if (mappedAddress.address[i] != 0)
return false;
if (mappedAddress.address[10] != 255 || mappedAddress.address[11] != 255)
return false;
return true;
}
IPAddress IPAddress::convertIPv4MappedAddressToIPv4 (const IPAddress& mappedAddress)
{
// The address that you're converting needs to be IPv6!
jassert (mappedAddress.isIPv6);
if (isIPv4MappedAddress (mappedAddress))
return { mappedAddress.address[12], mappedAddress.address[13],
mappedAddress.address[14], mappedAddress.address[15] };
return {};
}
IPAddress IPAddress::convertIPv4AddressToIPv4Mapped (const IPAddress& addressToMap)
{
// The address that you're converting needs to be IPv4!
jassert (! addressToMap.isIPv6);
return { 0x0, 0x0, 0x0, 0x0, 0x0, 0xffff,
static_cast<uint16> ((addressToMap.address[0] << 8) | addressToMap.address[1]),
static_cast<uint16> ((addressToMap.address[2] << 8) | addressToMap.address[3]) };
}
IPAddress IPAddress::getLocalAddress (bool includeIPv6)
{
auto addresses = getAllAddresses (includeIPv6);
for (auto& a : addresses)
if (a != local())
return a;
return local();
}
Array<IPAddress> IPAddress::getAllAddresses (bool includeIPv6)
{
Array<IPAddress> addresses;
findAllAddresses (addresses, includeIPv6);
return addresses;
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct IPAddressTests final : public UnitTest
{
IPAddressTests()
: UnitTest ("IPAddress", UnitTestCategories::networking)
{}
void runTest() override
{
testConstructors();
testFindAllAddresses();
testFindBroadcastAddress();
}
void testConstructors()
{
beginTest ("constructors");
// Default IPAdress should be null
IPAddress defaultConstructed;
expect (defaultConstructed.isNull());
auto local = IPAddress::local();
expect (! local.isNull());
IPAddress ipv4{1, 2, 3, 4};
expect (! ipv4.isNull());
expect (! ipv4.isIPv6);
expect (ipv4.toString() == "1.2.3.4");
}
void testFindAllAddresses()
{
beginTest ("find all addresses");
Array<IPAddress> ipv4Addresses;
Array<IPAddress> allAddresses;
IPAddress::findAllAddresses (ipv4Addresses, false);
IPAddress::findAllAddresses (allAddresses, true);
expect (allAddresses.size() >= ipv4Addresses.size());
for (auto& a : ipv4Addresses)
{
expect (! a.isNull());
expect (! a.isIPv6);
}
for (auto& a : allAddresses)
{
expect (! a.isNull());
}
}
void testFindBroadcastAddress()
{
beginTest ("broadcast addresses");
Array<IPAddress> addresses;
// Only IPv4 interfaces have broadcast
IPAddress::findAllAddresses (addresses, false);
for (auto& a : addresses)
{
expect (! a.isNull());
auto broadcastAddress = IPAddress::getInterfaceBroadcastAddress (a);
// If we retrieve an address, it should be an IPv4 address
if (! broadcastAddress.isNull())
{
expect (! a.isIPv6);
}
}
// Expect to fail to find a broadcast for this address
IPAddress address{1, 2, 3, 4};
expect (IPAddress::getInterfaceBroadcastAddress (address).isNull());
}
};
static IPAddressTests iPAddressTests;
#endif
} // namespace juce
@@ -0,0 +1,154 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Represents an IP address.
@tags{Core}
*/
class JUCE_API IPAddress final
{
public:
//==============================================================================
/** Returns an IP address meaning "any", equivalent to 0.0.0.0 (IPv4) or ::, (IPv6) */
static IPAddress any() noexcept;
/** Returns an IPv4 address meaning "broadcast" (255.255.255.255) */
static IPAddress broadcast() noexcept;
/** Returns an IPv4 or IPv6 address meaning "localhost", equivalent to 127.0.0.1 (IPv4) or ::1 (IPv6) */
static IPAddress local (bool IPv6 = false) noexcept;
//==============================================================================
/** Populates a list of all the IP addresses that this machine is using. */
static void findAllAddresses (Array<IPAddress>& results, bool includeIPv6 = false);
/** Populates a list of all the IP addresses that this machine is using. */
static Array<IPAddress> getAllAddresses (bool includeIPv6 = false);
/** Returns the first 'real' address for the local machine.
Unlike local(), this will attempt to find the machine's actual assigned
address rather than "127.0.0.1". If there are multiple network cards, this
may return any of their addresses. If it doesn't find any, then it'll return
local() as a fallback.
*/
static IPAddress getLocalAddress (bool includeIPv6 = false);
//==============================================================================
/** Creates a null address - 0.0.0.0 (IPv4) or ::, (IPv6) */
IPAddress() noexcept;
/** Creates an IPv4 or IPv6 address by reading 4 or 16 bytes from an array.
@param bytes The array containing the bytes to read.
@param IPv6 if true indicates that 16 bytes should be read instead of 4.
*/
explicit IPAddress (const uint8* bytes, bool IPv6 = false) noexcept;
/** Creates an IPv6 address from an array of 8 16-bit integers
@param bytes The array containing the bytes to read.
*/
explicit IPAddress (const uint16* bytes) noexcept;
/** Creates an IPv4 address from 4 bytes. */
IPAddress (uint8 address1, uint8 address2, uint8 address3, uint8 address4) noexcept;
/** Creates an IPv6 address from 8 16-bit integers */
IPAddress (uint16 address1, uint16 address2, uint16 address3, uint16 address4,
uint16 address5, uint16 address6, uint16 address7, uint16 address8) noexcept;
/** Creates an IPv4 address from a packed 32-bit integer, where the
MSB is the first number in the address, and the LSB is the last.
*/
explicit IPAddress (uint32 asNativeEndian32Bit) noexcept;
/** Parses a string IP address of the form "1.2.3.4" (IPv4) or "1:2:3:4:5:6:7:8" (IPv6). */
explicit IPAddress (const String& address);
/** Returns whether the address contains the null address (e.g. 0.0.0.0). */
bool isNull() const;
//==============================================================================
/** Returns a dot- or colon-separated string in the form "1.2.3.4" (IPv4) or "1:2:3:4:5:6:7:8" (IPv6). */
String toString() const;
/** Compares this IPAddress with another.
@returns 0 if the two addresses are identical, negative if this address is smaller than
the other one, or positive if is greater.
*/
int compare (const IPAddress&) const noexcept;
bool operator== (const IPAddress&) const noexcept;
bool operator!= (const IPAddress&) const noexcept;
bool operator< (const IPAddress&) const noexcept;
bool operator> (const IPAddress&) const noexcept;
bool operator<= (const IPAddress&) const noexcept;
bool operator>= (const IPAddress&) const noexcept;
//==============================================================================
/** The elements of the IP address. */
uint8 address[16];
bool isIPv6 = false;
//==============================================================================
/** Returns a formatted version of the provided IPv6 address conforming to RFC 5952 with leading zeros suppressed,
lower case characters, and double-colon notation used to represent contiguous 16-bit fields of zeros.
@param unformattedAddress the IPv6 address to be formatted
*/
static String getFormattedAddress (const String& unformattedAddress);
/** Returns true if the given IP address is an IPv4-mapped IPv6 address. */
static bool isIPv4MappedAddress (const IPAddress& mappedAddress);
/** Converts an IPv4-mapped IPv6 address to an IPv4 address.
If the address is not IPv4-mapped, this will return a null address.
*/
static IPAddress convertIPv4MappedAddressToIPv4 (const IPAddress& mappedAddress);
/** Converts an IPv4 address to an IPv4-mapped IPv6 address. */
static IPAddress convertIPv4AddressToIPv4Mapped (const IPAddress& addressToMap);
/** If the IPAdress is the address of an interface on the machine, returns the associated broadcast address.
If the address is not an interface, it will return a null address.
*/
static IPAddress getInterfaceBroadcastAddress (const IPAddress& interfaceAddress);
};
} // namespace juce
@@ -0,0 +1,112 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
MACAddress::MACAddress() noexcept
{
zeromem (address, sizeof (address));
}
MACAddress::MACAddress (const MACAddress& other) noexcept
{
memcpy (address, other.address, sizeof (address));
}
MACAddress& MACAddress::operator= (const MACAddress& other) noexcept
{
memcpy (address, other.address, sizeof (address));
return *this;
}
MACAddress::MACAddress (const uint8 bytes[6]) noexcept
{
memcpy (address, bytes, sizeof (address));
}
MACAddress::MACAddress (StringRef addressString)
{
MemoryBlock hex;
hex.loadFromHexString (addressString);
if (hex.getSize() == sizeof (address))
memcpy (address, hex.getData(), sizeof (address));
else
zeromem (address, sizeof (address));
}
String MACAddress::toString() const
{
return toString ("-");
}
String MACAddress::toString (StringRef separator) const
{
String s;
for (size_t i = 0; i < sizeof (address); ++i)
{
s << String::toHexString ((int) address[i]).paddedLeft ('0', 2);
if (i < sizeof (address) - 1)
s << separator;
}
return s;
}
int64 MACAddress::toInt64() const noexcept
{
int64 n = 0;
for (int i = (int) sizeof (address); --i >= 0;)
n = (n << 8) | address[i];
return n;
}
Array<MACAddress> MACAddress::getAllAddresses()
{
Array<MACAddress> addresses;
findAllAddresses (addresses);
return addresses;
}
bool MACAddress::isNull() const noexcept { return toInt64() == 0; }
bool MACAddress::operator== (const MACAddress& other) const noexcept { return memcmp (address, other.address, sizeof (address)) == 0; }
bool MACAddress::operator!= (const MACAddress& other) const noexcept { return ! operator== (other); }
} // namespace juce
@@ -0,0 +1,100 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Represents a MAC network card adapter address ID.
@tags{Core}
*/
class JUCE_API MACAddress final
{
public:
//==============================================================================
/** Returns a list of the MAC addresses of all the available network cards. */
static Array<MACAddress> getAllAddresses();
/** Populates a list of the MAC addresses of all the available network cards. */
static void findAllAddresses (Array<MACAddress>& results);
//==============================================================================
/** Creates a null address (00-00-00-00-00-00). */
MACAddress() noexcept;
/** Creates a copy of another address. */
MACAddress (const MACAddress&) noexcept;
/** Creates a copy of another address. */
MACAddress& operator= (const MACAddress&) noexcept;
/** Creates an address from 6 bytes. */
explicit MACAddress (const uint8 bytes[6]) noexcept;
/** Creates an address from a hex string.
If the string isn't a 6-byte hex value, this will just default-initialise
the object.
*/
explicit MACAddress (StringRef address);
/** Returns a pointer to the 6 bytes that make up this address. */
const uint8* getBytes() const noexcept { return address; }
/** Returns a dash-separated string in the form "11-22-33-44-55-66" */
String toString() const;
/** Returns a hex string of this address, using a custom separator between each byte. */
String toString (StringRef separator) const;
/** Returns the address in the lower 6 bytes of an int64.
This uses a little-endian arrangement, with the first byte of the address being
stored in the least-significant byte of the result value.
*/
int64 toInt64() const noexcept;
/** Returns true if this address is null (00-00-00-00-00-00). */
bool isNull() const noexcept;
bool operator== (const MACAddress&) const noexcept;
bool operator!= (const MACAddress&) const noexcept;
//==============================================================================
private:
uint8 address[6];
};
} // namespace juce
@@ -0,0 +1,294 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if ! JUCE_WASM
NamedPipe::NamedPipe() {}
NamedPipe::~NamedPipe()
{
close();
}
bool NamedPipe::openExisting (const String& pipeName)
{
close();
ScopedWriteLock sl (lock);
currentPipeName = pipeName;
return openInternal (pipeName, false, false);
}
bool NamedPipe::isOpen() const
{
ScopedReadLock sl (lock);
return pimpl != nullptr;
}
bool NamedPipe::createNewPipe (const String& pipeName, bool mustNotExist)
{
close();
ScopedWriteLock sl (lock);
currentPipeName = pipeName;
return openInternal (pipeName, true, mustNotExist);
}
String NamedPipe::getName() const
{
ScopedReadLock sl (lock);
return currentPipeName;
}
// other methods for this class are implemented in the platform-specific files
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class NamedPipeTests final : public UnitTest
{
public:
//==============================================================================
NamedPipeTests()
: UnitTest ("NamedPipe", UnitTestCategories::networking)
{}
void runTest() override
{
const auto pid =
#if JUCE_WINDOWS
_getpid();
#else
getpid();
#endif
const auto pipeName = "TestPipe-"
+ String::toHexString (pid)
+ "-"
+ String::toHexString (Time::currentTimeMillis());
beginTest ("Pre test cleanup");
{
NamedPipe pipe;
expect (pipe.createNewPipe (pipeName, false));
}
beginTest ("Create pipe");
{
NamedPipe pipe;
expect (! pipe.isOpen());
expect (pipe.createNewPipe (pipeName, true));
expect (pipe.isOpen());
expect (pipe.createNewPipe (pipeName, false));
expect (pipe.isOpen());
NamedPipe otherPipe;
expect (! otherPipe.createNewPipe (pipeName, true));
expect (! otherPipe.isOpen());
}
beginTest ("Existing pipe");
{
NamedPipe pipe;
expect (! pipe.openExisting (pipeName));
expect (! pipe.isOpen());
expect (pipe.createNewPipe (pipeName, true));
NamedPipe otherPipe;
expect (otherPipe.openExisting (pipeName));
expect (otherPipe.isOpen());
}
int sendData = 4684682;
beginTest ("Receive message created pipe");
{
NamedPipe pipe;
expect (pipe.createNewPipe (pipeName, true));
WaitableEvent senderFinished;
SenderThread sender (pipeName, false, senderFinished, sendData);
sender.startThread();
int recvData = -1;
auto bytesRead = pipe.read (&recvData, sizeof (recvData), 2000);
expect (senderFinished.wait (4000));
expectEquals (bytesRead, (int) sizeof (recvData));
expectEquals (sender.result, (int) sizeof (sendData));
expectEquals (recvData, sendData);
}
beginTest ("Receive message existing pipe");
{
WaitableEvent senderFinished;
SenderThread sender (pipeName, true, senderFinished, sendData);
NamedPipe pipe;
expect (pipe.openExisting (pipeName));
sender.startThread();
int recvData = -1;
auto bytesRead = pipe.read (&recvData, sizeof (recvData), 2000);
expect (senderFinished.wait (4000));
expectEquals (bytesRead, (int) sizeof (recvData));
expectEquals (sender.result, (int) sizeof (sendData));
expectEquals (recvData, sendData);
}
beginTest ("Send message created pipe");
{
NamedPipe pipe;
expect (pipe.createNewPipe (pipeName, true));
WaitableEvent receiverFinished;
ReceiverThread receiver (pipeName, false, receiverFinished);
receiver.startThread();
auto bytesWritten = pipe.write (&sendData, sizeof (sendData), 2000);
expect (receiverFinished.wait (4000));
expectEquals (bytesWritten, (int) sizeof (sendData));
expectEquals (receiver.result, (int) sizeof (receiver.recvData));
expectEquals (receiver.recvData, sendData);
}
beginTest ("Send message existing pipe");
{
WaitableEvent receiverFinished;
ReceiverThread receiver (pipeName, true, receiverFinished);
NamedPipe pipe;
expect (pipe.openExisting (pipeName));
receiver.startThread();
auto bytesWritten = pipe.write (&sendData, sizeof (sendData), 2000);
expect (receiverFinished.wait (4000));
expectEquals (bytesWritten, (int) sizeof (sendData));
expectEquals (receiver.result, (int) sizeof (receiver.recvData));
expectEquals (receiver.recvData, sendData);
}
}
private:
//==============================================================================
struct NamedPipeThread : public Thread
{
NamedPipeThread (const String& tName, const String& pName,
bool shouldCreatePipe, WaitableEvent& completed)
: Thread (tName), pipeName (pName), workCompleted (completed)
{
if (shouldCreatePipe)
pipe.createNewPipe (pipeName);
else
pipe.openExisting (pipeName);
}
NamedPipe pipe;
const String& pipeName;
WaitableEvent& workCompleted;
int result = -2;
};
//==============================================================================
struct SenderThread final : public NamedPipeThread
{
SenderThread (const String& pName, bool shouldCreatePipe,
WaitableEvent& completed, int sData)
: NamedPipeThread ("NamePipeSender", pName, shouldCreatePipe, completed),
sendData (sData)
{}
~SenderThread() override
{
stopThread (100);
}
void run() override
{
result = pipe.write (&sendData, sizeof (sendData), 2000);
workCompleted.signal();
}
const int sendData;
};
//==============================================================================
struct ReceiverThread final : public NamedPipeThread
{
ReceiverThread (const String& pName, bool shouldCreatePipe,
WaitableEvent& completed)
: NamedPipeThread ("NamePipeReceiver", pName, shouldCreatePipe, completed)
{}
~ReceiverThread() override
{
stopThread (100);
}
void run() override
{
result = pipe.read (&recvData, sizeof (recvData), 2000);
workCompleted.signal();
}
int recvData = -2;
};
};
static NamedPipeTests namedPipeTests;
#endif
#endif
} // namespace juce
@@ -0,0 +1,112 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A cross-process pipe that can have data written to and read from it.
Two processes can use NamedPipe objects to exchange blocks of data.
@see InterprocessConnection
@tags{Core}
*/
class JUCE_API NamedPipe final
{
public:
//==============================================================================
/** Creates a NamedPipe. */
NamedPipe();
/** Destructor. */
~NamedPipe();
//==============================================================================
/** Tries to open a pipe that already exists.
Returns true if it succeeds.
*/
bool openExisting (const String& pipeName);
/** Tries to create a new pipe.
Returns true if it succeeds.
If mustNotExist is true then it will fail if a pipe is already
open with the same name.
*/
bool createNewPipe (const String& pipeName, bool mustNotExist = false);
/** Closes the pipe, if it's open. */
void close();
/** True if the pipe is currently open. */
bool isOpen() const;
/** Returns the last name that was used to try to open this pipe. */
String getName() const;
//==============================================================================
/** Reads data from the pipe.
This will block until another thread has written enough data into the pipe to fill
the number of bytes specified, or until another thread calls the cancelPendingReads()
method.
If the operation fails, it returns -1, otherwise, it will return the number of
bytes read.
If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
this is a maximum timeout for reading from the pipe.
*/
int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds);
/** Writes some data to the pipe.
@returns the number of bytes written, or -1 on failure.
*/
int write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds);
private:
//==============================================================================
JUCE_PUBLIC_IN_DLL_BUILD (class Pimpl)
std::unique_ptr<Pimpl> pimpl;
String currentPipeName;
ReadWriteLock lock;
bool openInternal (const String& pipeName, bool createPipe, bool mustNotExist);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe)
};
} // namespace juce
@@ -0,0 +1,904 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if ! JUCE_WASM
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4127 4389 4018)
#ifndef AI_NUMERICSERV // (missing in older Mac SDKs)
#define AI_NUMERICSERV 0x1000
#endif
#if JUCE_WINDOWS
using juce_socklen_t = int;
using juce_recvsend_size_t = int;
using SocketHandle = SOCKET;
static const SocketHandle invalidSocket = INVALID_SOCKET;
#elif JUCE_ANDROID
using juce_socklen_t = socklen_t;
using juce_recvsend_size_t = size_t;
using SocketHandle = int;
static const SocketHandle invalidSocket = -1;
#else
using juce_socklen_t = socklen_t;
using juce_recvsend_size_t = socklen_t;
using SocketHandle = int;
static const SocketHandle invalidSocket = -1;
#endif
//==============================================================================
namespace SocketHelpers
{
static void initSockets()
{
#if JUCE_WINDOWS
static bool socketsStarted = false;
if (! socketsStarted)
{
WSADATA wsaData;
const WORD wVersionRequested = MAKEWORD (1, 1);
socketsStarted = WSAStartup (wVersionRequested, &wsaData) == 0;
}
#endif
}
inline bool isValidPortNumber (int port) noexcept
{
return isPositiveAndBelow (port, 65536);
}
template <typename Type>
static bool setOption (SocketHandle handle, int mode, int property, Type value) noexcept
{
return setsockopt (handle, mode, property, reinterpret_cast<const char*> (&value), sizeof (value)) == 0;
}
template <typename Type>
static bool setOption (SocketHandle handle, int property, Type value) noexcept
{
return setOption (handle, SOL_SOCKET, property, value);
}
static std::optional<int> getBufferSize (SocketHandle handle, int property)
{
int result;
auto outParamSize = (socklen_t) sizeof (result);
if (getsockopt (handle, SOL_SOCKET, property, reinterpret_cast<char*> (&result), &outParamSize) != 0
|| outParamSize != (socklen_t) sizeof (result))
{
return std::nullopt;
}
return result;
}
static bool resetSocketOptions (SocketHandle handle, bool isDatagram, bool allowBroadcast, const SocketOptions& options) noexcept
{
auto getCurrentBufferSizeWithMinimum = [handle] (int property)
{
constexpr auto minBufferSize = 65536;
if (auto currentBufferSize = getBufferSize (handle, property))
return std::max (*currentBufferSize, minBufferSize);
return minBufferSize;
};
const auto receiveBufferSize = options.getReceiveBufferSize().value_or (getCurrentBufferSizeWithMinimum (SO_RCVBUF));
const auto sendBufferSize = options.getSendBufferSize() .value_or (getCurrentBufferSizeWithMinimum (SO_SNDBUF));
return handle != invalidSocket
&& setOption (handle, SO_RCVBUF, receiveBufferSize)
&& setOption (handle, SO_SNDBUF, sendBufferSize)
&& (isDatagram ? ((! allowBroadcast) || setOption (handle, SO_BROADCAST, (int) 1))
: setOption (handle, IPPROTO_TCP, TCP_NODELAY, (int) 1));
}
static void closeSocket (std::atomic<int>& handle,
[[maybe_unused]] CriticalSection& readLock,
[[maybe_unused]] bool isListener,
[[maybe_unused]] int portNumber,
std::atomic<bool>& connected) noexcept
{
const auto h = (SocketHandle) handle.load();
handle = -1;
#if JUCE_WINDOWS
if (h != invalidSocket || connected)
closesocket (h);
// make sure any read process finishes before we delete the socket
CriticalSection::ScopedLockType lock (readLock);
connected = false;
#else
if (connected)
{
connected = false;
if (isListener)
{
// need to do this to interrupt the accept() function
StreamingSocket temp;
temp.connect (IPAddress::local().toString(), portNumber, 1000);
}
}
if (h >= 0)
{
// unblock any pending read requests
::shutdown (h, SHUT_RDWR);
{
// see man-page of recv on linux about a race condition where the
// shutdown command is lost if the receiving thread does not have
// a chance to process before close is called. On Mac OS X shutdown
// does not unblock a select call, so using a lock here will dead-lock
// both threads.
#if JUCE_LINUX || JUCE_BSD || JUCE_ANDROID
CriticalSection::ScopedLockType lock (readLock);
::close (h);
#else
::close (h);
CriticalSection::ScopedLockType lock (readLock);
#endif
}
}
#endif
}
static bool bindSocket (SocketHandle handle, int port, const String& address) noexcept
{
if (handle == invalidSocket || ! isValidPortNumber (port))
return false;
struct sockaddr_in addr;
zerostruct (addr); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct)
addr.sin_family = PF_INET;
addr.sin_port = htons ((uint16) port);
addr.sin_addr.s_addr = address.isNotEmpty() ? ::inet_addr (address.toRawUTF8())
: htonl (INADDR_ANY);
return ::bind (handle, (struct sockaddr*) &addr, sizeof (addr)) >= 0;
}
static int getBoundPort (SocketHandle handle) noexcept
{
if (handle != invalidSocket)
{
struct sockaddr_in addr;
socklen_t len = sizeof (addr);
if (getsockname (handle, (struct sockaddr*) &addr, &len) == 0)
return ntohs (addr.sin_port);
}
return -1;
}
static String getConnectedAddress (SocketHandle handle) noexcept
{
struct sockaddr_in addr;
socklen_t len = sizeof (addr);
if (getpeername (handle, (struct sockaddr*) &addr, &len) >= 0)
return inet_ntoa (addr.sin_addr);
return "0.0.0.0";
}
static bool setSocketBlockingState (SocketHandle handle, bool shouldBlock) noexcept
{
#if JUCE_WINDOWS
u_long nonBlocking = shouldBlock ? 0 : (u_long) 1;
return ioctlsocket (handle, (long) FIONBIO, &nonBlocking) == 0;
#else
int socketFlags = fcntl (handle, F_GETFL, 0);
if (socketFlags == -1)
return false;
if (shouldBlock)
socketFlags &= ~O_NONBLOCK;
else
socketFlags |= O_NONBLOCK;
return fcntl (handle, F_SETFL, socketFlags) == 0;
#endif
}
#if ! JUCE_WINDOWS
static bool getSocketBlockingState (SocketHandle handle)
{
return (fcntl (handle, F_GETFL, 0) & O_NONBLOCK) == 0;
}
#endif
static int readSocket (SocketHandle handle,
void* destBuffer, int maxBytesToRead,
std::atomic<bool>& connected,
bool blockUntilSpecifiedAmountHasArrived,
CriticalSection& readLock,
String* senderIP = nullptr,
int* senderPort = nullptr) noexcept
{
#if ! JUCE_WINDOWS
if (blockUntilSpecifiedAmountHasArrived != getSocketBlockingState (handle))
#endif
setSocketBlockingState (handle, blockUntilSpecifiedAmountHasArrived);
int bytesRead = 0;
while (bytesRead < maxBytesToRead)
{
long bytesThisTime = -1;
auto buffer = static_cast<char*> (destBuffer) + bytesRead;
auto numToRead = (juce_recvsend_size_t) (maxBytesToRead - bytesRead);
{
// avoid race-condition
CriticalSection::ScopedTryLockType lock (readLock);
if (lock.isLocked())
{
if (senderIP == nullptr || senderPort == nullptr)
{
bytesThisTime = ::recv (handle, buffer, numToRead, 0);
}
else
{
sockaddr_in client;
socklen_t clientLen = sizeof (sockaddr);
bytesThisTime = ::recvfrom (handle, buffer, numToRead, 0, (sockaddr*) &client, &clientLen);
*senderIP = String::fromUTF8 (inet_ntoa (client.sin_addr), 16);
*senderPort = ntohs (client.sin_port);
}
}
}
if (bytesThisTime <= 0 || ! connected)
{
if (bytesRead == 0 && blockUntilSpecifiedAmountHasArrived)
bytesRead = -1;
break;
}
bytesRead = static_cast<int> (bytesRead + bytesThisTime);
if (! blockUntilSpecifiedAmountHasArrived)
break;
}
return (int) bytesRead;
}
static int waitForReadiness (std::atomic<int>& handle, CriticalSection& readLock,
bool forReading, int timeoutMsecs) noexcept
{
// avoid race-condition
CriticalSection::ScopedTryLockType lock (readLock);
if (! lock.isLocked())
return -1;
auto hasErrorOccurred = [&handle]() -> bool
{
auto h = (SocketHandle) handle.load();
if (h == invalidSocket)
return true;
int opt;
juce_socklen_t len = sizeof (opt);
if (getsockopt (h, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0 || opt != 0)
return true;
return false;
};
auto h = handle.load();
#if JUCE_WINDOWS
struct timeval timeout;
struct timeval* timeoutp;
if (timeoutMsecs >= 0)
{
timeout.tv_sec = timeoutMsecs / 1000;
timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
timeoutp = &timeout;
}
else
{
timeoutp = nullptr;
}
fd_set rset, wset;
FD_ZERO (&rset);
FD_SET ((SOCKET) h, &rset);
FD_ZERO (&wset);
FD_SET ((SOCKET) h, &wset);
fd_set* prset = forReading ? &rset : nullptr;
fd_set* pwset = forReading ? nullptr : &wset;
// NB - need to use select() here as WSAPoll is broken on Windows
if (select ((int) h + 1, prset, pwset, nullptr, timeoutp) < 0 || hasErrorOccurred())
return -1;
return FD_ISSET (h, forReading ? &rset : &wset) ? 1 : 0;
#else
short eventsFlag = (forReading ? POLLIN : POLLOUT);
pollfd pfd { (SocketHandle) h, eventsFlag, 0 };
int result = 0;
for (;;)
{
result = poll (&pfd, 1, timeoutMsecs);
if (result >= 0 || errno != EINTR)
break;
}
if (result < 0 || hasErrorOccurred())
return -1;
return (pfd.revents & eventsFlag) != 0;
#endif
}
static addrinfo* getAddressInfo (bool isDatagram, const String& hostName, int portNumber)
{
struct addrinfo hints;
zerostruct (hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = isDatagram ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
struct addrinfo* info = nullptr;
if (getaddrinfo (hostName.toRawUTF8(), String (portNumber).toRawUTF8(), &hints, &info) == 0)
return info;
return nullptr;
}
static bool connectSocket (std::atomic<int>& handle,
CriticalSection& readLock,
const String& hostName,
int portNumber,
int timeOutMillisecs,
const SocketOptions& options) noexcept
{
bool success = false;
if (auto* info = getAddressInfo (false, hostName, portNumber))
{
for (auto* i = info; i != nullptr; i = i->ai_next)
{
auto newHandle = socket (i->ai_family, i->ai_socktype, 0);
if (newHandle != invalidSocket)
{
setSocketBlockingState (newHandle, false);
auto result = ::connect (newHandle, i->ai_addr, (socklen_t) i->ai_addrlen);
success = (result >= 0);
if (! success)
{
#if JUCE_WINDOWS
if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
#else
if (errno == EINPROGRESS)
#endif
{
std::atomic<int> cvHandle { (int) newHandle };
if (waitForReadiness (cvHandle, readLock, false, timeOutMillisecs) == 1)
success = true;
}
}
if (success)
{
handle = (int) newHandle;
break;
}
#if JUCE_WINDOWS
closesocket (newHandle);
#else
::close (newHandle);
#endif
}
}
freeaddrinfo (info);
if (success)
{
auto h = (SocketHandle) handle.load();
setSocketBlockingState (h, true);
resetSocketOptions (h, false, false, options);
}
}
return success;
}
static void makeReusable (int handle) noexcept
{
setOption ((SocketHandle) handle, SO_REUSEADDR, (int) 1);
}
static bool multicast (int handle, const String& multicastIPAddress,
const String& interfaceIPAddress, bool join) noexcept
{
struct ip_mreq mreq;
zerostruct (mreq);
mreq.imr_multiaddr.s_addr = inet_addr (multicastIPAddress.toRawUTF8());
mreq.imr_interface.s_addr = INADDR_ANY;
if (interfaceIPAddress.isNotEmpty())
mreq.imr_interface.s_addr = inet_addr (interfaceIPAddress.toRawUTF8());
return setsockopt ((SocketHandle) handle, IPPROTO_IP,
join ? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP,
(const char*) &mreq, sizeof (mreq)) == 0;
}
}
//==============================================================================
StreamingSocket::StreamingSocket()
{
SocketHelpers::initSockets();
}
StreamingSocket::StreamingSocket (const String& host, int portNum, int h, const SocketOptions& optionsIn)
: options (optionsIn),
hostName (host),
portNumber (portNum),
handle (h),
connected (true)
{
jassert (SocketHelpers::isValidPortNumber (portNum));
SocketHelpers::initSockets();
SocketHelpers::resetSocketOptions ((SocketHandle) h, false, false, options);
}
StreamingSocket::~StreamingSocket()
{
close();
}
//==============================================================================
int StreamingSocket::read (void* destBuffer, int maxBytesToRead, bool shouldBlock)
{
return (connected && ! isListener) ? SocketHelpers::readSocket ((SocketHandle) handle.load(), destBuffer,maxBytesToRead,
connected, shouldBlock, readLock)
: -1;
}
int StreamingSocket::write (const void* sourceBuffer, int numBytesToWrite)
{
if (isListener || ! connected)
return -1;
return (int) ::send ((SocketHandle) handle.load(), (const char*) sourceBuffer, (juce_recvsend_size_t) numBytesToWrite, 0);
}
//==============================================================================
int StreamingSocket::waitUntilReady (bool readyForReading, int timeoutMsecs)
{
return connected ? SocketHelpers::waitForReadiness (handle, readLock, readyForReading, timeoutMsecs)
: -1;
}
//==============================================================================
bool StreamingSocket::bindToPort (int port)
{
return bindToPort (port, String());
}
bool StreamingSocket::bindToPort (int port, const String& addr)
{
jassert (SocketHelpers::isValidPortNumber (port));
return SocketHelpers::bindSocket ((SocketHandle) handle.load(), port, addr);
}
int StreamingSocket::getBoundPort() const noexcept
{
return SocketHelpers::getBoundPort ((SocketHandle) handle.load());
}
bool StreamingSocket::connect (const String& remoteHostName, int remotePortNumber, int timeOutMillisecs)
{
jassert (SocketHelpers::isValidPortNumber (remotePortNumber));
if (isListener)
{
// a listener socket can't connect to another one!
jassertfalse;
return false;
}
if (connected)
close();
hostName = remoteHostName;
portNumber = remotePortNumber;
isListener = false;
connected = SocketHelpers::connectSocket (handle, readLock, remoteHostName,
remotePortNumber, timeOutMillisecs, options);
if (! connected)
return false;
if (! SocketHelpers::resetSocketOptions ((SocketHandle) handle.load(), false, false, options))
{
close();
return false;
}
return true;
}
void StreamingSocket::close()
{
if (handle >= 0)
SocketHelpers::closeSocket (handle, readLock, isListener, portNumber, connected);
hostName.clear();
portNumber = 0;
handle = -1;
isListener = false;
}
//==============================================================================
bool StreamingSocket::createListener (int newPortNumber, const String& localHostName)
{
jassert (SocketHelpers::isValidPortNumber (newPortNumber));
if (connected)
close();
hostName = "listener";
portNumber = newPortNumber;
isListener = true;
handle = (int) socket (AF_INET, SOCK_STREAM, 0);
if (handle < 0)
return false;
#if ! JUCE_WINDOWS // on windows, adding this option produces behaviour different to posix
SocketHelpers::makeReusable (handle);
#endif
if (SocketHelpers::bindSocket ((SocketHandle) handle.load(), portNumber, localHostName)
&& listen ((SocketHandle) handle.load(), SOMAXCONN) >= 0)
{
connected = true;
return true;
}
close();
return false;
}
StreamingSocket* StreamingSocket::waitForNextConnection() const
{
// To call this method, you first have to use createListener() to
// prepare this socket as a listener.
jassert (isListener || ! connected);
if (connected && isListener)
{
struct sockaddr_storage address;
juce_socklen_t len = sizeof (address);
auto newSocket = (int) accept ((SocketHandle) handle.load(), (struct sockaddr*) &address, &len);
if (newSocket >= 0 && connected)
return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
portNumber, newSocket, options);
}
return nullptr;
}
bool StreamingSocket::isLocal() const noexcept
{
if (! isConnected())
return false;
IPAddress currentIP (SocketHelpers::getConnectedAddress ((SocketHandle) handle.load()));
for (auto& a : IPAddress::getAllAddresses())
if (a == currentIP)
return true;
return hostName == "127.0.0.1";
}
//==============================================================================
//==============================================================================
DatagramSocket::DatagramSocket (bool canBroadcast, const SocketOptions& optionsIn)
: options { optionsIn }
{
SocketHelpers::initSockets();
handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
if (handle >= 0)
{
SocketHelpers::resetSocketOptions ((SocketHandle) handle.load(), true, canBroadcast, options);
SocketHelpers::makeReusable (handle);
}
}
DatagramSocket::~DatagramSocket()
{
if (lastServerAddress != nullptr)
freeaddrinfo (static_cast<struct addrinfo*> (lastServerAddress));
shutdown();
}
void DatagramSocket::shutdown()
{
if (handle < 0)
return;
std::atomic<int> handleCopy { handle.load() };
handle = -1;
std::atomic<bool> connected { false };
SocketHelpers::closeSocket (handleCopy, readLock, false, 0, connected);
isBound = false;
}
bool DatagramSocket::bindToPort (int port)
{
return bindToPort (port, String());
}
bool DatagramSocket::bindToPort (int port, const String& addr)
{
jassert (SocketHelpers::isValidPortNumber (port));
if (handle < 0)
return false;
if (SocketHelpers::bindSocket ((SocketHandle) handle.load(), port, addr))
{
isBound = true;
lastBindAddress = addr;
return true;
}
return false;
}
int DatagramSocket::getBoundPort() const noexcept
{
return (handle >= 0 && isBound) ? SocketHelpers::getBoundPort ((SocketHandle) handle.load()) : -1;
}
//==============================================================================
int DatagramSocket::waitUntilReady (bool readyForReading, int timeoutMsecs)
{
if (handle < 0)
return -1;
return SocketHelpers::waitForReadiness (handle, readLock, readyForReading, timeoutMsecs);
}
int DatagramSocket::read (void* destBuffer, int maxBytesToRead, bool shouldBlock)
{
if (handle < 0 || ! isBound)
return -1;
std::atomic<bool> connected { true };
return SocketHelpers::readSocket ((SocketHandle) handle.load(), destBuffer, maxBytesToRead,
connected, shouldBlock, readLock);
}
int DatagramSocket::read (void* destBuffer, int maxBytesToRead, bool shouldBlock, String& senderIPAddress, int& senderPort)
{
if (handle < 0 || ! isBound)
return -1;
std::atomic<bool> connected { true };
return SocketHelpers::readSocket ((SocketHandle) handle.load(), destBuffer, maxBytesToRead, connected,
shouldBlock, readLock, &senderIPAddress, &senderPort);
}
int DatagramSocket::write (const String& remoteHostname, int remotePortNumber,
const void* sourceBuffer, int numBytesToWrite)
{
jassert (SocketHelpers::isValidPortNumber (remotePortNumber));
if (handle < 0)
return -1;
struct addrinfo*& info = reinterpret_cast<struct addrinfo*&> (lastServerAddress);
// getaddrinfo can be quite slow so cache the result of the address lookup
if (info == nullptr || remoteHostname != lastServerHost || remotePortNumber != lastServerPort)
{
if (info != nullptr)
freeaddrinfo (info);
if ((info = SocketHelpers::getAddressInfo (true, remoteHostname, remotePortNumber)) == nullptr)
return -1;
lastServerHost = remoteHostname;
lastServerPort = remotePortNumber;
}
return (int) ::sendto ((SocketHandle) handle.load(), (const char*) sourceBuffer,
(juce_recvsend_size_t) numBytesToWrite, 0,
info->ai_addr, (socklen_t) info->ai_addrlen);
}
bool DatagramSocket::joinMulticast (const String& multicastIPAddress)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::multicast (handle, multicastIPAddress, lastBindAddress, true);
}
bool DatagramSocket::leaveMulticast (const String& multicastIPAddress)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::multicast (handle, multicastIPAddress, lastBindAddress, false);
}
bool DatagramSocket::setMulticastLoopbackEnabled (bool enable)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::setOption<bool> ((SocketHandle) handle.load(), IPPROTO_IP, IP_MULTICAST_LOOP, enable);
}
bool DatagramSocket::setEnablePortReuse ([[maybe_unused]] bool enabled)
{
#if ! JUCE_ANDROID
if (handle >= 0)
return SocketHelpers::setOption ((SocketHandle) handle.load(),
#if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
SO_REUSEADDR, // port re-use is implied by addr re-use on these platforms
#else
SO_REUSEPORT,
#endif
(int) (enabled ? 1 : 0));
#endif
return false;
}
JUCE_END_IGNORE_WARNINGS_MSVC
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct SocketTests final : public UnitTest
{
SocketTests()
: UnitTest ("Sockets", UnitTestCategories::networking)
{
}
void runTest() override
{
auto localHost = IPAddress::local();
int portNum = 12345;
beginTest ("StreamingSocket");
{
StreamingSocket socketServer;
expect (socketServer.isConnected() == false);
expect (socketServer.getHostName().isEmpty());
expect (socketServer.getBoundPort() == -1);
expect (static_cast<SocketHandle> (socketServer.getRawSocketHandle()) == invalidSocket);
expect (socketServer.createListener (portNum, localHost.toString()));
StreamingSocket socket;
expect (socket.connect (localHost.toString(), portNum));
expect (socket.isConnected() == true);
expect (socket.getHostName() == localHost.toString());
expect (socket.getBoundPort() != -1);
expect (static_cast<SocketHandle> (socket.getRawSocketHandle()) != invalidSocket);
socket.close();
expect (socket.isConnected() == false);
expect (socket.getHostName().isEmpty());
expect (socket.getBoundPort() == -1);
expect (static_cast<SocketHandle> (socket.getRawSocketHandle()) == invalidSocket);
}
beginTest ("DatagramSocket");
{
DatagramSocket socket;
expect (socket.getBoundPort() == -1);
expect (static_cast<SocketHandle> (socket.getRawSocketHandle()) != invalidSocket);
expect (socket.bindToPort (portNum, localHost.toString()));
expect (socket.getBoundPort() == portNum);
expect (static_cast<SocketHandle> (socket.getRawSocketHandle()) != invalidSocket);
socket.shutdown();
expect (socket.getBoundPort() == -1);
expect (static_cast<SocketHandle> (socket.getRawSocketHandle()) == invalidSocket);
}
}
};
static SocketTests socketTests;
#endif
#endif
} // namespace juce
@@ -0,0 +1,465 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/**
Options used for the configuration of the underlying system socket in the
StreamingSocket and DatagramSocket classes.
@see StreamingSocket, DatagramSocket
@tags{Core}
*/
class JUCE_API SocketOptions
{
public:
/** The provided size will be used to configure the socket's SO_RCVBUF property. Increasing the
buffer size can reduce the number of lost packets with the DatagramSocket class, if the
socket is to receive packets in large bursts.
If this property is not specified, the system default value will be used, but a minimum of
65536 will be ensured.
*/
[[nodiscard]] SocketOptions withReceiveBufferSize (int size) const
{
return withMember (*this, &SocketOptions::receiveBufferSize, size);
}
/** The provided size will be used to configure the socket's SO_SNDBUF property.
If this property is not specified, the system default value will be used, but a minimum of
65536 will be ensured.
*/
[[nodiscard]] SocketOptions withSendBufferSize (int size) const
{
return withMember (*this, &SocketOptions::sendBufferSize, size);
}
/** @see withReceiveBufferSize() */
[[nodiscard]] auto getReceiveBufferSize() const { return receiveBufferSize; }
/** @see withSendBufferSize() */
[[nodiscard]] auto getSendBufferSize() const { return sendBufferSize; }
private:
std::optional<int> receiveBufferSize;
std::optional<int> sendBufferSize;
};
//==============================================================================
/**
A wrapper for a streaming (TCP) socket.
This allows low-level use of sockets; for an easier-to-use messaging layer on top of
sockets, you could also try the InterprocessConnection class.
@see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
@tags{Core}
*/
class JUCE_API StreamingSocket final
{
public:
using Options = SocketOptions;
//==============================================================================
/** Creates an uninitialised socket.
To connect it, use the connect() method, after which you can read() or write()
to it.
To wait for other sockets to connect to this one, the createListener() method
enters "listener" mode, and can be used to spawn new sockets for each connection
that comes along.
*/
StreamingSocket();
/** Creates an uninitialised socket and allows specifying options related to the
configuration of the underlying socket.
To connect it, use the connect() method, after which you can read() or write()
to it.
To wait for other sockets to connect to this one, the createListener() method
enters "listener" mode, and can be used to spawn new sockets for each connection
that comes along.
*/
explicit StreamingSocket (const SocketOptions& optionsIn)
: options { optionsIn }
{}
/** Destructor. */
~StreamingSocket();
//==============================================================================
/** Binds the socket to the specified local port.
@returns true on success; false may indicate that another socket is already bound
on the same port
*/
bool bindToPort (int localPortNumber);
/** Binds the socket to the specified local port and local address.
If localAddress is not an empty string then the socket will be bound to localAddress
as well. This is useful if you would like to bind your socket to a specific network
adapter. Note that localAddress must be an IP address assigned to one of your
network address otherwise this function will fail.
@returns true on success; false may indicate that another socket is already bound
on the same port
@see bindToPort (int localPortNumber), IPAddress::getAllAddresses
*/
bool bindToPort (int localPortNumber, const String& localAddress);
/** Returns the local port number to which this socket is currently bound.
This is useful if you need to know to which port the OS has actually bound your
socket when calling the constructor or bindToPort with zero as the
localPortNumber argument.
@returns -1 if the function fails
*/
int getBoundPort() const noexcept;
/** Tries to connect the socket to hostname:port.
If timeOutMillisecs is 0, then this method will block until the operating system
rejects the connection (which could take a long time).
@returns true if it succeeds, false if otherwise
@see isConnected
*/
bool connect (const String& remoteHostname,
int remotePortNumber,
int timeOutMillisecs = 3000);
/** True if the socket is currently connected. */
bool isConnected() const noexcept { return connected; }
/** Closes the connection. */
void close();
/** Returns the name of the currently connected host. */
const String& getHostName() const noexcept { return hostName; }
/** Returns the port number that's currently open. */
int getPort() const noexcept { return portNumber; }
/** True if the socket is connected to this machine rather than over the network. */
bool isLocal() const noexcept;
/** Returns the OS's socket handle that's currently open. */
int getRawSocketHandle() const noexcept { return handle; }
//==============================================================================
/** Waits until the socket is ready for reading or writing.
If readyForReading is true, it will wait until the socket is ready for
reading; if false, it will wait until it's ready for writing.
If the timeout is < 0, it will wait forever, or else will give up after
the specified time.
@returns 1 if the socket is ready on return, 0 if it times-out before
the socket becomes ready, or -1 if an error occurs
*/
int waitUntilReady (bool readyForReading, int timeoutMsecs);
/** Reads bytes from the socket.
If blockUntilSpecifiedAmountHasArrived is true, the method will block until
maxBytesToRead bytes have been read, (or until an error occurs). If this
flag is false, the method will return as much data as is currently available
without blocking.
@returns the number of bytes read, or -1 if there was an error
@see waitUntilReady
*/
int read (void* destBuffer, int maxBytesToRead,
bool blockUntilSpecifiedAmountHasArrived);
/** Writes bytes to the socket from a buffer.
Note that this method will block unless you have checked the socket is ready
for writing before calling it (see the waitUntilReady() method).
@returns the number of bytes written, or -1 if there was an error
*/
int write (const void* sourceBuffer, int numBytesToWrite);
//==============================================================================
/** Puts this socket into "listener" mode.
When in this mode, your thread can call waitForNextConnection() repeatedly,
which will spawn new sockets for each new connection, so that these can
be handled in parallel by other threads.
@param portNumber the port number to listen on
@param localHostName the interface address to listen on - pass an empty
string to listen on all addresses
@returns true if it manages to open the socket successfully
@see waitForNextConnection
*/
bool createListener (int portNumber, const String& localHostName = String());
/** When in "listener" mode, this waits for a connection and spawns it as a new
socket.
The object that gets returned will be owned by the caller.
This method can only be called after using createListener().
@see createListener
*/
StreamingSocket* waitForNextConnection() const;
private:
//==============================================================================
SocketOptions options;
String hostName;
std::atomic<int> portNumber { 0 }, handle { -1 };
std::atomic<bool> connected { false }, isListener { false };
mutable CriticalSection readLock;
StreamingSocket (const String& hostname, int portNumber, int handle, const SocketOptions& options);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket)
};
//==============================================================================
/**
A wrapper for a datagram (UDP) socket.
This allows low-level use of sockets; for an easier-to-use messaging layer on top of
sockets, you could also try the InterprocessConnection class.
@see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
@tags{Core}
*/
class JUCE_API DatagramSocket final
{
public:
using Options = SocketOptions;
//==============================================================================
/** Creates a datagram socket and allows specifying options related to the
configuration of the underlying socket.
You first need to bind this socket to a port with bindToPort if you intend to read
from this socket.
If enableBroadcasting is true, the socket will be allowed to send broadcast messages
(may require extra privileges on linux)
*/
DatagramSocket (bool enableBroadcasting, const SocketOptions& optionsIn);
/** Creates a datagram socket.
You first need to bind this socket to a port with bindToPort if you intend to read
from this socket.
If enableBroadcasting is true, the socket will be allowed to send broadcast messages
(may require extra privileges on linux)
*/
explicit DatagramSocket (bool enableBroadcasting)
: DatagramSocket (enableBroadcasting, SocketOptions{})
{}
/** Creates a datagram socket.
You first need to bind this socket to a port with bindToPort if you intend to read
from this socket.
This constructor creates a socket that does not allow sending broadcast messages.
*/
DatagramSocket() : DatagramSocket (false)
{}
/** Destructor. */
~DatagramSocket();
//==============================================================================
/** Binds the socket to the specified local port.
The localPortNumber is the port on which to bind this socket. If this value is 0,
the port number is assigned by the operating system.
@returns true on success; false may indicate that another socket is already bound
on the same port
*/
bool bindToPort (int localPortNumber);
/** Binds the socket to the specified local port and local address.
If localAddress is not an empty string then the socket will be bound to localAddress
as well. This is useful if you would like to bind your socket to a specific network
adapter. Note that localAddress must be an IP address assigned to one of your
network address otherwise this function will fail.
@returns true on success; false may indicate that another socket is already bound
on the same port
@see bindToPort (int localPortNumber), IPAddress::getAllAddresses
*/
bool bindToPort (int localPortNumber, const String& localAddress);
/** Returns the local port number to which this socket is currently bound.
This is useful if you need to know to which port the OS has actually bound your
socket when bindToPort was called with zero.
@returns -1 if the socket didn't bind to any port yet or an error occurred
*/
int getBoundPort() const noexcept;
/** Returns the OS's socket handle that's currently open. */
int getRawSocketHandle() const noexcept { return handle; }
//==============================================================================
/** Waits until the socket is ready for reading or writing.
If readyForReading is true, it will wait until the socket is ready for
reading; if false, it will wait until it's ready for writing.
If the timeout is < 0, it will wait forever, or else will give up after
the specified time.
@returns 1 if the socket is ready on return, 0 if it times-out before the
socket becomes ready, or -1 if an error occurs
*/
int waitUntilReady (bool readyForReading, int timeoutMsecs);
/** Reads bytes from the socket.
If blockUntilSpecifiedAmountHasArrived is true, the method will block until
maxBytesToRead bytes have been read, (or until an error occurs). If this
flag is false, the method will return as much data as is currently available
without blocking.
@returns the number of bytes read, or -1 if there was an error
@see waitUntilReady
*/
int read (void* destBuffer, int maxBytesToRead,
bool blockUntilSpecifiedAmountHasArrived);
/** Reads bytes from the socket and return the IP address of the sender.
If blockUntilSpecifiedAmountHasArrived is true, the method will block until
maxBytesToRead bytes have been read, (or until an error occurs). If this
flag is false, the method will return as much data as is currently available
without blocking.
@returns the number of bytes read, or -1 if there was an error. On a successful
result, the senderIPAddress value will be set to the IP of the sender
@see waitUntilReady
*/
int read (void* destBuffer, int maxBytesToRead,
bool blockUntilSpecifiedAmountHasArrived,
String& senderIPAddress, int& senderPortNumber);
/** Writes bytes to the socket from a buffer.
Note that this method will block unless you have checked the socket is ready
for writing before calling it (see the waitUntilReady() method).
@returns the number of bytes written, or -1 if there was an error
*/
int write (const String& remoteHostname, int remotePortNumber,
const void* sourceBuffer, int numBytesToWrite);
/** Closes the underlying socket object.
Closes the underlying socket object and aborts any read or write operations.
Note that all other methods will return an error after this call and the object
cannot be re-used.
This method is useful if another thread is blocking in a read/write call and you
would like to abort the read/write thread. Simply deleting the socket
object without calling shutdown may cause a race-condition where the read/write
returns just before the socket is deleted and the subsequent read/write would
try to read from an invalid pointer. By calling shutdown first, the socket
object remains valid but all current and subsequent calls to read/write will
return immediately.
*/
void shutdown();
//==============================================================================
/** Join a multicast group.
@returns true if it succeeds
*/
bool joinMulticast (const String& multicastIPAddress);
/** Leave a multicast group.
@returns true if it succeeds
*/
bool leaveMulticast (const String& multicastIPAddress);
/** Enables or disables multicast loopback.
@returns true if it succeeds
*/
bool setMulticastLoopbackEnabled (bool enableLoopback);
//==============================================================================
/** Allow other applications to re-use the port.
Allow any other application currently running to bind to the same port.
Do not use this if your socket handles sensitive data as it could be
read by any, possibly malicious, third-party apps.
@returns true on success
*/
bool setEnablePortReuse (bool enabled);
private:
//==============================================================================
SocketOptions options;
std::atomic<int> handle { -1 };
bool isBound = false;
String lastBindAddress, lastServerHost;
int lastServerPort = -1;
void* lastServerAddress = nullptr;
mutable CriticalSection readLock;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket)
};
} // namespace juce
File diff suppressed because it is too large Load Diff
+762
View File
@@ -0,0 +1,762 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
class WebInputStream;
//==============================================================================
/**
Represents a URL and has a bunch of useful functions to manipulate it.
This class can be used to launch URLs in browsers, and also to create
InputStreams that can read from remote HTTP or FTP sources.
@tags{Core}
*/
class JUCE_API URL
{
public:
//==============================================================================
/** Creates an empty URL. */
URL();
/** Creates a URL from a string.
This will parse any embedded parameters after a '?' character and store them
in the list (see getParameterNames etc). If you don't want this to happen, you
can use createWithoutParsing().
*/
URL (const String& url);
/** Creates URL referring to a local file on your disk using the file:// scheme. */
explicit URL (File localFile);
/** Compares two URLs.
All aspects of the URLs must be identical for them to match, including any parameters,
upload files, etc.
*/
bool operator== (const URL&) const;
bool operator!= (const URL&) const;
//==============================================================================
/** Returns a string version of the URL.
@param includeGetParameters if this is true and any parameters have been set
with the withParameter() method, then the string
will have these appended on the end and URL-encoded.
@see getQueryString
*/
String toString (bool includeGetParameters) const;
/** Returns true if the URL is an empty string. */
bool isEmpty() const noexcept;
/** True if it seems to be valid. */
bool isWellFormed() const;
/** Returns just the domain part of the URL.
e.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
*/
String getDomain() const;
/** Returns the path part of the URL.
e.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
@param includeGetParameters if this is true and any parameters have been set
with the withParameter() method, then the string
will have these appended on the end and URL-encoded.
@see getQueryString
*/
String getSubPath (bool includeGetParameters = false) const;
/** If any parameters are set, returns these URL-encoded, including the "?"
prefix.
*/
String getQueryString() const;
/** If any anchor is set, returns URL-encoded anchor, including the "#"
prefix.
*/
String getAnchorString() const;
/** Returns the scheme of the URL.
e.g. for "http://www.xyz.com/foobar", this will return "http" (it won't
include the colon).
*/
String getScheme() const;
/** Returns true if this URL refers to a local file. */
bool isLocalFile() const;
/** Returns the file path of the local file to which this URL refers to.
If the URL does not represent a local file URL (i.e. the URL's scheme is not 'file')
then this method will assert.
This method also supports converting Android's content:// URLs to local file paths.
@see isLocalFile
*/
File getLocalFile() const;
/** Returns the file name.
For all but Android's content:// scheme, it will simply return the last segment of
the URL, e.g. for "http://www.xyz.com/foo/bar.txt", this will return "bar.txt".
For Android's content:// scheme, it will attempt to resolve the filename
located under the URL.
*/
String getFileName() const;
/** Attempts to read a port number from the URL.
@returns the port number, or 0 if none is explicitly specified.
*/
int getPort() const;
/** Returns the origin of a resource reachable on this URL.
In the context of cross-origin resource sharing (CORS) a script downloaded from this URL
would only be allowed to reach resources from the returned origin.
*/
String getOrigin() const;
/** Returns a new version of this URL with a different domain and path.
e.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
"abc.com/zzz", it'll return "http://abc.com/zzz?x=1".
@see withNewSubPath
*/
[[nodiscard]] URL withNewDomainAndPath (const String& newFullPath) const;
/** Returns a new version of this URL with a different sub-path.
e.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
"bar", it'll return "http://www.xyz.com/bar?x=1".
@see withNewDomainAndPath
*/
[[nodiscard]] URL withNewSubPath (const String& newPath) const;
/** Attempts to return a URL which is the parent folder containing this URL.
If there isn't a parent, this method will just return a copy of this URL.
*/
URL getParentURL() const;
/** Returns a new URL that refers to a sub-path relative to this one.
e.g. if the URL is "http://www.xyz.com/foo" and you call this with "bar",
it'll return "http://www.xyz.com/foo/bar".
Note that there's no way for this method to know whether the original URL is
a file or directory, so it's up to you to make sure it's a directory. It also
won't attempt to be smart about the content of the childPath string, so if this
string is an absolute URL, it'll still just get bolted onto the end of the path.
@see File::getChildFile
*/
URL getChildURL (const String& subPath) const;
//==============================================================================
/** Returns a copy of this URL, with a GET or POST parameter added to the end.
Any control characters in the value will be URL-encoded.
e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
would produce a new url whose `toString (true)` method would return
"www.fish.com?amount=some+fish".
@see getParameterNames, getParameterValues
*/
[[nodiscard]] URL withParameter (const String& parameterName,
const String& parameterValue) const;
/** Returns a copy of this URL, with a set of GET or POST parameters added.
This is a convenience method, equivalent to calling withParameter for each value.
@see withParameter
*/
[[nodiscard]] URL withParameters (const StringPairArray& parametersToAdd) const;
/** Returns a copy of this URL, with an anchor added to the end of the URL.
*/
[[nodiscard]] URL withAnchor (const String& anchor) const;
/** Returns a copy of this URL, with a file-upload type parameter added to it.
When performing a POST where one of your parameters is a binary file, this
lets you specify the file.
Note that the filename is stored, but the file itself won't actually be read
until this URL is later used to create a network input stream. If you want to
upload data from memory, use withDataToUpload().
@see withDataToUpload
*/
[[nodiscard]] URL withFileToUpload (const String& parameterName,
const File& fileToUpload,
const String& mimeType) const;
/** Returns a copy of this URL, with a file-upload type parameter added to it.
When performing a POST where one of your parameters is a binary file, this
lets you specify the file content.
Note that the filename parameter should not be a full path, it's just the
last part of the filename.
@see withFileToUpload
*/
[[nodiscard]] URL withDataToUpload (const String& parameterName,
const String& filename,
const MemoryBlock& fileContentToUpload,
const String& mimeType) const;
/** Returns an array of the names of all the URL's parameters.
e.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
contain two items: "type" and "amount".
You can call getParameterValues() to get the corresponding value of each
parameter. Note that the list can contain multiple parameters with the same name.
@see getParameterValues, withParameter
*/
const StringArray& getParameterNames() const noexcept { return parameterNames; }
/** Returns an array of the values of all the URL's parameters.
e.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
contain two items: "haddock" and "some fish".
The values returned will have been cleaned up to remove any escape characters.
You can call getParameterNames() to get the corresponding name of each
parameter. Note that the list can contain multiple parameters with the same name.
@see getParameterNames, withParameter
*/
const StringArray& getParameterValues() const noexcept { return parameterValues; }
/** Returns a copy of this URL, with a block of data to send as the POST data.
If the URL already contains some POST data, this will replace it, rather
than being appended to it.
If no HTTP command is set when calling createInputStream() to read from
this URL and some data has been set, it will do a POST request.
*/
[[nodiscard]] URL withPOSTData (const String& postData) const;
/** Returns a copy of this URL, with a block of data to send as the POST data.
If the URL already contains some POST data, this will replace it, rather
than being appended to it.
If no HTTP command is set when calling createInputStream() to read from
this URL and some data has been set, it will do a POST request.
*/
[[nodiscard]] URL withPOSTData (const MemoryBlock& postData) const;
/** Returns the data that was set using withPOSTData(). */
String getPostData() const { return postData.toString(); }
/** Returns the data that was set using withPOSTData() as a MemoryBlock. */
const MemoryBlock& getPostDataAsMemoryBlock() const noexcept { return postData; }
//==============================================================================
/** Tries to launch the system's default browser to open the URL.
@returns true if this seems to have worked.
*/
bool launchInDefaultBrowser() const;
//==============================================================================
/** Takes a guess as to whether a string might be a valid website address.
This isn't foolproof!
*/
static bool isProbablyAWebsiteURL (const String& possibleURL);
/** Takes a guess as to whether a string might be a valid email address.
This isn't foolproof!
*/
static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
//==============================================================================
enum class ParameterHandling
{
inAddress,
inPostData
};
/** Class used to create a set of options to pass to the createInputStream() method.
You can chain together a series of calls to this class's methods to create
a set of whatever options you want to specify, e.g.
@code
if (auto inputStream = URL ("http://www.xyz.com/foobar")
.createInputStream (URL::InputStreamOptions (URL::ParameterHandling::inAddress)
.withConnectionTimeoutMs (1000)
.withNumRedirectsToFollow (0)))
{
...
}
@endcode
*/
class JUCE_API InputStreamOptions
{
public:
/** Constructor.
If parameterHandling is ParameterHandling::inPostData, any URL parameters
that have been set will be transferred via the request body data. Otherwise
the parameters will be added to the URL address.
*/
explicit InputStreamOptions (ParameterHandling parameterHandling);
//==============================================================================
/** A callback function to keep track of the operation's progress.
This can be useful for lengthy POST operations, so that you can provide user feedback.
*/
[[nodiscard]] InputStreamOptions withProgressCallback (std::function<bool (int bytesSent, int totalBytes)> progressCallback) const;
/** A string that will be appended onto the headers that are used for the request.
It must be a valid set of HTML header directives, separated by newlines.
*/
[[nodiscard]] InputStreamOptions withExtraHeaders (const String& extraHeaders) const;
/** Specifies a timeout for the request in milliseconds.
If 0, this will use whatever default setting the OS chooses. If a negative
number, it will be infinite.
*/
[[nodiscard]] InputStreamOptions withConnectionTimeoutMs (int connectionTimeoutMs) const;
/** If this is non-null, all the (key, value) pairs received as headers
in the response will be stored in this array.
*/
[[nodiscard]] InputStreamOptions withResponseHeaders (StringPairArray* responseHeaders) const;
/** If this is non-null, it will get set to the http status code, if one
is known, or 0 if a code isn't available.
*/
[[nodiscard]] InputStreamOptions withStatusCode (int* statusCode) const;
/** Specifies the number of redirects that will be followed before returning a response.
N.B. This will be ignored on Android which follows up to 5 redirects.
*/
[[nodiscard]] InputStreamOptions withNumRedirectsToFollow (int numRedirectsToFollow) const;
/** Specifies which HTTP request command to use.
If this is not set, then the command will be POST if parameterHandling is
set to ParameterHandling::inPostData or if any POST data has been specified
via withPOSTData(), withFileToUpload(), or withDataToUpload(). Otherwise it
will be GET.
*/
[[nodiscard]] InputStreamOptions withHttpRequestCmd (const String& httpRequestCmd) const;
//==============================================================================
ParameterHandling getParameterHandling() const noexcept { return parameterHandling; }
std::function<bool (int, int)> getProgressCallback() const noexcept { return progressCallback; }
String getExtraHeaders() const noexcept { return extraHeaders; }
int getConnectionTimeoutMs() const noexcept { return connectionTimeOutMs; }
StringPairArray* getResponseHeaders() const noexcept { return responseHeaders; }
int* getStatusCode() const noexcept { return statusCode; }
int getNumRedirectsToFollow() const noexcept { return numRedirectsToFollow; }
String getHttpRequestCmd() const noexcept { return httpRequestCmd; }
private:
//==============================================================================
const ParameterHandling parameterHandling;
std::function<bool (int, int)> progressCallback = nullptr;
String extraHeaders;
int connectionTimeOutMs = 0;
StringPairArray* responseHeaders = nullptr;
int* statusCode = nullptr;
int numRedirectsToFollow = 5;
String httpRequestCmd;
};
/** Attempts to open a stream that can read from this URL.
Note that this method will block until the first byte of data has been received or an
error has occurred.
Note that on some platforms (Android, for example) it's not permitted to do any network
action from the message thread, so you must only call it from a background thread.
Unless the URL represents a local file, this method returns an instance of a
WebInputStream. You can use dynamic_cast to cast the return value to a WebInputStream
which allows you more fine-grained control of the transfer process.
If the URL represents a local file, then this method simply returns a FileInputStream.
@param options a set of options that will be used when opening the stream.
@returns a valid input stream, or nullptr if there was an error trying to open it.
*/
std::unique_ptr<InputStream> createInputStream (const InputStreamOptions& options) const;
/** Attempts to open an output stream to a URL for writing
This method can only be used for certain scheme types such as local files
and content:// URIs on Android.
*/
std::unique_ptr<OutputStream> createOutputStream() const;
//==============================================================================
class DownloadTask;
/** Used to receive callbacks for download progress. */
struct JUCE_API DownloadTaskListener
{
virtual ~DownloadTaskListener() = default;
/** Called when the download has finished. Be aware that this callback may
come on an arbitrary thread.
*/
virtual void finished (DownloadTask* task, bool success) = 0;
/** Called periodically by the OS to indicate download progress.
Beware that this callback may come on an arbitrary thread.
*/
virtual void progress (DownloadTask* task, int64 bytesDownloaded, int64 totalLength);
};
/** Holds options that can be specified when starting a new download
with downloadToFile().
*/
class DownloadTaskOptions
{
public:
String extraHeaders;
String sharedContainer;
DownloadTaskListener* listener = nullptr;
bool usePost = false;
/** Specifies headers to add to the request. */
[[nodiscard]] auto withExtraHeaders (String value) const { return with (&DownloadTaskOptions::extraHeaders, std::move (value)); }
/** On iOS, specifies the container where the downloaded file will be stored.
If you initiate a download task from inside an app extension on iOS,
you must supply this option.
This is currently unused on other platforms.
*/
[[nodiscard]] auto withSharedContainer (String value) const { return with (&DownloadTaskOptions::sharedContainer, std::move (value)); }
/** Specifies an observer for the download task. */
[[nodiscard]] auto withListener (DownloadTaskListener* value) const { return with (&DownloadTaskOptions::listener, std::move (value)); }
/** Specifies whether a post command should be used. */
[[nodiscard]] auto withUsePost (bool value) const { return with (&DownloadTaskOptions::usePost, value); }
private:
template <typename Member, typename Value>
[[nodiscard]] DownloadTaskOptions with (Member&& member, Value&& value) const
{
auto copy = *this;
copy.*member = std::forward<Value> (value);
return copy;
}
};
/** Represents a download task.
Returned by downloadToFile() to allow querying and controlling the download task.
*/
class JUCE_API DownloadTask
{
public:
using Listener = DownloadTaskListener;
/** Releases the resources of the download task, unregisters the listener
and cancels the download if necessary.
*/
virtual ~DownloadTask();
/** Returns the total length of the download task.
This may return -1 if the length was not returned by the server.
*/
int64 getTotalLength() const { return contentLength; }
/** Returns the number of bytes that have been downloaded so far. */
int64 getLengthDownloaded() const { return downloaded; }
/** Returns true if the download finished or there was an error. */
bool isFinished() const { return finished; }
/** Returns the status code of the server's response.
This will only be valid after the download has finished.
@see isFinished
*/
int statusCode() const { return httpCode; }
/** Returns true if there was an error. */
inline bool hadError() const { return error; }
/** Returns the target file location that was provided in URL::downloadToFile. */
File getTargetLocation() const { return targetLocation; }
protected:
int64 contentLength = -1, downloaded = 0;
bool finished = false, error = false;
int httpCode = -1;
File targetLocation;
DownloadTask();
private:
friend class URL;
static std::unique_ptr<DownloadTask> createFallbackDownloader (const URL&, const File&, const DownloadTaskOptions&);
public:
#if JUCE_IOS
/** internal **/
static void juce_iosURLSessionNotify (const String&);
#endif
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DownloadTask)
};
/** This function is replaced by a new overload accepting a DownloadTaskOptions argument. */
[[deprecated ("Use the overload with a DownloadTaskOptions argument instead")]]
std::unique_ptr<DownloadTask> downloadToFile (const File& targetLocation,
String extraHeaders = String(),
DownloadTaskListener* listener = nullptr,
bool usePostCommand = false);
/** Download the URL to a file.
This method attempts to download the URL to a given file location.
Using this method to download files on mobile is less flexible but more reliable
than using createInputStream or WebInputStreams as it will attempt to download the file
using a native OS background network task. Such tasks automatically deal with
network re-connections and continuing your download while your app is suspended.
*/
std::unique_ptr<DownloadTask> downloadToFile (const File& targetLocation,
const DownloadTaskOptions& options);
//==============================================================================
/** Tries to download the entire contents of this URL into a binary data block.
If it succeeds, this will return true and append the data it read onto the end
of the memory block.
Note that on some platforms (Android, for example) it's not permitted to do any network
action from the message thread, so you must only call it from a background thread.
@param destData the memory block to append the new data to.
@param usePostCommand whether to use a POST command to get the data (uses
a GET command if this is false).
@see readEntireTextStream, readEntireXmlStream
*/
bool readEntireBinaryStream (MemoryBlock& destData,
bool usePostCommand = false) const;
/** Tries to download the entire contents of this URL as a string.
If it fails, this will return an empty string, otherwise it will return the
contents of the downloaded file. If you need to distinguish between a read
operation that fails and one that returns an empty string, you'll need to use
a different method, such as readEntireBinaryStream().
Note that on some platforms (Android, for example) it's not permitted to do any network
action from the message thread, so you must only call it from a background thread.
@param usePostCommand whether to use a POST command to get the data (uses
a GET command if this is false).
@see readEntireBinaryStream, readEntireXmlStream
*/
String readEntireTextStream (bool usePostCommand = false) const;
/** Tries to download the entire contents of this URL and parse it as XML.
If it fails, or if the text that it reads can't be parsed as XML, this will
return nullptr.
Note that on some platforms (Android, for example) it's not permitted to do any network
action from the message thread, so you must only call it from a background thread.
@param usePostCommand whether to use a POST command to get the data (uses
a GET command if this is false).
@see readEntireBinaryStream, readEntireTextStream
*/
std::unique_ptr<XmlElement> readEntireXmlStream (bool usePostCommand = false) const;
//==============================================================================
/** Adds escape sequences to a string to encode any characters that aren't
legal in a URL.
E.g. any spaces will be replaced with "%20".
This is the opposite of removeEscapeChars().
@param stringToAddEscapeCharsTo the string to escape.
@param isParameter if true then the string is going to be
used as a parameter, so it also encodes
'$' and ',' (which would otherwise be
legal in a URL.
@param roundBracketsAreLegal technically round brackets are ok in URLs,
however, some servers (like AWS) also want
round brackets to be escaped.
@see removeEscapeChars
*/
static String addEscapeChars (const String& stringToAddEscapeCharsTo,
bool isParameter,
bool roundBracketsAreLegal = true);
/** Replaces any escape character sequences in a string with their original
character codes.
E.g. any instances of "%20" will be replaced by a space.
This is the opposite of addEscapeChars().
@see addEscapeChars
*/
static String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
/** Returns a URL without attempting to remove any embedded parameters from the string.
This may be necessary if you need to create a request that involves both POST
parameters and parameters which are embedded in the URL address itself.
*/
static URL createWithoutParsing (const String& url);
//==============================================================================
/** @cond */
using OpenStreamProgressCallback = bool (void* context, int bytesSent, int totalBytes);
/** This method has been deprecated.
@see InputStreamOptions
*/
[[deprecated ("New code should use the method which takes an InputStreamOptions argument instead.")]]
std::unique_ptr<InputStream> createInputStream (bool doPostLikeRequest,
OpenStreamProgressCallback* progressCallback = nullptr,
void* progressCallbackContext = nullptr,
String extraHeaders = {},
int connectionTimeOutMs = 0,
StringPairArray* responseHeaders = nullptr,
int* statusCode = nullptr,
int numRedirectsToFollow = 5,
String httpRequestCmd = {}) const;
/** @endcond */
private:
//==============================================================================
#if JUCE_IOS
struct Bookmark : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<Bookmark>;
Bookmark (void*);
~Bookmark();
void* data;
};
Bookmark::Ptr bookmark;
friend void setURLBookmark (URL&, void*);
friend void* getURLBookmark (URL&);
#endif
//==============================================================================
struct Upload : public ReferenceCountedObject
{
Upload (const String&, const String&, const String&, const File&, MemoryBlock*);
String parameterName, filename, mimeType;
File file;
std::unique_ptr<MemoryBlock> data;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Upload)
};
//==============================================================================
friend class WebInputStream;
URL (const String&, int);
void init();
void addParameter (const String&, const String&);
bool hasBodyDataToSend() const;
void createHeadersAndPostData (String&, MemoryBlock&, bool) const;
URL withUpload (Upload*) const;
static ParameterHandling toHandling (bool);
static File fileFromFileSchemeURL (const URL&);
String getDomainInternal (bool) const;
//==============================================================================
String url;
MemoryBlock postData;
StringArray parameterNames, parameterValues;
String anchor;
ReferenceCountedArray<Upload> filesToUpload;
//==============================================================================
JUCE_LEAK_DETECTOR (URL)
};
} // namespace juce
@@ -0,0 +1,115 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
WebInputStream::WebInputStream (const URL& url, const bool usePost)
: pimpl (std::make_unique<Pimpl> (*this, url, usePost))
{
}
WebInputStream::~WebInputStream()
{
}
WebInputStream& WebInputStream::withExtraHeaders (const String& extra) { pimpl->withExtraHeaders (extra); return *this; }
WebInputStream& WebInputStream::withCustomRequestCommand (const String& cmd) { pimpl->withCustomRequestCommand (cmd); return *this; }
WebInputStream& WebInputStream::withConnectionTimeout (int t) { pimpl->withConnectionTimeout (t); return *this; }
WebInputStream& WebInputStream::withNumRedirectsToFollow (int num) { pimpl->withNumRedirectsToFollow (num); return *this; }
StringPairArray WebInputStream::getRequestHeaders() const { return pimpl->getRequestHeaders(); }
StringPairArray WebInputStream::getResponseHeaders() { connect (nullptr); return pimpl->getResponseHeaders(); }
bool WebInputStream::isError() const { return pimpl->isError(); }
void WebInputStream::cancel() { pimpl->cancel(); }
bool WebInputStream::isExhausted() { return pimpl->isExhausted(); }
int64 WebInputStream::getPosition() { return pimpl->getPosition(); }
int64 WebInputStream::getTotalLength() { connect (nullptr); return pimpl->getTotalLength(); }
int WebInputStream::read (void* buffer, int bytes) { connect (nullptr); return pimpl->read (buffer, bytes); }
bool WebInputStream::setPosition (int64 pos) { return pimpl->setPosition (pos); }
int WebInputStream::getStatusCode() { connect (nullptr); return pimpl->getStatusCode(); }
bool WebInputStream::connect (Listener* listener)
{
if (hasCalledConnect)
return ! isError();
hasCalledConnect = true;
return pimpl->connect (listener);
}
StringPairArray WebInputStream::parseHttpHeaders (const String& headerData)
{
StringPairArray headerPairs;
auto headerLines = StringArray::fromLines (headerData);
for (const auto& headersEntry : headerLines)
{
if (headersEntry.isNotEmpty())
{
const auto key = headersEntry.upToFirstOccurrenceOf (": ", false, false);
auto value = [&headersEntry, &headerPairs, &key]
{
const auto currentValue = headersEntry.fromFirstOccurrenceOf (": ", false, false);
const auto previousValue = headerPairs [key];
if (previousValue.isNotEmpty())
return previousValue + "," + currentValue;
return currentValue;
}();
headerPairs.set (key, value);
}
}
return headerPairs;
}
void WebInputStream::createHeadersAndPostData (const URL& aURL,
String& headers,
MemoryBlock& data,
bool addParametersToBody)
{
aURL.createHeadersAndPostData (headers, data, addParametersToBody);
}
bool WebInputStream::Listener::postDataSendProgress ([[maybe_unused]] WebInputStream& request,
[[maybe_unused]] int bytesSent,
[[maybe_unused]] int totalBytes)
{
return true;
}
} // namespace juce
@@ -0,0 +1,245 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
An InputStream which can be used to read from a given URL.
@tags{Core}
*/
class JUCE_API WebInputStream : public InputStream
{
public:
/** Creates a new WebInputStream which can be used to read from a URL.
@param url the URL that should be retrieved. This parameter may also contain
POST data and/or parameters.
@param addParametersToRequestBody specifies whether any URL parameters that have
been set will be transferred via the request body data or added
to the URL address. This will also determine whether a POST or GET
command will be used if a custom command is not set.
*/
WebInputStream (const URL& url, bool addParametersToRequestBody);
/** Destructor. */
~WebInputStream() override;
/** Add extra headers to the HTTP request.
Returns a reference to itself so that several methods can be chained.
@param extraHeaders this string is appended onto the headers that are used for
the request. It must therefore be a valid set of HTML
header directives, separated by newlines.
*/
WebInputStream& withExtraHeaders (const String& extraHeaders);
/** Override the HTTP command that is sent.
Returns a reference to itself so that several methods can be chained.
Note that this command will not change the way parameters are sent. This
must be specified in the constructor.
@param customRequestCommand this string is the custom HTTP request command such
as POST or GET.
*/
WebInputStream& withCustomRequestCommand (const String& customRequestCommand);
/** Specify the connection time-out.
Returns a reference to itself so that several methods can be chained.
@param timeoutInMs the number of milliseconds to wait until the connection
request is aborted.
*/
WebInputStream& withConnectionTimeout (int timeoutInMs);
/** Specify the number of redirects to be followed.
Returns a reference to itself so that several methods can be chained.
@param numRedirects specifies the number of redirects that will be followed
before returning a response (ignored for Android which
follows up to 5 redirects)
*/
WebInputStream& withNumRedirectsToFollow (int numRedirects);
//==============================================================================
/** Used to receive callbacks for POST data send progress.
Pass one of these into the connect() method and its postDataSendProgress()
method will be called periodically with updates on POST data upload progress.
*/
class JUCE_API Listener
{
public:
/** Destructor. */
virtual ~Listener() = default;
/** This method will be called periodically with updates on POST data upload progress.
@param request the original request
@param bytesSent the number of bytes sent so far
@param totalBytes the total number of bytes to send
@returns true to continue or false to cancel the upload
*/
virtual bool postDataSendProgress (WebInputStream& request, int bytesSent, int totalBytes);
};
/** Wait until the first byte is ready for reading.
This method will attempt to connect to the URL given in the constructor
and block until the status code and all response headers have been received or
an error has occurred.
Note that most methods will call connect() internally if they are called without
an established connection. Therefore, it is not necessary to explicitly
call connect unless you would like to use a custom listener.
After a successful call to connect(), getResponseHeaders(), getTotalLength()
and getStatusCode() will all be non-blocking.
@param listener a listener to receive progress callbacks on the status
of a POST data upload.
@see getResponseHeaders, getTotalLength, getStatusCode
*/
bool connect (Listener* listener);
/** Returns true if there was an error during the connection attempt. */
bool isError() const;
/** Will cancel a blocking read and prevent any subsequent connection attempts. */
void cancel();
/** Returns a StringPairArray of the request headers. */
StringPairArray getRequestHeaders() const;
/** Returns a StringPairArray of response headers.
If getResponseHeaders() is called without an established connection, then
getResponseHeaders() will call connect internally and block until connect
returns - either due to a successful connection or a connection
error.
@see connect
*/
StringPairArray getResponseHeaders();
/** Returns the status code returned by the HTTP server
If getStatusCode() is called without an established connection, then
getStatusCode() will call connect internally and block until connect
returns - either due to a successful connection or a connection
error.
@see connect
*/
int getStatusCode();
//==============================================================================
/** Returns the total number of bytes available for reading in this stream.
Note that this is the number of bytes available from the start of the
stream, not from the current position.
If getTotalLength() is called without an established connection, then
getTotalLength() will call connect internally and block until connect
returns - either due to a successful connection or a connection
error.
If the size of the stream isn't actually known, this will return -1.
*/
int64 getTotalLength() override;
/** Reads some data from the stream into a memory buffer.
This method will block until the maxBytesToRead bytes are available.
This method calls connect() internally if the connection hasn't already
been established.
@param destBuffer the destination buffer for the data. This must not be null.
@param maxBytesToRead the maximum number of bytes to read - make sure the
memory block passed in is big enough to contain this
many bytes. This value must not be negative.
@returns the actual number of bytes that were read, which may be less than
maxBytesToRead if the stream is exhausted before it gets that far
*/
int read (void* destBuffer, int maxBytesToRead) override;
/** Returns true if the stream has no more data to read. */
bool isExhausted() override;
/** Returns the offset of the next byte that will be read from the stream.
@see setPosition
*/
int64 getPosition() override;
/** Tries to move the current read position of the stream.
The position is an absolute number of bytes from the stream's start.
For a WebInputStream, this method will fail if wantedPos is smaller
than the current position. If wantedPos is greater than the current
position, then calling setPosition() is the same as calling read(), i.e.
the skipped data will still be downloaded, although skipped bytes will
be discarded immediately.
@returns true if the stream manages to reposition itself correctly
@see getPosition
*/
bool setPosition (int64 wantedPos) override;
private:
static void createHeadersAndPostData (const URL&, String&, MemoryBlock&, bool);
static StringPairArray parseHttpHeaders (const String&);
class Pimpl;
friend class Pimpl;
std::unique_ptr<Pimpl> pimpl;
bool hasCalledConnect = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream)
};
} // namespace juce