set eol-style to native

This commit is contained in:
Guenter Obiltschnig
2006-10-23 16:25:09 +00:00
parent 1ecd4a8a9e
commit 0c24077c43
338 changed files with 49884 additions and 49884 deletions

View File

@@ -1,227 +1,227 @@
//
// DNS.cpp
//
// $Id: //poco/1.2/Net/src/DNS.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: DNS
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DNS.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Environment.h"
#include "Poco/NumberFormatter.h"
using Poco::FastMutex;
using Poco::Environment;
using Poco::NumberFormatter;
using Poco::IOException;
//
// Automatic initialization of Windows networking
//
#if defined(_WIN32)
namespace
{
class NetworkInitializer
{
public:
NetworkInitializer()
{
WORD version = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(version, &data);
}
~NetworkInitializer()
{
WSACleanup();
}
};
static NetworkInitializer networkInitializer;
}
#endif // _WIN32
namespace Poco {
namespace Net {
DNS::DNSCache DNS::_cache;
Poco::FastMutex DNS::_mutex;
const HostEntry& DNS::hostByName(const std::string& hostname)
{
FastMutex::ScopedLock lock(_mutex);
DNSCache::const_iterator it = _cache.find(hostname);
if (it != _cache.end())
{
return it->second;
}
else
{
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
struct addrinfo* pAI;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_CANONNAME;
if (getaddrinfo(hostname.c_str(), NULL, &hints, &pAI) == 0)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(pAI)));
freeaddrinfo(pAI);
return res.first->second;
}
#else
struct hostent* he = gethostbyname(hostname.c_str());
if (he)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(he)));
return res.first->second;
}
#endif
}
error(lastError(), hostname); // will throw an appropriate exception
throw NetException(); // to silence compiler
}
const HostEntry& DNS::hostByAddress(const IPAddress& address)
{
FastMutex::ScopedLock lock(_mutex);
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
SocketAddress sa(address, 0);
static char fqname[1024];
if (getnameinfo(sa.addr(), sa.length(), fqname, sizeof(fqname), NULL, 0, 0) == 0)
{
DNSCache::const_iterator it = _cache.find(std::string(fqname));
if (it != _cache.end())
{
return it->second;
}
else
{
struct addrinfo* pAI;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
if (getaddrinfo(fqname, NULL, &hints, &pAI) == 0)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(std::string(fqname), HostEntry(pAI)));
freeaddrinfo(pAI);
return res.first->second;
}
}
}
#else
struct hostent* he = gethostbyaddr(reinterpret_cast<const char*>(address.addr()), address.length(), address.af());
if (he)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(std::string(he->h_name), HostEntry(he)));
return res.first->second;
}
#endif
error(lastError(), address.toString()); // will throw an appropriate exception
throw NetException(); // to silence compiler
}
const HostEntry& DNS::resolve(const std::string& address)
{
IPAddress ip;
if (IPAddress::tryParse(address, ip))
return hostByAddress(ip);
else
return hostByName(address);
}
IPAddress DNS::resolveOne(const std::string& address)
{
const HostEntry& entry = resolve(address);
if (!entry.addresses().empty())
return entry.addresses()[0];
else
throw NoAddressFoundException(address);
}
const HostEntry& DNS::thisHost()
{
return hostByName(Environment::nodeName());
}
void DNS::flushCache()
{
FastMutex::ScopedLock lock(_mutex);
_cache.clear();
}
int DNS::lastError()
{
#if defined(_WIN32)
return GetLastError();
#else
return h_errno;
#endif
}
void DNS::error(int code, const std::string& arg)
{
switch (code)
{
case POCO_ESYSNOTREADY:
throw NetException("Net subsystem not ready");
case POCO_ENOTINIT:
throw NetException("Net subsystem not initialized");
case POCO_HOST_NOT_FOUND:
throw HostNotFoundException(arg);
case POCO_TRY_AGAIN:
throw DNSException("Temporary DNS error while resolving", arg);
case POCO_NO_RECOVERY:
throw DNSException("Non recoverable DNS error while resolving", arg);
case POCO_NO_DATA:
throw NoAddressFoundException(arg);
default:
throw IOException(NumberFormatter::format(code));
}
}
} } // namespace Poco::Net
//
// DNS.cpp
//
// $Id: //poco/1.2/Net/src/DNS.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: DNS
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DNS.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Environment.h"
#include "Poco/NumberFormatter.h"
using Poco::FastMutex;
using Poco::Environment;
using Poco::NumberFormatter;
using Poco::IOException;
//
// Automatic initialization of Windows networking
//
#if defined(_WIN32)
namespace
{
class NetworkInitializer
{
public:
NetworkInitializer()
{
WORD version = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(version, &data);
}
~NetworkInitializer()
{
WSACleanup();
}
};
static NetworkInitializer networkInitializer;
}
#endif // _WIN32
namespace Poco {
namespace Net {
DNS::DNSCache DNS::_cache;
Poco::FastMutex DNS::_mutex;
const HostEntry& DNS::hostByName(const std::string& hostname)
{
FastMutex::ScopedLock lock(_mutex);
DNSCache::const_iterator it = _cache.find(hostname);
if (it != _cache.end())
{
return it->second;
}
else
{
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
struct addrinfo* pAI;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_CANONNAME;
if (getaddrinfo(hostname.c_str(), NULL, &hints, &pAI) == 0)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(pAI)));
freeaddrinfo(pAI);
return res.first->second;
}
#else
struct hostent* he = gethostbyname(hostname.c_str());
if (he)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(he)));
return res.first->second;
}
#endif
}
error(lastError(), hostname); // will throw an appropriate exception
throw NetException(); // to silence compiler
}
const HostEntry& DNS::hostByAddress(const IPAddress& address)
{
FastMutex::ScopedLock lock(_mutex);
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
SocketAddress sa(address, 0);
static char fqname[1024];
if (getnameinfo(sa.addr(), sa.length(), fqname, sizeof(fqname), NULL, 0, 0) == 0)
{
DNSCache::const_iterator it = _cache.find(std::string(fqname));
if (it != _cache.end())
{
return it->second;
}
else
{
struct addrinfo* pAI;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
if (getaddrinfo(fqname, NULL, &hints, &pAI) == 0)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(std::string(fqname), HostEntry(pAI)));
freeaddrinfo(pAI);
return res.first->second;
}
}
}
#else
struct hostent* he = gethostbyaddr(reinterpret_cast<const char*>(address.addr()), address.length(), address.af());
if (he)
{
std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(std::string(he->h_name), HostEntry(he)));
return res.first->second;
}
#endif
error(lastError(), address.toString()); // will throw an appropriate exception
throw NetException(); // to silence compiler
}
const HostEntry& DNS::resolve(const std::string& address)
{
IPAddress ip;
if (IPAddress::tryParse(address, ip))
return hostByAddress(ip);
else
return hostByName(address);
}
IPAddress DNS::resolveOne(const std::string& address)
{
const HostEntry& entry = resolve(address);
if (!entry.addresses().empty())
return entry.addresses()[0];
else
throw NoAddressFoundException(address);
}
const HostEntry& DNS::thisHost()
{
return hostByName(Environment::nodeName());
}
void DNS::flushCache()
{
FastMutex::ScopedLock lock(_mutex);
_cache.clear();
}
int DNS::lastError()
{
#if defined(_WIN32)
return GetLastError();
#else
return h_errno;
#endif
}
void DNS::error(int code, const std::string& arg)
{
switch (code)
{
case POCO_ESYSNOTREADY:
throw NetException("Net subsystem not ready");
case POCO_ENOTINIT:
throw NetException("Net subsystem not initialized");
case POCO_HOST_NOT_FOUND:
throw HostNotFoundException(arg);
case POCO_TRY_AGAIN:
throw DNSException("Temporary DNS error while resolving", arg);
case POCO_NO_RECOVERY:
throw DNSException("Non recoverable DNS error while resolving", arg);
case POCO_NO_DATA:
throw NoAddressFoundException(arg);
default:
throw IOException(NumberFormatter::format(code));
}
}
} } // namespace Poco::Net

View File

@@ -1,130 +1,130 @@
//
// DatagramSocket.cpp
//
// $Id: //poco/1.2/Net/src/DatagramSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DatagramSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DatagramSocket.h"
#include "Poco/Net/DatagramSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
DatagramSocket::DatagramSocket(): Socket(new DatagramSocketImpl)
{
}
DatagramSocket::DatagramSocket(IPAddress::Family family): Socket(new DatagramSocketImpl(family))
{
}
DatagramSocket::DatagramSocket(const SocketAddress& address, bool reuseAddress): Socket(new DatagramSocketImpl)
{
bind(address, reuseAddress);
}
DatagramSocket::DatagramSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<DatagramSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
DatagramSocket::DatagramSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<DatagramSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
DatagramSocket::~DatagramSocket()
{
}
DatagramSocket& DatagramSocket::operator = (const Socket& socket)
{
if (dynamic_cast<DatagramSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void DatagramSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void DatagramSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
int DatagramSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int DatagramSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
int DatagramSocket::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{
return impl()->sendTo(buffer, length, address, flags);
}
int DatagramSocket::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
return impl()->receiveFrom(buffer, length, address, flags);
}
} } // namespace Poco::Net
//
// DatagramSocket.cpp
//
// $Id: //poco/1.2/Net/src/DatagramSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DatagramSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DatagramSocket.h"
#include "Poco/Net/DatagramSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
DatagramSocket::DatagramSocket(): Socket(new DatagramSocketImpl)
{
}
DatagramSocket::DatagramSocket(IPAddress::Family family): Socket(new DatagramSocketImpl(family))
{
}
DatagramSocket::DatagramSocket(const SocketAddress& address, bool reuseAddress): Socket(new DatagramSocketImpl)
{
bind(address, reuseAddress);
}
DatagramSocket::DatagramSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<DatagramSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
DatagramSocket::DatagramSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<DatagramSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
DatagramSocket::~DatagramSocket()
{
}
DatagramSocket& DatagramSocket::operator = (const Socket& socket)
{
if (dynamic_cast<DatagramSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void DatagramSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void DatagramSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
int DatagramSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int DatagramSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
int DatagramSocket::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{
return impl()->sendTo(buffer, length, address, flags);
}
int DatagramSocket::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
return impl()->receiveFrom(buffer, length, address, flags);
}
} } // namespace Poco::Net

View File

@@ -1,83 +1,83 @@
//
// DatagramSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/DatagramSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DatagramSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DatagramSocketImpl.h"
#include "Poco/Net/NetException.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
DatagramSocketImpl::DatagramSocketImpl()
{
init(AF_INET);
}
DatagramSocketImpl::DatagramSocketImpl(IPAddress::Family family)
{
if (family == IPAddress::IPv4)
init(AF_INET);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
init(AF_INET6);
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to DatagramSocketImpl");
}
DatagramSocketImpl::DatagramSocketImpl(poco_socket_t sockfd): SocketImpl(sockfd)
{
}
DatagramSocketImpl::~DatagramSocketImpl()
{
}
void DatagramSocketImpl::init(int af)
{
initSocket(af, SOCK_DGRAM);
}
} } // namespace Poco::Net
//
// DatagramSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/DatagramSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DatagramSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DatagramSocketImpl.h"
#include "Poco/Net/NetException.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
DatagramSocketImpl::DatagramSocketImpl()
{
init(AF_INET);
}
DatagramSocketImpl::DatagramSocketImpl(IPAddress::Family family)
{
if (family == IPAddress::IPv4)
init(AF_INET);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
init(AF_INET6);
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to DatagramSocketImpl");
}
DatagramSocketImpl::DatagramSocketImpl(poco_socket_t sockfd): SocketImpl(sockfd)
{
}
DatagramSocketImpl::~DatagramSocketImpl()
{
}
void DatagramSocketImpl::init(int af)
{
initSocket(af, SOCK_DGRAM);
}
} } // namespace Poco::Net

View File

@@ -1,278 +1,278 @@
//
// DialogSocket.cpp
//
// $Id: //poco/1.2/Net/src/DialogSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DialogSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DialogSocket.h"
#include <string.h>
#include <ctype.h>
namespace Poco {
namespace Net {
DialogSocket::DialogSocket():
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::DialogSocket(const SocketAddress& address):
StreamSocket(address),
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::DialogSocket(const Socket& socket):
StreamSocket(socket),
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::~DialogSocket()
{
delete [] _pBuffer;
}
DialogSocket& DialogSocket::operator = (const Socket& socket)
{
StreamSocket::operator = (socket);
return *this;
}
void DialogSocket::sendByte(unsigned char ch)
{
sendBytes(&ch, 1);
}
void DialogSocket::sendString(const char* str)
{
sendBytes(str, (int) strlen(str));
}
void DialogSocket::sendString(const std::string& str)
{
sendBytes(str.data(), (int) str.length());
}
void DialogSocket::sendMessage(const std::string& message)
{
std::string line;
line.reserve(message.length() + 2);
line.append(message);
line.append("\r\n");
sendString(line);
}
void DialogSocket::sendMessage(const std::string& message, const std::string& arg)
{
std::string line;
line.reserve(message.length() + arg.length() + 3);
line.append(message);
if (!arg.empty())
{
line.append(" ");
line.append(arg);
}
line.append("\r\n");
sendString(line);
}
void DialogSocket::sendMessage(const std::string& message, const std::string& arg1, const std::string& arg2)
{
std::string line;
line.reserve(message.length() + arg1.length() +arg2.length() + 4);
line.append(message);
line.append(" ");
line.append(arg1);
if (!arg2.empty())
{
line.append(" ");
line.append(arg2);
}
line.append("\r\n");
sendString(line);
}
bool DialogSocket::receiveMessage(std::string& message)
{
message.clear();
return receiveLine(message);
}
int DialogSocket::receiveStatusMessage(std::string& message)
{
message.clear();
int status = receiveStatusLine(message);
if (status < 0)
{
while (status <= 0)
{
message += '\n';
status = receiveStatusLine(message);
}
}
return status;
}
int DialogSocket::get()
{
refill();
if (_pNext != _pEnd)
return *_pNext++;
else
return EOF_CHAR;
}
int DialogSocket::peek()
{
refill();
if (_pNext != _pEnd)
return *_pNext;
else
return EOF_CHAR;
}
void DialogSocket::synch()
{
sendUrgent(TELNET_DM);
}
void DialogSocket::sendTelnetCommand(unsigned char command)
{
unsigned char buffer[2];
buffer[0] = TELNET_IAC;
buffer[1] = command;
sendBytes(buffer, 2);
}
void DialogSocket::sendTelnetCommand(unsigned char command, unsigned char arg)
{
unsigned char buffer[3];
buffer[0] = TELNET_IAC;
buffer[1] = command;
buffer[2] = arg;
sendBytes(buffer, 3);
}
void DialogSocket::refill()
{
if (_pNext == _pEnd)
{
int n = receiveBytes(_pBuffer, RECEIVE_BUFFER_SIZE);
_pNext = _pBuffer;
_pEnd = _pBuffer + n;
}
}
void DialogSocket::allocBuffer()
{
_pBuffer = new char [RECEIVE_BUFFER_SIZE];
_pNext = _pBuffer;
_pEnd = _pBuffer;
}
bool DialogSocket::receiveLine(std::string& line)
{
// An old wisdom goes: be strict in what you emit
// and generous in what you accept.
int ch = get();
while (ch != EOF_CHAR && ch != '\r' && ch != '\n')
{
line += (char) ch;
ch = get();
}
if (ch == '\r' && peek() == '\n')
get();
else if (ch == EOF_CHAR)
return false;
return true;
}
int DialogSocket::receiveStatusLine(std::string& line)
{
int status = 0;
int ch = get();
if (ch != EOF_CHAR) line += (char) ch;
int n = 0;
while (isdigit(ch) && n < 3)
{
status *= 10;
status += ch - '0';
++n;
ch = get();
if (ch != EOF_CHAR) line += (char) ch;
}
if (n == 3)
{
if (ch == '-')
status = -status;
}
else status = 0;
if (ch != EOF_CHAR) receiveLine(line);
return status;
}
} } // namespace Poco::Net
//
// DialogSocket.cpp
//
// $Id: //poco/1.2/Net/src/DialogSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: DialogSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/DialogSocket.h"
#include <string.h>
#include <ctype.h>
namespace Poco {
namespace Net {
DialogSocket::DialogSocket():
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::DialogSocket(const SocketAddress& address):
StreamSocket(address),
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::DialogSocket(const Socket& socket):
StreamSocket(socket),
_pBuffer(0),
_pNext(0),
_pEnd(0)
{
allocBuffer();
}
DialogSocket::~DialogSocket()
{
delete [] _pBuffer;
}
DialogSocket& DialogSocket::operator = (const Socket& socket)
{
StreamSocket::operator = (socket);
return *this;
}
void DialogSocket::sendByte(unsigned char ch)
{
sendBytes(&ch, 1);
}
void DialogSocket::sendString(const char* str)
{
sendBytes(str, (int) strlen(str));
}
void DialogSocket::sendString(const std::string& str)
{
sendBytes(str.data(), (int) str.length());
}
void DialogSocket::sendMessage(const std::string& message)
{
std::string line;
line.reserve(message.length() + 2);
line.append(message);
line.append("\r\n");
sendString(line);
}
void DialogSocket::sendMessage(const std::string& message, const std::string& arg)
{
std::string line;
line.reserve(message.length() + arg.length() + 3);
line.append(message);
if (!arg.empty())
{
line.append(" ");
line.append(arg);
}
line.append("\r\n");
sendString(line);
}
void DialogSocket::sendMessage(const std::string& message, const std::string& arg1, const std::string& arg2)
{
std::string line;
line.reserve(message.length() + arg1.length() +arg2.length() + 4);
line.append(message);
line.append(" ");
line.append(arg1);
if (!arg2.empty())
{
line.append(" ");
line.append(arg2);
}
line.append("\r\n");
sendString(line);
}
bool DialogSocket::receiveMessage(std::string& message)
{
message.clear();
return receiveLine(message);
}
int DialogSocket::receiveStatusMessage(std::string& message)
{
message.clear();
int status = receiveStatusLine(message);
if (status < 0)
{
while (status <= 0)
{
message += '\n';
status = receiveStatusLine(message);
}
}
return status;
}
int DialogSocket::get()
{
refill();
if (_pNext != _pEnd)
return *_pNext++;
else
return EOF_CHAR;
}
int DialogSocket::peek()
{
refill();
if (_pNext != _pEnd)
return *_pNext;
else
return EOF_CHAR;
}
void DialogSocket::synch()
{
sendUrgent(TELNET_DM);
}
void DialogSocket::sendTelnetCommand(unsigned char command)
{
unsigned char buffer[2];
buffer[0] = TELNET_IAC;
buffer[1] = command;
sendBytes(buffer, 2);
}
void DialogSocket::sendTelnetCommand(unsigned char command, unsigned char arg)
{
unsigned char buffer[3];
buffer[0] = TELNET_IAC;
buffer[1] = command;
buffer[2] = arg;
sendBytes(buffer, 3);
}
void DialogSocket::refill()
{
if (_pNext == _pEnd)
{
int n = receiveBytes(_pBuffer, RECEIVE_BUFFER_SIZE);
_pNext = _pBuffer;
_pEnd = _pBuffer + n;
}
}
void DialogSocket::allocBuffer()
{
_pBuffer = new char [RECEIVE_BUFFER_SIZE];
_pNext = _pBuffer;
_pEnd = _pBuffer;
}
bool DialogSocket::receiveLine(std::string& line)
{
// An old wisdom goes: be strict in what you emit
// and generous in what you accept.
int ch = get();
while (ch != EOF_CHAR && ch != '\r' && ch != '\n')
{
line += (char) ch;
ch = get();
}
if (ch == '\r' && peek() == '\n')
get();
else if (ch == EOF_CHAR)
return false;
return true;
}
int DialogSocket::receiveStatusLine(std::string& line)
{
int status = 0;
int ch = get();
if (ch != EOF_CHAR) line += (char) ch;
int n = 0;
while (isdigit(ch) && n < 3)
{
status *= 10;
status += ch - '0';
++n;
ch = get();
if (ch != EOF_CHAR) line += (char) ch;
}
if (n == 3)
{
if (ch == '-')
status = -status;
}
else status = 0;
if (ch != EOF_CHAR) receiveLine(line);
return status;
}
} } // namespace Poco::Net

File diff suppressed because it is too large Load Diff

View File

@@ -1,257 +1,257 @@
//
// FTPStreamFactory.cpp
//
// $Id: //poco/1.2/Net/src/FTPStreamFactory.cpp#1 $
//
// Library: Net
// Package: FTP
// Module: FTPStreamFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/FTPStreamFactory.h"
#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/Path.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
using Poco::Path;
namespace Poco {
namespace Net {
class FTPStreamBuf: public UnbufferedStreamBuf
{
public:
FTPStreamBuf(std::istream& istr):
_istr(istr)
{
}
~FTPStreamBuf()
{
}
private:
int readFromDevice()
{
return _istr.get();
}
std::istream& _istr;
};
class FTPIOS: public virtual std::ios
{
public:
FTPIOS(std::istream& istr):
_buf(istr)
{
poco_ios_init(&_buf);
}
~FTPIOS()
{
}
FTPStreamBuf* rdbuf()
{
return &_buf;
}
protected:
FTPStreamBuf _buf;
};
class FTPStream: public FTPIOS, public std::istream
{
public:
FTPStream(std::istream& istr, FTPClientSession* pSession):
FTPIOS(istr),
std::istream(&_buf),
_pSession(pSession)
{
}
~FTPStream()
{
delete _pSession;
}
private:
FTPClientSession* _pSession;
};
FTPPasswordProvider::FTPPasswordProvider()
{
}
FTPPasswordProvider::~FTPPasswordProvider()
{
}
std::string FTPStreamFactory::_anonymousPassword("poco@localhost");
FTPPasswordProvider* FTPStreamFactory::_pPasswordProvider(0);
FTPStreamFactory::FTPStreamFactory()
{
}
FTPStreamFactory::~FTPStreamFactory()
{
}
std::istream* FTPStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "ftp");
FTPClientSession* pSession = new FTPClientSession(uri.getHost(), uri.getPort());
try
{
std::string username;
std::string password;
getUserInfo(uri, username, password);
std::string path;
char type;
getPathAndType(uri, path, type);
pSession->login(username, password);
if (type == 'a')
pSession->setFileType(FTPClientSession::TYPE_TEXT);
Path p(path, Path::PATH_UNIX);
p.makeFile();
for (int i = 0; i < p.depth(); ++i)
pSession->setWorkingDirectory(p[i]);
std::string file(p.getFileName());
std::istream& istr = (type == 'd' ? pSession->beginList(file) : pSession->beginDownload(file));
return new FTPStream(istr, pSession);
}
catch (...)
{
delete pSession;
throw;
}
}
void FTPStreamFactory::setAnonymousPassword(const std::string& password)
{
_anonymousPassword = password;
}
const std::string& FTPStreamFactory::getAnonymousPassword()
{
return _anonymousPassword;
}
void FTPStreamFactory::setPasswordProvider(FTPPasswordProvider* pProvider)
{
_pPasswordProvider = pProvider;
}
FTPPasswordProvider* FTPStreamFactory::getPasswordProvider()
{
return _pPasswordProvider;
}
void FTPStreamFactory::splitUserInfo(const std::string& userInfo, std::string& username, std::string& password)
{
std::string::size_type pos = userInfo.find(':');
if (pos != std::string::npos)
{
username.assign(userInfo, 0, pos++);
password.assign(userInfo, pos, userInfo.size() - pos);
}
else username = userInfo;
}
void FTPStreamFactory::getUserInfo(const URI& uri, std::string& username, std::string& password)
{
splitUserInfo(uri.getUserInfo(), username, password);
if (username.empty())
{
username = "anonymous";
password = _anonymousPassword;
}
else if (password.empty())
{
if (_pPasswordProvider)
password = _pPasswordProvider->password(username, uri.getHost());
else
throw FTPException(std::string("Password required for ") + username + "@" + uri.getHost());
}
}
void FTPStreamFactory::getPathAndType(const Poco::URI& uri, std::string& path, char& type)
{
path = uri.getPath();
type = 'i';
std::string::size_type pos = path.rfind(';');
if (pos != std::string::npos)
{
if (path.length() == pos + 7 && path.compare(pos + 1, 5, "type=") == 0)
{
type = path[pos + 6];
path.resize(pos);
}
}
}
void FTPStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("ftp", new FTPStreamFactory);
}
} } // namespace Poco::Net
//
// FTPStreamFactory.cpp
//
// $Id: //poco/1.2/Net/src/FTPStreamFactory.cpp#1 $
//
// Library: Net
// Package: FTP
// Module: FTPStreamFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/FTPStreamFactory.h"
#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/Path.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
using Poco::Path;
namespace Poco {
namespace Net {
class FTPStreamBuf: public UnbufferedStreamBuf
{
public:
FTPStreamBuf(std::istream& istr):
_istr(istr)
{
}
~FTPStreamBuf()
{
}
private:
int readFromDevice()
{
return _istr.get();
}
std::istream& _istr;
};
class FTPIOS: public virtual std::ios
{
public:
FTPIOS(std::istream& istr):
_buf(istr)
{
poco_ios_init(&_buf);
}
~FTPIOS()
{
}
FTPStreamBuf* rdbuf()
{
return &_buf;
}
protected:
FTPStreamBuf _buf;
};
class FTPStream: public FTPIOS, public std::istream
{
public:
FTPStream(std::istream& istr, FTPClientSession* pSession):
FTPIOS(istr),
std::istream(&_buf),
_pSession(pSession)
{
}
~FTPStream()
{
delete _pSession;
}
private:
FTPClientSession* _pSession;
};
FTPPasswordProvider::FTPPasswordProvider()
{
}
FTPPasswordProvider::~FTPPasswordProvider()
{
}
std::string FTPStreamFactory::_anonymousPassword("poco@localhost");
FTPPasswordProvider* FTPStreamFactory::_pPasswordProvider(0);
FTPStreamFactory::FTPStreamFactory()
{
}
FTPStreamFactory::~FTPStreamFactory()
{
}
std::istream* FTPStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "ftp");
FTPClientSession* pSession = new FTPClientSession(uri.getHost(), uri.getPort());
try
{
std::string username;
std::string password;
getUserInfo(uri, username, password);
std::string path;
char type;
getPathAndType(uri, path, type);
pSession->login(username, password);
if (type == 'a')
pSession->setFileType(FTPClientSession::TYPE_TEXT);
Path p(path, Path::PATH_UNIX);
p.makeFile();
for (int i = 0; i < p.depth(); ++i)
pSession->setWorkingDirectory(p[i]);
std::string file(p.getFileName());
std::istream& istr = (type == 'd' ? pSession->beginList(file) : pSession->beginDownload(file));
return new FTPStream(istr, pSession);
}
catch (...)
{
delete pSession;
throw;
}
}
void FTPStreamFactory::setAnonymousPassword(const std::string& password)
{
_anonymousPassword = password;
}
const std::string& FTPStreamFactory::getAnonymousPassword()
{
return _anonymousPassword;
}
void FTPStreamFactory::setPasswordProvider(FTPPasswordProvider* pProvider)
{
_pPasswordProvider = pProvider;
}
FTPPasswordProvider* FTPStreamFactory::getPasswordProvider()
{
return _pPasswordProvider;
}
void FTPStreamFactory::splitUserInfo(const std::string& userInfo, std::string& username, std::string& password)
{
std::string::size_type pos = userInfo.find(':');
if (pos != std::string::npos)
{
username.assign(userInfo, 0, pos++);
password.assign(userInfo, pos, userInfo.size() - pos);
}
else username = userInfo;
}
void FTPStreamFactory::getUserInfo(const URI& uri, std::string& username, std::string& password)
{
splitUserInfo(uri.getUserInfo(), username, password);
if (username.empty())
{
username = "anonymous";
password = _anonymousPassword;
}
else if (password.empty())
{
if (_pPasswordProvider)
password = _pPasswordProvider->password(username, uri.getHost());
else
throw FTPException(std::string("Password required for ") + username + "@" + uri.getHost());
}
}
void FTPStreamFactory::getPathAndType(const Poco::URI& uri, std::string& path, char& type)
{
path = uri.getPath();
type = 'i';
std::string::size_type pos = path.rfind(';');
if (pos != std::string::npos)
{
if (path.length() == pos + 7 && path.compare(pos + 1, 5, "type=") == 0)
{
type = path[pos + 6];
path.resize(pos);
}
}
}
void FTPStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("ftp", new FTPStreamFactory);
}
} } // namespace Poco::Net

View File

@@ -1,88 +1,88 @@
//
// FilePartSource.cpp
//
// $Id: //poco/1.2/Net/src/FilePartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: FilePartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/FilePartSource.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"
using Poco::Path;
using Poco::OpenFileException;
namespace Poco {
namespace Net {
FilePartSource::FilePartSource(const std::string& path):
_istr(path.c_str(), std::ios::in | std::ios::binary)
{
Path p(path);
_filename = p.getFileName();
if (!_istr.good())
throw OpenFileException(path);
}
FilePartSource::FilePartSource(const std::string& path, const std::string& mediaType):
PartSource(mediaType),
_istr(path.c_str(), std::ios::in | std::ios::binary)
{
Path p(path);
_filename = p.getFileName();
if (!_istr.good())
throw OpenFileException(path);
}
FilePartSource::~FilePartSource()
{
}
std::istream& FilePartSource::stream()
{
return _istr;
}
const std::string& FilePartSource::filename()
{
return _filename;
}
} } // namespace Poco::Net
//
// FilePartSource.cpp
//
// $Id: //poco/1.2/Net/src/FilePartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: FilePartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/FilePartSource.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"
using Poco::Path;
using Poco::OpenFileException;
namespace Poco {
namespace Net {
FilePartSource::FilePartSource(const std::string& path):
_istr(path.c_str(), std::ios::in | std::ios::binary)
{
Path p(path);
_filename = p.getFileName();
if (!_istr.good())
throw OpenFileException(path);
}
FilePartSource::FilePartSource(const std::string& path, const std::string& mediaType):
PartSource(mediaType),
_istr(path.c_str(), std::ios::in | std::ios::binary)
{
Path p(path);
_filename = p.getFileName();
if (!_istr.good())
throw OpenFileException(path);
}
FilePartSource::~FilePartSource()
{
}
std::istream& FilePartSource::stream()
{
return _istr;
}
const std::string& FilePartSource::filename()
{
return _filename;
}
} } // namespace Poco::Net

View File

@@ -1,361 +1,361 @@
//
// HTMLForm.cpp
//
// $Id: //poco/1.2/Net/src/HTMLForm.cpp#3 $
//
// Library: Net
// Package: HTML
// Module: HTMLForm
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTMLForm.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/PartSource.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/Net/MultipartWriter.h"
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/NullPartHandler.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include "Poco/URI.h"
#include "Poco/String.h"
#include <sstream>
#include <ctype.h>
using Poco::NullInputStream;
using Poco::StreamCopier;
using Poco::SyntaxException;
using Poco::URI;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTMLForm::ENCODING_URL = "application/x-www-form-urlencoded";
const std::string HTMLForm::ENCODING_MULTIPART = "multipart/form-data";
HTMLForm::HTMLForm():
_encoding(ENCODING_URL)
{
}
HTMLForm::HTMLForm(const std::string& encoding):
_encoding(encoding)
{
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler)
{
load(request, requestBody, handler);
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody)
{
load(request, requestBody);
}
HTMLForm::HTMLForm(const HTTPRequest& request)
{
load(request);
}
HTMLForm::~HTMLForm()
{
for (PartVec::iterator it = _parts.begin(); it != _parts.end(); ++it)
{
delete it->pSource;
}
}
void HTMLForm::setEncoding(const std::string& encoding)
{
_encoding = encoding;
}
void HTMLForm::addPart(const std::string& name, PartSource* pSource)
{
poco_check_ptr (pSource);
Part part;
part.name = name;
part.pSource = pSource;
_parts.push_back(part);
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler)
{
if (request.getMethod() == HTTPRequest::HTTP_POST)
{
std::string mediaType;
NameValueCollection params;
MessageHeader::splitParameters(request.getContentType(), mediaType, params);
_encoding = mediaType;
if (_encoding == ENCODING_MULTIPART)
{
_boundary = params["boundary"];
readMultipart(requestBody, handler);
}
else
{
readUrl(requestBody);
}
}
else
{
URI uri(request.getURI());
std::istringstream istr(uri.getRawQuery());
readUrl(istr);
}
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody)
{
NullPartHandler nah;
load(request, requestBody, nah);
}
void HTMLForm::load(const HTTPRequest& request)
{
NullPartHandler nah;
NullInputStream nis;
load(request, nis, nah);
}
void HTMLForm::read(std::istream& istr, PartHandler& handler)
{
if (_encoding == ENCODING_URL)
readUrl(istr);
else
readMultipart(istr, handler);
}
void HTMLForm::prepareSubmit(HTTPRequest& request)
{
if (request.getMethod() == HTTPRequest::HTTP_POST)
{
if (_encoding == ENCODING_URL)
{
request.setContentType(_encoding);
}
else
{
_boundary = MultipartWriter::createBoundary();
std::string ct(_encoding);
ct.append("; boundary=\"");
ct.append(_boundary);
ct.append("\"");
request.setContentType(ct);
}
if (request.getVersion() == HTTPMessage::HTTP_1_0)
{
request.setKeepAlive(false);
request.setChunkedTransferEncoding(false);
}
else
{
request.setChunkedTransferEncoding(true);
}
}
else
{
std::string uri = request.getURI();
std::ostringstream ostr;
write(ostr);
uri.append("?");
uri.append(ostr.str());
request.setURI(uri);
}
}
void HTMLForm::write(std::ostream& ostr, const std::string& boundary)
{
if (_encoding == ENCODING_URL)
{
writeUrl(ostr);
}
else
{
_boundary = boundary;
writeMultipart(ostr);
}
}
void HTMLForm::write(std::ostream& ostr)
{
if (_encoding == ENCODING_URL)
writeUrl(ostr);
else
writeMultipart(ostr);
}
void HTMLForm::readUrl(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
int ch = istr.get();
while (ch != eof)
{
std::string name;
std::string value;
while (ch != eof && ch != '=' && ch != '&')
{
if (ch == '+') ch = ' ';
name += (char) ch;
ch = istr.get();
}
if (ch == '=')
{
ch = istr.get();
while (ch != eof && ch != '&')
{
if (ch == '+') ch = ' ';
value += (char) ch;
ch = istr.get();
}
}
std::string decodedName;
std::string decodedValue;
URI::decode(name, decodedName);
URI::decode(value, decodedValue);
add(decodedName, decodedValue);
if (ch == '&') ch = istr.get();
}
}
void HTMLForm::readMultipart(std::istream& istr, PartHandler& handler)
{
static const int eof = std::char_traits<char>::eof();
MultipartReader reader(istr, _boundary);
while (reader.hasNextPart())
{
MessageHeader header;
reader.nextPart(header);
std::string disp;
NameValueCollection params;
if (header.has("Content-Disposition"))
{
std::string cd = header.get("Content-Disposition");
MessageHeader::splitParameters(cd, disp, params);
}
if (params.has("filename"))
{
handler.handlePart(header, reader.stream());
// Ensure that the complete part has been read.
while (reader.stream().good()) reader.stream().get();
}
else
{
std::string name = params["name"];
std::string value;
std::istream& istr = reader.stream();
int ch = istr.get();
while (ch != eof)
{
value += (char) ch;
ch = istr.get();
}
add(name, value);
}
}
}
void HTMLForm::writeUrl(std::ostream& ostr)
{
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
if (it != begin()) ostr << "&";
std::string name;
URI::encode(it->first, "=&", name);
std::string value;
URI::encode(it->second, "=&", value);
ostr << name << "=" << value;
}
}
void HTMLForm::writeMultipart(std::ostream& ostr)
{
MultipartWriter writer(ostr, _boundary);
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
MessageHeader header;
std::string disp("form-data; name=\"");
disp.append(it->first);
disp.append("\"");
header.set("Content-Disposition", disp);
writer.nextPart(header);
ostr << it->second;
}
for (PartVec::iterator ita = _parts.begin(); ita != _parts.end(); ++ita)
{
MessageHeader header;
std::string disp("file; name=\"");
disp.append(ita->name);
disp.append("\"");
std::string filename = ita->pSource->filename();
if (!filename.empty())
{
disp.append("; filename=\"");
disp.append(filename);
disp.append("\"");
}
header.set("Content-Disposition", disp);
header.set("Content-Type", ita->pSource->mediaType());
writer.nextPart(header);
StreamCopier::copyStream(ita->pSource->stream(), ostr);
}
writer.close();
_boundary = writer.boundary();
}
} } // namespace Poco::Net
//
// HTMLForm.cpp
//
// $Id: //poco/1.2/Net/src/HTMLForm.cpp#3 $
//
// Library: Net
// Package: HTML
// Module: HTMLForm
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTMLForm.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/PartSource.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/Net/MultipartWriter.h"
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/NullPartHandler.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include "Poco/URI.h"
#include "Poco/String.h"
#include <sstream>
#include <ctype.h>
using Poco::NullInputStream;
using Poco::StreamCopier;
using Poco::SyntaxException;
using Poco::URI;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTMLForm::ENCODING_URL = "application/x-www-form-urlencoded";
const std::string HTMLForm::ENCODING_MULTIPART = "multipart/form-data";
HTMLForm::HTMLForm():
_encoding(ENCODING_URL)
{
}
HTMLForm::HTMLForm(const std::string& encoding):
_encoding(encoding)
{
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler)
{
load(request, requestBody, handler);
}
HTMLForm::HTMLForm(const HTTPRequest& request, std::istream& requestBody)
{
load(request, requestBody);
}
HTMLForm::HTMLForm(const HTTPRequest& request)
{
load(request);
}
HTMLForm::~HTMLForm()
{
for (PartVec::iterator it = _parts.begin(); it != _parts.end(); ++it)
{
delete it->pSource;
}
}
void HTMLForm::setEncoding(const std::string& encoding)
{
_encoding = encoding;
}
void HTMLForm::addPart(const std::string& name, PartSource* pSource)
{
poco_check_ptr (pSource);
Part part;
part.name = name;
part.pSource = pSource;
_parts.push_back(part);
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody, PartHandler& handler)
{
if (request.getMethod() == HTTPRequest::HTTP_POST)
{
std::string mediaType;
NameValueCollection params;
MessageHeader::splitParameters(request.getContentType(), mediaType, params);
_encoding = mediaType;
if (_encoding == ENCODING_MULTIPART)
{
_boundary = params["boundary"];
readMultipart(requestBody, handler);
}
else
{
readUrl(requestBody);
}
}
else
{
URI uri(request.getURI());
std::istringstream istr(uri.getRawQuery());
readUrl(istr);
}
}
void HTMLForm::load(const HTTPRequest& request, std::istream& requestBody)
{
NullPartHandler nah;
load(request, requestBody, nah);
}
void HTMLForm::load(const HTTPRequest& request)
{
NullPartHandler nah;
NullInputStream nis;
load(request, nis, nah);
}
void HTMLForm::read(std::istream& istr, PartHandler& handler)
{
if (_encoding == ENCODING_URL)
readUrl(istr);
else
readMultipart(istr, handler);
}
void HTMLForm::prepareSubmit(HTTPRequest& request)
{
if (request.getMethod() == HTTPRequest::HTTP_POST)
{
if (_encoding == ENCODING_URL)
{
request.setContentType(_encoding);
}
else
{
_boundary = MultipartWriter::createBoundary();
std::string ct(_encoding);
ct.append("; boundary=\"");
ct.append(_boundary);
ct.append("\"");
request.setContentType(ct);
}
if (request.getVersion() == HTTPMessage::HTTP_1_0)
{
request.setKeepAlive(false);
request.setChunkedTransferEncoding(false);
}
else
{
request.setChunkedTransferEncoding(true);
}
}
else
{
std::string uri = request.getURI();
std::ostringstream ostr;
write(ostr);
uri.append("?");
uri.append(ostr.str());
request.setURI(uri);
}
}
void HTMLForm::write(std::ostream& ostr, const std::string& boundary)
{
if (_encoding == ENCODING_URL)
{
writeUrl(ostr);
}
else
{
_boundary = boundary;
writeMultipart(ostr);
}
}
void HTMLForm::write(std::ostream& ostr)
{
if (_encoding == ENCODING_URL)
writeUrl(ostr);
else
writeMultipart(ostr);
}
void HTMLForm::readUrl(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
int ch = istr.get();
while (ch != eof)
{
std::string name;
std::string value;
while (ch != eof && ch != '=' && ch != '&')
{
if (ch == '+') ch = ' ';
name += (char) ch;
ch = istr.get();
}
if (ch == '=')
{
ch = istr.get();
while (ch != eof && ch != '&')
{
if (ch == '+') ch = ' ';
value += (char) ch;
ch = istr.get();
}
}
std::string decodedName;
std::string decodedValue;
URI::decode(name, decodedName);
URI::decode(value, decodedValue);
add(decodedName, decodedValue);
if (ch == '&') ch = istr.get();
}
}
void HTMLForm::readMultipart(std::istream& istr, PartHandler& handler)
{
static const int eof = std::char_traits<char>::eof();
MultipartReader reader(istr, _boundary);
while (reader.hasNextPart())
{
MessageHeader header;
reader.nextPart(header);
std::string disp;
NameValueCollection params;
if (header.has("Content-Disposition"))
{
std::string cd = header.get("Content-Disposition");
MessageHeader::splitParameters(cd, disp, params);
}
if (params.has("filename"))
{
handler.handlePart(header, reader.stream());
// Ensure that the complete part has been read.
while (reader.stream().good()) reader.stream().get();
}
else
{
std::string name = params["name"];
std::string value;
std::istream& istr = reader.stream();
int ch = istr.get();
while (ch != eof)
{
value += (char) ch;
ch = istr.get();
}
add(name, value);
}
}
}
void HTMLForm::writeUrl(std::ostream& ostr)
{
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
if (it != begin()) ostr << "&";
std::string name;
URI::encode(it->first, "=&", name);
std::string value;
URI::encode(it->second, "=&", value);
ostr << name << "=" << value;
}
}
void HTMLForm::writeMultipart(std::ostream& ostr)
{
MultipartWriter writer(ostr, _boundary);
for (NameValueCollection::ConstIterator it = begin(); it != end(); ++it)
{
MessageHeader header;
std::string disp("form-data; name=\"");
disp.append(it->first);
disp.append("\"");
header.set("Content-Disposition", disp);
writer.nextPart(header);
ostr << it->second;
}
for (PartVec::iterator ita = _parts.begin(); ita != _parts.end(); ++ita)
{
MessageHeader header;
std::string disp("file; name=\"");
disp.append(ita->name);
disp.append("\"");
std::string filename = ita->pSource->filename();
if (!filename.empty())
{
disp.append("; filename=\"");
disp.append(filename);
disp.append("\"");
}
header.set("Content-Disposition", disp);
header.set("Content-Type", ita->pSource->mediaType());
writer.nextPart(header);
StreamCopier::copyStream(ita->pSource->stream(), ostr);
}
writer.close();
_boundary = writer.boundary();
}
} } // namespace Poco::Net

View File

@@ -1,125 +1,125 @@
//
// HTTPBasicCredentials.cpp
//
// $Id: //poco/1.2/Net/src/HTTPBasicCredentials.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPBasicCredentials
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/NetException.h"
#include "Poco/Base64Encoder.h"
#include "Poco/Base64Decoder.h"
#include "Poco/String.h"
#include <sstream>
using Poco::Base64Decoder;
using Poco::Base64Encoder;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTTPBasicCredentials::SCHEME = "Basic";
HTTPBasicCredentials::HTTPBasicCredentials()
{
}
HTTPBasicCredentials::HTTPBasicCredentials(const std::string& username, const std::string& password):
_username(username),
_password(password)
{
}
HTTPBasicCredentials::HTTPBasicCredentials(const HTTPRequest& request)
{
static const int eof = std::char_traits<char>::eof();
std::string scheme;
std::string info;
request.getCredentials(scheme, info);
if (icompare(scheme, SCHEME) == 0)
{
std::istringstream istr(info);
Base64Decoder decoder(istr);
int ch = decoder.get();
while (ch != eof && ch != ':')
{
_username += (char) ch;
ch = decoder.get();
}
if (ch == ':') ch = decoder.get();
while (ch != eof)
{
_password += (char) ch;
ch = decoder.get();
}
}
else throw NotAuthenticatedException("Basic authentication expected");
}
HTTPBasicCredentials::~HTTPBasicCredentials()
{
}
void HTTPBasicCredentials::setUsername(const std::string& username)
{
_username = username;
}
void HTTPBasicCredentials::setPassword(const std::string& password)
{
_password = password;
}
void HTTPBasicCredentials::authenticate(HTTPRequest& request)
{
std::ostringstream ostr;
Base64Encoder encoder(ostr);
encoder << _username << ":" << _password;
encoder.close();
request.setCredentials(SCHEME, ostr.str());
}
} } // namespace Poco::Net
//
// HTTPBasicCredentials.cpp
//
// $Id: //poco/1.2/Net/src/HTTPBasicCredentials.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPBasicCredentials
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/NetException.h"
#include "Poco/Base64Encoder.h"
#include "Poco/Base64Decoder.h"
#include "Poco/String.h"
#include <sstream>
using Poco::Base64Decoder;
using Poco::Base64Encoder;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTTPBasicCredentials::SCHEME = "Basic";
HTTPBasicCredentials::HTTPBasicCredentials()
{
}
HTTPBasicCredentials::HTTPBasicCredentials(const std::string& username, const std::string& password):
_username(username),
_password(password)
{
}
HTTPBasicCredentials::HTTPBasicCredentials(const HTTPRequest& request)
{
static const int eof = std::char_traits<char>::eof();
std::string scheme;
std::string info;
request.getCredentials(scheme, info);
if (icompare(scheme, SCHEME) == 0)
{
std::istringstream istr(info);
Base64Decoder decoder(istr);
int ch = decoder.get();
while (ch != eof && ch != ':')
{
_username += (char) ch;
ch = decoder.get();
}
if (ch == ':') ch = decoder.get();
while (ch != eof)
{
_password += (char) ch;
ch = decoder.get();
}
}
else throw NotAuthenticatedException("Basic authentication expected");
}
HTTPBasicCredentials::~HTTPBasicCredentials()
{
}
void HTTPBasicCredentials::setUsername(const std::string& username)
{
_username = username;
}
void HTTPBasicCredentials::setPassword(const std::string& password)
{
_password = password;
}
void HTTPBasicCredentials::authenticate(HTTPRequest& request)
{
std::ostringstream ostr;
Base64Encoder encoder(ostr);
encoder << _username << ":" << _password;
encoder.close();
request.setCredentials(SCHEME, ostr.str());
}
} } // namespace Poco::Net

View File

@@ -1,66 +1,66 @@
//
// HTTPBufferAllocator.cpp
//
// $Id: //poco/Main/template/class.cpp#4 $
//
// Library: Net
// Package: HTTP
// Module: HTTPBufferAllocator
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPBufferAllocator.h"
using Poco::MemoryPool;
namespace Poco {
namespace Net {
MemoryPool HTTPBufferAllocator::_pool(HTTPBufferAllocator::BUFFER_SIZE, 16);
char* HTTPBufferAllocator::allocate(std::streamsize size)
{
poco_assert_dbg (size == BUFFER_SIZE);
return reinterpret_cast<char*>(_pool.get());
}
void HTTPBufferAllocator::deallocate(char* ptr, std::streamsize size)
{
poco_assert_dbg (size == BUFFER_SIZE);
_pool.release(ptr);
}
} } // namespace Poco::Net
//
// HTTPBufferAllocator.cpp
//
// $Id: //poco/Main/template/class.cpp#4 $
//
// Library: Net
// Package: HTTP
// Module: HTTPBufferAllocator
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPBufferAllocator.h"
using Poco::MemoryPool;
namespace Poco {
namespace Net {
MemoryPool HTTPBufferAllocator::_pool(HTTPBufferAllocator::BUFFER_SIZE, 16);
char* HTTPBufferAllocator::allocate(std::streamsize size)
{
poco_assert_dbg (size == BUFFER_SIZE);
return reinterpret_cast<char*>(_pool.get());
}
void HTTPBufferAllocator::deallocate(char* ptr, std::streamsize size)
{
poco_assert_dbg (size == BUFFER_SIZE);
_pool.release(ptr);
}
} } // namespace Poco::Net

View File

@@ -1,214 +1,214 @@
//
// HTTPChunkedStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPChunkedStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPChunkedStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/HTTPSession.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include <ctype.h>
using Poco::NumberFormatter;
using Poco::NumberParser;
namespace Poco {
namespace Net {
//
// HTTPChunkedStreamBuf
//
HTTPChunkedStreamBuf::HTTPChunkedStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_mode(mode),
_chunk(0)
{
}
HTTPChunkedStreamBuf::~HTTPChunkedStreamBuf()
{
}
void HTTPChunkedStreamBuf::close()
{
if (_mode & std::ios::out)
{
sync();
_session.write("0\r\n", 3);
}
}
int HTTPChunkedStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
static const int eof = std::char_traits<char>::eof();
if (_chunk == 0)
{
int ch = _session.get();
while (isspace(ch)) ch = _session.get();
std::string chunkLen;
while (isxdigit(ch)) { chunkLen += (char) ch; ch = _session.get(); }
while (ch != eof && ch != '\n') ch = _session.get();
unsigned chunk;
if (NumberParser::tryParseHex(chunkLen, chunk))
_chunk = (std::streamsize) chunk;
else
return eof;
}
if (_chunk > 0)
{
if (length > _chunk) length = _chunk;
int n = _session.read(buffer, length);
if (n > 0) _chunk -= n;
return n;
}
else return 0;
}
int HTTPChunkedStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
std::string chunkSize(NumberFormatter::formatHex(length));
chunkSize.append("\r\n");
_session.write(chunkSize.data(), (std::streamsize) chunkSize.length());
_session.write(buffer, length);
_session.write("\r\n", 2);
return length;
}
//
// HTTPChunkedIOS
//
HTTPChunkedIOS::HTTPChunkedIOS(HTTPSession& session, HTTPChunkedStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPChunkedIOS::~HTTPChunkedIOS()
{
try
{
_buf.close();
}
catch (...)
{
}
}
HTTPChunkedStreamBuf* HTTPChunkedIOS::rdbuf()
{
return &_buf;
}
//
// HTTPChunkedInputStream
//
Poco::MemoryPool HTTPChunkedInputStream::_pool(sizeof(HTTPChunkedInputStream));
HTTPChunkedInputStream::HTTPChunkedInputStream(HTTPSession& session):
HTTPChunkedIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPChunkedInputStream::~HTTPChunkedInputStream()
{
}
void* HTTPChunkedInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPChunkedInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPChunkedOutputStream
//
Poco::MemoryPool HTTPChunkedOutputStream::_pool(sizeof(HTTPChunkedOutputStream));
HTTPChunkedOutputStream::HTTPChunkedOutputStream(HTTPSession& session):
HTTPChunkedIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPChunkedOutputStream::~HTTPChunkedOutputStream()
{
}
void* HTTPChunkedOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPChunkedOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net
//
// HTTPChunkedStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPChunkedStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPChunkedStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/HTTPSession.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include <ctype.h>
using Poco::NumberFormatter;
using Poco::NumberParser;
namespace Poco {
namespace Net {
//
// HTTPChunkedStreamBuf
//
HTTPChunkedStreamBuf::HTTPChunkedStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_mode(mode),
_chunk(0)
{
}
HTTPChunkedStreamBuf::~HTTPChunkedStreamBuf()
{
}
void HTTPChunkedStreamBuf::close()
{
if (_mode & std::ios::out)
{
sync();
_session.write("0\r\n", 3);
}
}
int HTTPChunkedStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
static const int eof = std::char_traits<char>::eof();
if (_chunk == 0)
{
int ch = _session.get();
while (isspace(ch)) ch = _session.get();
std::string chunkLen;
while (isxdigit(ch)) { chunkLen += (char) ch; ch = _session.get(); }
while (ch != eof && ch != '\n') ch = _session.get();
unsigned chunk;
if (NumberParser::tryParseHex(chunkLen, chunk))
_chunk = (std::streamsize) chunk;
else
return eof;
}
if (_chunk > 0)
{
if (length > _chunk) length = _chunk;
int n = _session.read(buffer, length);
if (n > 0) _chunk -= n;
return n;
}
else return 0;
}
int HTTPChunkedStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
std::string chunkSize(NumberFormatter::formatHex(length));
chunkSize.append("\r\n");
_session.write(chunkSize.data(), (std::streamsize) chunkSize.length());
_session.write(buffer, length);
_session.write("\r\n", 2);
return length;
}
//
// HTTPChunkedIOS
//
HTTPChunkedIOS::HTTPChunkedIOS(HTTPSession& session, HTTPChunkedStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPChunkedIOS::~HTTPChunkedIOS()
{
try
{
_buf.close();
}
catch (...)
{
}
}
HTTPChunkedStreamBuf* HTTPChunkedIOS::rdbuf()
{
return &_buf;
}
//
// HTTPChunkedInputStream
//
Poco::MemoryPool HTTPChunkedInputStream::_pool(sizeof(HTTPChunkedInputStream));
HTTPChunkedInputStream::HTTPChunkedInputStream(HTTPSession& session):
HTTPChunkedIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPChunkedInputStream::~HTTPChunkedInputStream()
{
}
void* HTTPChunkedInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPChunkedInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPChunkedOutputStream
//
Poco::MemoryPool HTTPChunkedOutputStream::_pool(sizeof(HTTPChunkedOutputStream));
HTTPChunkedOutputStream::HTTPChunkedOutputStream(HTTPSession& session):
HTTPChunkedIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPChunkedOutputStream::~HTTPChunkedOutputStream()
{
}
void* HTTPChunkedOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPChunkedOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net

View File

@@ -1,297 +1,297 @@
//
// HTTPClientSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPClientSession.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
using Poco::NumberFormatter;
using Poco::IllegalStateException;
namespace Poco {
namespace Net {
HTTPClientSession::HTTPClientSession():
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const StreamSocket& socket):
HTTPSession(socket),
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const SocketAddress& address):
_host(address.host().toString()),
_port(address.port()),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const std::string& host, Poco::UInt16 port):
_host(host),
_port(port),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::~HTTPClientSession()
{
delete _pRequestStream;
delete _pResponseStream;
}
void HTTPClientSession::setHost(const std::string& host)
{
if (!connected())
_host = host;
else
throw IllegalStateException("Cannot set the host for an already connected session");
}
void HTTPClientSession::setPort(Poco::UInt16 port)
{
if (!connected())
_port = port;
else
throw IllegalStateException("Cannot set the port number for an already connected session");
}
void HTTPClientSession::setProxy(const std::string& host, Poco::UInt16 port)
{
if (!connected())
{
_proxyHost = host;
_proxyPort = port;
}
else throw IllegalStateException("Cannot set the proxy host and port for an already connected session");
}
void HTTPClientSession::setProxyHost(const std::string& host)
{
if (!connected())
_proxyHost = host;
else
throw IllegalStateException("Cannot set the proxy host for an already connected session");
}
void HTTPClientSession::setProxyPort(Poco::UInt16 port)
{
if (!connected())
_proxyPort = port;
else
throw IllegalStateException("Cannot set the proxy port number for an already connected session");
}
std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
{
delete _pResponseStream;
_pResponseStream = 0;
bool keepAlive = getKeepAlive();
if (connected() && !keepAlive)
close();
if (!connected())
reconnect();
request.setKeepAlive(keepAlive);
request.setHost(_host, _port);
if (!_proxyHost.empty())
request.setURI(getHostInfo() + request.getURI());
HTTPHeaderOutputStream hos(*this);
_reconnect = keepAlive;
request.write(hos);
_reconnect = false;
_expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD;
if (request.getChunkedTransferEncoding())
_pRequestStream = new HTTPChunkedOutputStream(*this);
else if (request.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength());
else if (request.getMethod() == HTTPRequest::HTTP_GET || request.getMethod() == HTTPRequest::HTTP_HEAD)
_pRequestStream = new HTTPFixedLengthOutputStream(*this, 0);
else
_pRequestStream = new HTTPOutputStream(*this);
return *_pRequestStream;
}
std::istream& HTTPClientSession::receiveResponse(HTTPResponse& response)
{
delete _pRequestStream;
_pRequestStream = 0;
do
{
response.clear();
HTTPHeaderInputStream his(*this);
try
{
response.read(his);
}
catch (MessageException&)
{
if (networkException())
networkException()->rethrow();
else
throw;
}
}
while (response.getStatus() == HTTPResponse::HTTP_CONTINUE);
if (!_expectResponseBody)
_pResponseStream = new HTTPFixedLengthInputStream(*this, 0);
else if (response.getChunkedTransferEncoding())
_pResponseStream = new HTTPChunkedInputStream(*this);
else if (response.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pResponseStream = new HTTPFixedLengthInputStream(*this, response.getContentLength());
else
_pResponseStream = new HTTPInputStream(*this);
return *_pResponseStream;
}
int HTTPClientSession::write(const char* buffer, std::streamsize length)
{
try
{
return HTTPSession::write(buffer, length);
}
catch (NetException&)
{
if (_reconnect)
{
close();
reconnect();
return HTTPSession::write(buffer, length);
}
else throw;
}
}
void HTTPClientSession::reconnect()
{
if (_proxyHost.empty())
{
SocketAddress addr(_host, _port);
connect(addr);
}
else
{
SocketAddress addr(_proxyHost, _proxyPort);
connect(addr);
}
}
std::string HTTPClientSession::getHostInfo() const
{
std::string result("http://");
result.append(_host);
result.append(":");
result.append(NumberFormatter::format(_port));
return result;
}
void HTTPClientSession::deleteResponseStream()
{
delete _pResponseStream;
_pResponseStream = 0;
}
void HTTPClientSession::deleteRequestStream()
{
delete _pRequestStream;
_pRequestStream = 0;
}
void HTTPClientSession::setResponseStream(std::istream* pRespStream)
{
poco_assert( !_pResponseStream);
_pResponseStream = pRespStream;
}
void HTTPClientSession::setRequestStream(std::ostream* pRequestStream)
{
poco_assert (!_pRequestStream);
_pRequestStream = pRequestStream;
}
} } // namespace Poco::Net
//
// HTTPClientSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPClientSession.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
using Poco::NumberFormatter;
using Poco::IllegalStateException;
namespace Poco {
namespace Net {
HTTPClientSession::HTTPClientSession():
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const StreamSocket& socket):
HTTPSession(socket),
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const SocketAddress& address):
_host(address.host().toString()),
_port(address.port()),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::HTTPClientSession(const std::string& host, Poco::UInt16 port):
_host(host),
_port(port),
_proxyPort(HTTPSession::HTTP_PORT),
_reconnect(false),
_expectResponseBody(false),
_pRequestStream(0),
_pResponseStream(0)
{
}
HTTPClientSession::~HTTPClientSession()
{
delete _pRequestStream;
delete _pResponseStream;
}
void HTTPClientSession::setHost(const std::string& host)
{
if (!connected())
_host = host;
else
throw IllegalStateException("Cannot set the host for an already connected session");
}
void HTTPClientSession::setPort(Poco::UInt16 port)
{
if (!connected())
_port = port;
else
throw IllegalStateException("Cannot set the port number for an already connected session");
}
void HTTPClientSession::setProxy(const std::string& host, Poco::UInt16 port)
{
if (!connected())
{
_proxyHost = host;
_proxyPort = port;
}
else throw IllegalStateException("Cannot set the proxy host and port for an already connected session");
}
void HTTPClientSession::setProxyHost(const std::string& host)
{
if (!connected())
_proxyHost = host;
else
throw IllegalStateException("Cannot set the proxy host for an already connected session");
}
void HTTPClientSession::setProxyPort(Poco::UInt16 port)
{
if (!connected())
_proxyPort = port;
else
throw IllegalStateException("Cannot set the proxy port number for an already connected session");
}
std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
{
delete _pResponseStream;
_pResponseStream = 0;
bool keepAlive = getKeepAlive();
if (connected() && !keepAlive)
close();
if (!connected())
reconnect();
request.setKeepAlive(keepAlive);
request.setHost(_host, _port);
if (!_proxyHost.empty())
request.setURI(getHostInfo() + request.getURI());
HTTPHeaderOutputStream hos(*this);
_reconnect = keepAlive;
request.write(hos);
_reconnect = false;
_expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD;
if (request.getChunkedTransferEncoding())
_pRequestStream = new HTTPChunkedOutputStream(*this);
else if (request.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength());
else if (request.getMethod() == HTTPRequest::HTTP_GET || request.getMethod() == HTTPRequest::HTTP_HEAD)
_pRequestStream = new HTTPFixedLengthOutputStream(*this, 0);
else
_pRequestStream = new HTTPOutputStream(*this);
return *_pRequestStream;
}
std::istream& HTTPClientSession::receiveResponse(HTTPResponse& response)
{
delete _pRequestStream;
_pRequestStream = 0;
do
{
response.clear();
HTTPHeaderInputStream his(*this);
try
{
response.read(his);
}
catch (MessageException&)
{
if (networkException())
networkException()->rethrow();
else
throw;
}
}
while (response.getStatus() == HTTPResponse::HTTP_CONTINUE);
if (!_expectResponseBody)
_pResponseStream = new HTTPFixedLengthInputStream(*this, 0);
else if (response.getChunkedTransferEncoding())
_pResponseStream = new HTTPChunkedInputStream(*this);
else if (response.getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pResponseStream = new HTTPFixedLengthInputStream(*this, response.getContentLength());
else
_pResponseStream = new HTTPInputStream(*this);
return *_pResponseStream;
}
int HTTPClientSession::write(const char* buffer, std::streamsize length)
{
try
{
return HTTPSession::write(buffer, length);
}
catch (NetException&)
{
if (_reconnect)
{
close();
reconnect();
return HTTPSession::write(buffer, length);
}
else throw;
}
}
void HTTPClientSession::reconnect()
{
if (_proxyHost.empty())
{
SocketAddress addr(_host, _port);
connect(addr);
}
else
{
SocketAddress addr(_proxyHost, _proxyPort);
connect(addr);
}
}
std::string HTTPClientSession::getHostInfo() const
{
std::string result("http://");
result.append(_host);
result.append(":");
result.append(NumberFormatter::format(_port));
return result;
}
void HTTPClientSession::deleteResponseStream()
{
delete _pResponseStream;
_pResponseStream = 0;
}
void HTTPClientSession::deleteRequestStream()
{
delete _pRequestStream;
_pRequestStream = 0;
}
void HTTPClientSession::setResponseStream(std::istream* pRespStream)
{
poco_assert( !_pResponseStream);
_pResponseStream = pRespStream;
}
void HTTPClientSession::setRequestStream(std::ostream* pRequestStream)
{
poco_assert (!_pRequestStream);
_pRequestStream = pRequestStream;
}
} } // namespace Poco::Net

View File

@@ -1,292 +1,292 @@
//
// HTTPCookie.cpp
//
// $Id: //poco/1.2/Net/src/HTTPCookie.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPCookie
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPCookie.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeParser.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/String.h"
using Poco::Timestamp;
using Poco::DateTime;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::DateTimeParser;
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::icompare;
namespace Poco {
namespace Net {
HTTPCookie::HTTPCookie():
_version(0),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const std::string& name):
_version(0),
_name(name),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const NameValueCollection& nvc):
_version(0),
_secure(false),
_maxAge(-1)
{
for (NameValueCollection::ConstIterator it = nvc.begin(); it != nvc.end(); ++it)
{
const std::string& name = it->first;
const std::string& value = it->second;
if (icompare(name, "comment") == 0)
{
setComment(value);
}
else if (icompare(name, "domain") == 0)
{
setDomain(value);
}
else if (icompare(name, "path") == 0)
{
setPath(value);
}
else if (icompare(name, "max-age") == 0)
{
setMaxAge(NumberParser::parse(value));
}
else if (icompare(name, "secure") == 0)
{
setSecure(true);
}
else if (icompare(name, "expires") == 0)
{
int tzd;
DateTime exp = DateTimeParser::parse(value, tzd);
Timestamp now;
setMaxAge((int) ((exp.timestamp() - now)/1000000));
}
else if (icompare(name, "version") == 0)
{
setVersion(NumberParser::parse(value));
}
else
{
setName(name);
setValue(value);
}
}
}
HTTPCookie::HTTPCookie(const std::string& name, const std::string& value):
_version(0),
_name(name),
_value(value),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const HTTPCookie& cookie):
_version(cookie._version),
_name(cookie._name),
_value(cookie._value),
_comment(cookie._comment),
_domain(cookie._domain),
_path(cookie._path),
_secure(cookie._secure),
_maxAge(cookie._maxAge)
{
}
HTTPCookie::~HTTPCookie()
{
}
HTTPCookie& HTTPCookie::operator = (const HTTPCookie& cookie)
{
if (&cookie != this)
{
_version = cookie._version;
_name = cookie._name;
_value = cookie._value;
_comment = cookie._comment;
_domain = cookie._domain;
_path = cookie._path;
_secure = cookie._secure;
_maxAge = cookie._maxAge;
}
return *this;
}
void HTTPCookie::setVersion(int version)
{
_version = version;
}
void HTTPCookie::setName(const std::string& name)
{
_name = name;
}
void HTTPCookie::setValue(const std::string& value)
{
_value = value;
}
void HTTPCookie::setComment(const std::string& comment)
{
_comment = comment;
}
void HTTPCookie::setDomain(const std::string& domain)
{
_domain = domain;
}
void HTTPCookie::setPath(const std::string& path)
{
_path = path;
}
void HTTPCookie::setSecure(bool secure)
{
_secure = secure;
}
void HTTPCookie::setMaxAge(int maxAge)
{
_maxAge = maxAge;
}
std::string HTTPCookie::toString() const
{
std::string result(_name);
result.append("=");
if (_version == 0)
{
// Netscape cookie
result.append(_value);
if (!_domain.empty())
{
result.append("; domain=");
result.append(_domain);
}
if (!_path.empty())
{
result.append("; path=");
result.append(_path);
}
if (_maxAge >= 0)
{
Timestamp ts;
ts += _maxAge*1000000;
result.append("; expires=");
result.append(DateTimeFormatter::format(ts, DateTimeFormat::RFC850_FORMAT));
}
if (_secure)
{
result.append("; secure");
}
}
else
{
// RFC 2109 cookie
result.append("\"");
result.append(_value);
result.append("\"");
if (!_comment.empty())
{
result.append("; Comment=\"");
result.append(_comment);
result.append("\"");
}
if (!_domain.empty())
{
result.append("; Domain=\"");
result.append(_domain);
result.append("\"");
}
if (!_path.empty())
{
result.append("; Path=\"");
result.append(_path);
result.append("\"");
}
if (_maxAge >= 0)
{
result.append("; Max-Age=\"");
result.append(NumberFormatter::format(_maxAge));
result.append("\"");
}
if (_secure)
{
result.append("; secure");
}
result.append("; Version=\"1\"");
}
return result;
}
} } // namespace Poco::Net
//
// HTTPCookie.cpp
//
// $Id: //poco/1.2/Net/src/HTTPCookie.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPCookie
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPCookie.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeParser.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/String.h"
using Poco::Timestamp;
using Poco::DateTime;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::DateTimeParser;
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::icompare;
namespace Poco {
namespace Net {
HTTPCookie::HTTPCookie():
_version(0),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const std::string& name):
_version(0),
_name(name),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const NameValueCollection& nvc):
_version(0),
_secure(false),
_maxAge(-1)
{
for (NameValueCollection::ConstIterator it = nvc.begin(); it != nvc.end(); ++it)
{
const std::string& name = it->first;
const std::string& value = it->second;
if (icompare(name, "comment") == 0)
{
setComment(value);
}
else if (icompare(name, "domain") == 0)
{
setDomain(value);
}
else if (icompare(name, "path") == 0)
{
setPath(value);
}
else if (icompare(name, "max-age") == 0)
{
setMaxAge(NumberParser::parse(value));
}
else if (icompare(name, "secure") == 0)
{
setSecure(true);
}
else if (icompare(name, "expires") == 0)
{
int tzd;
DateTime exp = DateTimeParser::parse(value, tzd);
Timestamp now;
setMaxAge((int) ((exp.timestamp() - now)/1000000));
}
else if (icompare(name, "version") == 0)
{
setVersion(NumberParser::parse(value));
}
else
{
setName(name);
setValue(value);
}
}
}
HTTPCookie::HTTPCookie(const std::string& name, const std::string& value):
_version(0),
_name(name),
_value(value),
_secure(false),
_maxAge(-1)
{
}
HTTPCookie::HTTPCookie(const HTTPCookie& cookie):
_version(cookie._version),
_name(cookie._name),
_value(cookie._value),
_comment(cookie._comment),
_domain(cookie._domain),
_path(cookie._path),
_secure(cookie._secure),
_maxAge(cookie._maxAge)
{
}
HTTPCookie::~HTTPCookie()
{
}
HTTPCookie& HTTPCookie::operator = (const HTTPCookie& cookie)
{
if (&cookie != this)
{
_version = cookie._version;
_name = cookie._name;
_value = cookie._value;
_comment = cookie._comment;
_domain = cookie._domain;
_path = cookie._path;
_secure = cookie._secure;
_maxAge = cookie._maxAge;
}
return *this;
}
void HTTPCookie::setVersion(int version)
{
_version = version;
}
void HTTPCookie::setName(const std::string& name)
{
_name = name;
}
void HTTPCookie::setValue(const std::string& value)
{
_value = value;
}
void HTTPCookie::setComment(const std::string& comment)
{
_comment = comment;
}
void HTTPCookie::setDomain(const std::string& domain)
{
_domain = domain;
}
void HTTPCookie::setPath(const std::string& path)
{
_path = path;
}
void HTTPCookie::setSecure(bool secure)
{
_secure = secure;
}
void HTTPCookie::setMaxAge(int maxAge)
{
_maxAge = maxAge;
}
std::string HTTPCookie::toString() const
{
std::string result(_name);
result.append("=");
if (_version == 0)
{
// Netscape cookie
result.append(_value);
if (!_domain.empty())
{
result.append("; domain=");
result.append(_domain);
}
if (!_path.empty())
{
result.append("; path=");
result.append(_path);
}
if (_maxAge >= 0)
{
Timestamp ts;
ts += _maxAge*1000000;
result.append("; expires=");
result.append(DateTimeFormatter::format(ts, DateTimeFormat::RFC850_FORMAT));
}
if (_secure)
{
result.append("; secure");
}
}
else
{
// RFC 2109 cookie
result.append("\"");
result.append(_value);
result.append("\"");
if (!_comment.empty())
{
result.append("; Comment=\"");
result.append(_comment);
result.append("\"");
}
if (!_domain.empty())
{
result.append("; Domain=\"");
result.append(_domain);
result.append("\"");
}
if (!_path.empty())
{
result.append("; Path=\"");
result.append(_path);
result.append("\"");
}
if (_maxAge >= 0)
{
result.append("; Max-Age=\"");
result.append(NumberFormatter::format(_maxAge));
result.append("\"");
}
if (_secure)
{
result.append("; secure");
}
result.append("; Version=\"1\"");
}
return result;
}
} } // namespace Poco::Net

View File

@@ -1,189 +1,189 @@
//
// HTTPFixedLengthStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPFixedLengthStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPFixedLengthStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPSession.h"
using Poco::BufferedStreamBuf;
namespace Poco {
namespace Net {
//
// HTTPFixedLengthStreamBuf
//
HTTPFixedLengthStreamBuf::HTTPFixedLengthStreamBuf(HTTPSession& session, std::streamsize length, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_length(length),
_count(0)
{
}
HTTPFixedLengthStreamBuf::~HTTPFixedLengthStreamBuf()
{
}
int HTTPFixedLengthStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
int n = 0;
if (_count < _length)
{
if (_count + length > _length)
length = _length - _count;
n = _session.read(buffer, length);
if (n > 0) _count += n;
}
return n;
}
int HTTPFixedLengthStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
int n = 0;
if (_count < _length)
{
if (_count + length > _length)
length = _length - _count;
n = _session.write(buffer, length);
if (n > 0) _count += n;
}
return n;
}
//
// HTTPFixedLengthIOS
//
HTTPFixedLengthIOS::HTTPFixedLengthIOS(HTTPSession& session, std::streamsize length, HTTPFixedLengthStreamBuf::openmode mode):
_buf(session, length, mode)
{
poco_ios_init(&_buf);
}
HTTPFixedLengthIOS::~HTTPFixedLengthIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
HTTPFixedLengthStreamBuf* HTTPFixedLengthIOS::rdbuf()
{
return &_buf;
}
//
// HTTPFixedLengthInputStream
//
Poco::MemoryPool HTTPFixedLengthInputStream::_pool(sizeof(HTTPFixedLengthInputStream));
HTTPFixedLengthInputStream::HTTPFixedLengthInputStream(HTTPSession& session, std::streamsize length):
HTTPFixedLengthIOS(session, length, std::ios::in),
std::istream(&_buf)
{
}
HTTPFixedLengthInputStream::~HTTPFixedLengthInputStream()
{
}
void* HTTPFixedLengthInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPFixedLengthInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPFixedLengthOutputStream
//
Poco::MemoryPool HTTPFixedLengthOutputStream::_pool(sizeof(HTTPFixedLengthOutputStream));
HTTPFixedLengthOutputStream::HTTPFixedLengthOutputStream(HTTPSession& session, std::streamsize length):
HTTPFixedLengthIOS(session, length, std::ios::out),
std::ostream(&_buf)
{
}
HTTPFixedLengthOutputStream::~HTTPFixedLengthOutputStream()
{
}
void* HTTPFixedLengthOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPFixedLengthOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net
//
// HTTPFixedLengthStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPFixedLengthStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPFixedLengthStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPSession.h"
using Poco::BufferedStreamBuf;
namespace Poco {
namespace Net {
//
// HTTPFixedLengthStreamBuf
//
HTTPFixedLengthStreamBuf::HTTPFixedLengthStreamBuf(HTTPSession& session, std::streamsize length, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_length(length),
_count(0)
{
}
HTTPFixedLengthStreamBuf::~HTTPFixedLengthStreamBuf()
{
}
int HTTPFixedLengthStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
int n = 0;
if (_count < _length)
{
if (_count + length > _length)
length = _length - _count;
n = _session.read(buffer, length);
if (n > 0) _count += n;
}
return n;
}
int HTTPFixedLengthStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
int n = 0;
if (_count < _length)
{
if (_count + length > _length)
length = _length - _count;
n = _session.write(buffer, length);
if (n > 0) _count += n;
}
return n;
}
//
// HTTPFixedLengthIOS
//
HTTPFixedLengthIOS::HTTPFixedLengthIOS(HTTPSession& session, std::streamsize length, HTTPFixedLengthStreamBuf::openmode mode):
_buf(session, length, mode)
{
poco_ios_init(&_buf);
}
HTTPFixedLengthIOS::~HTTPFixedLengthIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
HTTPFixedLengthStreamBuf* HTTPFixedLengthIOS::rdbuf()
{
return &_buf;
}
//
// HTTPFixedLengthInputStream
//
Poco::MemoryPool HTTPFixedLengthInputStream::_pool(sizeof(HTTPFixedLengthInputStream));
HTTPFixedLengthInputStream::HTTPFixedLengthInputStream(HTTPSession& session, std::streamsize length):
HTTPFixedLengthIOS(session, length, std::ios::in),
std::istream(&_buf)
{
}
HTTPFixedLengthInputStream::~HTTPFixedLengthInputStream()
{
}
void* HTTPFixedLengthInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPFixedLengthInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPFixedLengthOutputStream
//
Poco::MemoryPool HTTPFixedLengthOutputStream::_pool(sizeof(HTTPFixedLengthOutputStream));
HTTPFixedLengthOutputStream::HTTPFixedLengthOutputStream(HTTPSession& session, std::streamsize length):
HTTPFixedLengthIOS(session, length, std::ios::out),
std::ostream(&_buf)
{
}
HTTPFixedLengthOutputStream::~HTTPFixedLengthOutputStream()
{
}
void* HTTPFixedLengthOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPFixedLengthOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net

View File

@@ -1,186 +1,186 @@
//
// HTTPHeaderStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPHeaderStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPHeaderStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPSession.h"
namespace Poco {
namespace Net {
//
// HTTPHeaderStreamBuf
//
HTTPHeaderStreamBuf::HTTPHeaderStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_end(false)
{
}
HTTPHeaderStreamBuf::~HTTPHeaderStreamBuf()
{
}
int HTTPHeaderStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
// read line-by-line; an empty line denotes the end of the headers.
static const int eof = std::char_traits<char>::eof();
if (_end) return 0;
int n = 0;
int ch = _session.get();
while (ch != eof && ch != '\n' && n < length - 1)
{
*buffer++ = (char) ch; ++n;
ch = _session.get();
}
if (ch != eof)
{
*buffer++ = (char) ch; ++n;
if (n == 2) _end = true;
}
return n;
}
int HTTPHeaderStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _session.write(buffer, length);
}
//
// HTTPHeaderIOS
//
HTTPHeaderIOS::HTTPHeaderIOS(HTTPSession& session, HTTPHeaderStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPHeaderIOS::~HTTPHeaderIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
HTTPHeaderStreamBuf* HTTPHeaderIOS::rdbuf()
{
return &_buf;
}
//
// HTTPHeaderInputStream
//
Poco::MemoryPool HTTPHeaderInputStream::_pool(sizeof(HTTPHeaderInputStream));
HTTPHeaderInputStream::HTTPHeaderInputStream(HTTPSession& session):
HTTPHeaderIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPHeaderInputStream::~HTTPHeaderInputStream()
{
}
void* HTTPHeaderInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPHeaderInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPHeaderOutputStream
//
Poco::MemoryPool HTTPHeaderOutputStream::_pool(sizeof(HTTPHeaderOutputStream));
HTTPHeaderOutputStream::HTTPHeaderOutputStream(HTTPSession& session):
HTTPHeaderIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPHeaderOutputStream::~HTTPHeaderOutputStream()
{
}
void* HTTPHeaderOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPHeaderOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net
//
// HTTPHeaderStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPHeaderStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPHeaderStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPSession.h"
namespace Poco {
namespace Net {
//
// HTTPHeaderStreamBuf
//
HTTPHeaderStreamBuf::HTTPHeaderStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_end(false)
{
}
HTTPHeaderStreamBuf::~HTTPHeaderStreamBuf()
{
}
int HTTPHeaderStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
// read line-by-line; an empty line denotes the end of the headers.
static const int eof = std::char_traits<char>::eof();
if (_end) return 0;
int n = 0;
int ch = _session.get();
while (ch != eof && ch != '\n' && n < length - 1)
{
*buffer++ = (char) ch; ++n;
ch = _session.get();
}
if (ch != eof)
{
*buffer++ = (char) ch; ++n;
if (n == 2) _end = true;
}
return n;
}
int HTTPHeaderStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _session.write(buffer, length);
}
//
// HTTPHeaderIOS
//
HTTPHeaderIOS::HTTPHeaderIOS(HTTPSession& session, HTTPHeaderStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPHeaderIOS::~HTTPHeaderIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
HTTPHeaderStreamBuf* HTTPHeaderIOS::rdbuf()
{
return &_buf;
}
//
// HTTPHeaderInputStream
//
Poco::MemoryPool HTTPHeaderInputStream::_pool(sizeof(HTTPHeaderInputStream));
HTTPHeaderInputStream::HTTPHeaderInputStream(HTTPSession& session):
HTTPHeaderIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPHeaderInputStream::~HTTPHeaderInputStream()
{
}
void* HTTPHeaderInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPHeaderInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPHeaderOutputStream
//
Poco::MemoryPool HTTPHeaderOutputStream::_pool(sizeof(HTTPHeaderOutputStream));
HTTPHeaderOutputStream::HTTPHeaderOutputStream(HTTPSession& session):
HTTPHeaderIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPHeaderOutputStream::~HTTPHeaderOutputStream()
{
}
void* HTTPHeaderOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPHeaderOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net

View File

@@ -1,85 +1,85 @@
//
// HTTPIOStream.cpp
//
// $Id: //poco/Main/template/class.cpp#5 $
//
// Library: Net
// Package: HTTP
// Module: HTTPIOStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPClientSession.h"
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPResponseStreamBuf::HTTPResponseStreamBuf(std::istream& istr):
_istr(istr)
{
}
HTTPResponseStreamBuf::~HTTPResponseStreamBuf()
{
}
HTTPResponseIOS::HTTPResponseIOS(std::istream& istr):
_buf(istr)
{
poco_ios_init(&_buf);
}
HTTPResponseIOS::~HTTPResponseIOS()
{
}
HTTPResponseStream::HTTPResponseStream(std::istream& istr, HTTPClientSession* pSession):
HTTPResponseIOS(istr),
std::istream(&_buf),
_pSession(pSession)
{
}
HTTPResponseStream::~HTTPResponseStream()
{
delete _pSession;
}
} } // namespace Poco::Net
//
// HTTPIOStream.cpp
//
// $Id: //poco/Main/template/class.cpp#5 $
//
// Library: Net
// Package: HTTP
// Module: HTTPIOStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPClientSession.h"
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPResponseStreamBuf::HTTPResponseStreamBuf(std::istream& istr):
_istr(istr)
{
}
HTTPResponseStreamBuf::~HTTPResponseStreamBuf()
{
}
HTTPResponseIOS::HTTPResponseIOS(std::istream& istr):
_buf(istr)
{
poco_ios_init(&_buf);
}
HTTPResponseIOS::~HTTPResponseIOS()
{
}
HTTPResponseStream::HTTPResponseStream(std::istream& istr, HTTPClientSession* pSession):
HTTPResponseIOS(istr),
std::istream(&_buf),
_pSession(pSession)
{
}
HTTPResponseStream::~HTTPResponseStream()
{
delete _pSession;
}
} } // namespace Poco::Net

View File

@@ -1,183 +1,183 @@
//
// HTTPMessage.cpp
//
// $Id: //poco/1.2/Net/src/HTTPMessage.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPMessage
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/MediaType.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/String.h"
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTTPMessage::HTTP_1_0 = "HTTP/1.0";
const std::string HTTPMessage::HTTP_1_1 = "HTTP/1.1";
const std::string HTTPMessage::IDENTITY_TRANSFER_ENCODING = "identity";
const std::string HTTPMessage::CHUNKED_TRANSFER_ENCODING = "chunked";
const int HTTPMessage::UNKNOWN_CONTENT_LENGTH = -1;
const std::string HTTPMessage::UNKNOWN_CONTENT_TYPE;
const std::string HTTPMessage::CONTENT_LENGTH = "Content-Length";
const std::string HTTPMessage::CONTENT_TYPE = "Content-Type";
const std::string HTTPMessage::TRANSFER_ENCODING = "Transfer-Encoding";
const std::string HTTPMessage::CONNECTION = "Connection";
const std::string HTTPMessage::CONNECTION_KEEP_ALIVE = "Keep-Alive";
const std::string HTTPMessage::CONNECTION_CLOSE = "Close";
HTTPMessage::HTTPMessage():
_version(HTTP_1_0)
{
}
HTTPMessage::HTTPMessage(const std::string& version):
_version(version)
{
}
HTTPMessage::~HTTPMessage()
{
}
void HTTPMessage::setVersion(const std::string& version)
{
_version = version;
}
void HTTPMessage::setContentLength(int length)
{
if (length != UNKNOWN_CONTENT_LENGTH)
set(CONTENT_LENGTH, NumberFormatter::format(length));
else
erase(CONTENT_LENGTH);
}
int HTTPMessage::getContentLength() const
{
if (has(CONTENT_LENGTH))
return NumberParser::parse(get(CONTENT_LENGTH));
else
return UNKNOWN_CONTENT_LENGTH;
}
void HTTPMessage::setTransferEncoding(const std::string& transferEncoding)
{
if (icompare(transferEncoding, IDENTITY_TRANSFER_ENCODING) == 0)
erase(TRANSFER_ENCODING);
else
set(TRANSFER_ENCODING, transferEncoding);
}
const std::string& HTTPMessage::getTransferEncoding() const
{
if (has(TRANSFER_ENCODING))
return get(TRANSFER_ENCODING);
else
return IDENTITY_TRANSFER_ENCODING;
}
void HTTPMessage::setChunkedTransferEncoding(bool flag)
{
if (flag)
setTransferEncoding(CHUNKED_TRANSFER_ENCODING);
else
setTransferEncoding(IDENTITY_TRANSFER_ENCODING);
}
bool HTTPMessage::getChunkedTransferEncoding() const
{
return icompare(getTransferEncoding(), CHUNKED_TRANSFER_ENCODING) == 0;
}
void HTTPMessage::setContentType(const std::string& mediaType)
{
if (mediaType.empty())
erase(CONTENT_TYPE);
else
set(CONTENT_TYPE, mediaType);
}
void HTTPMessage::setContentType(const MediaType& mediaType)
{
setContentType(mediaType.toString());
}
const std::string& HTTPMessage::getContentType() const
{
if (has(CONTENT_TYPE))
return get(CONTENT_TYPE);
else
return UNKNOWN_CONTENT_TYPE;
}
void HTTPMessage::setKeepAlive(bool keepAlive)
{
if (keepAlive)
set(CONNECTION, CONNECTION_KEEP_ALIVE);
else
set(CONNECTION, CONNECTION_CLOSE);
}
bool HTTPMessage::getKeepAlive() const
{
if (has(CONNECTION))
return icompare(get(CONNECTION), CONNECTION_KEEP_ALIVE) == 0;
else
return getVersion() == HTTP_1_1;
}
} } // namespace Poco::Net
//
// HTTPMessage.cpp
//
// $Id: //poco/1.2/Net/src/HTTPMessage.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPMessage
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/MediaType.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/String.h"
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::icompare;
namespace Poco {
namespace Net {
const std::string HTTPMessage::HTTP_1_0 = "HTTP/1.0";
const std::string HTTPMessage::HTTP_1_1 = "HTTP/1.1";
const std::string HTTPMessage::IDENTITY_TRANSFER_ENCODING = "identity";
const std::string HTTPMessage::CHUNKED_TRANSFER_ENCODING = "chunked";
const int HTTPMessage::UNKNOWN_CONTENT_LENGTH = -1;
const std::string HTTPMessage::UNKNOWN_CONTENT_TYPE;
const std::string HTTPMessage::CONTENT_LENGTH = "Content-Length";
const std::string HTTPMessage::CONTENT_TYPE = "Content-Type";
const std::string HTTPMessage::TRANSFER_ENCODING = "Transfer-Encoding";
const std::string HTTPMessage::CONNECTION = "Connection";
const std::string HTTPMessage::CONNECTION_KEEP_ALIVE = "Keep-Alive";
const std::string HTTPMessage::CONNECTION_CLOSE = "Close";
HTTPMessage::HTTPMessage():
_version(HTTP_1_0)
{
}
HTTPMessage::HTTPMessage(const std::string& version):
_version(version)
{
}
HTTPMessage::~HTTPMessage()
{
}
void HTTPMessage::setVersion(const std::string& version)
{
_version = version;
}
void HTTPMessage::setContentLength(int length)
{
if (length != UNKNOWN_CONTENT_LENGTH)
set(CONTENT_LENGTH, NumberFormatter::format(length));
else
erase(CONTENT_LENGTH);
}
int HTTPMessage::getContentLength() const
{
if (has(CONTENT_LENGTH))
return NumberParser::parse(get(CONTENT_LENGTH));
else
return UNKNOWN_CONTENT_LENGTH;
}
void HTTPMessage::setTransferEncoding(const std::string& transferEncoding)
{
if (icompare(transferEncoding, IDENTITY_TRANSFER_ENCODING) == 0)
erase(TRANSFER_ENCODING);
else
set(TRANSFER_ENCODING, transferEncoding);
}
const std::string& HTTPMessage::getTransferEncoding() const
{
if (has(TRANSFER_ENCODING))
return get(TRANSFER_ENCODING);
else
return IDENTITY_TRANSFER_ENCODING;
}
void HTTPMessage::setChunkedTransferEncoding(bool flag)
{
if (flag)
setTransferEncoding(CHUNKED_TRANSFER_ENCODING);
else
setTransferEncoding(IDENTITY_TRANSFER_ENCODING);
}
bool HTTPMessage::getChunkedTransferEncoding() const
{
return icompare(getTransferEncoding(), CHUNKED_TRANSFER_ENCODING) == 0;
}
void HTTPMessage::setContentType(const std::string& mediaType)
{
if (mediaType.empty())
erase(CONTENT_TYPE);
else
set(CONTENT_TYPE, mediaType);
}
void HTTPMessage::setContentType(const MediaType& mediaType)
{
setContentType(mediaType.toString());
}
const std::string& HTTPMessage::getContentType() const
{
if (has(CONTENT_TYPE))
return get(CONTENT_TYPE);
else
return UNKNOWN_CONTENT_TYPE;
}
void HTTPMessage::setKeepAlive(bool keepAlive)
{
if (keepAlive)
set(CONNECTION, CONNECTION_KEEP_ALIVE);
else
set(CONNECTION, CONNECTION_CLOSE);
}
bool HTTPMessage::getKeepAlive() const
{
if (has(CONNECTION))
return icompare(get(CONNECTION), CONNECTION_KEEP_ALIVE) == 0;
else
return getVersion() == HTTP_1_1;
}
} } // namespace Poco::Net

View File

@@ -1,231 +1,231 @@
//
// HTTPRequest.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequest.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPRequest
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/NumberFormatter.h"
#include <ctype.h>
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
const std::string HTTPRequest::HTTP_GET = "GET";
const std::string HTTPRequest::HTTP_HEAD = "HEAD";
const std::string HTTPRequest::HTTP_PUT = "PUT";
const std::string HTTPRequest::HTTP_POST = "POST";
const std::string HTTPRequest::HTTP_OPTIONS = "OPTIONS";
const std::string HTTPRequest::HTTP_DELETE = "DELETE";
const std::string HTTPRequest::HTTP_TRACE = "TRACE";
const std::string HTTPRequest::HTTP_CONNECT = "CONNECT";
const std::string HTTPRequest::HOST = "Host";
const std::string HTTPRequest::COOKIE = "Cookie";
const std::string HTTPRequest::AUTHORIZATION = "Authorization";
HTTPRequest::HTTPRequest():
_method(HTTP_GET),
_uri("/")
{
}
HTTPRequest::HTTPRequest(const std::string& version):
HTTPMessage(version),
_method(HTTP_GET),
_uri("/")
{
}
HTTPRequest::HTTPRequest(const std::string& method, const std::string& uri):
_method(method),
_uri(uri)
{
}
HTTPRequest::HTTPRequest(const std::string& method, const std::string& uri, const std::string& version):
HTTPMessage(version),
_method(method),
_uri(uri)
{
}
HTTPRequest::~HTTPRequest()
{
}
void HTTPRequest::setMethod(const std::string& method)
{
_method = method;
}
void HTTPRequest::setURI(const std::string& uri)
{
_uri = uri;
}
void HTTPRequest::setHost(const std::string& host)
{
set(HOST, host);
}
void HTTPRequest::setHost(const std::string& host, Poco::UInt16 port)
{
std::string value(host);
if (port != HTTPSession::HTTP_PORT)
{
value.append(":");
value.append(NumberFormatter::format(port));
}
setHost(value);
}
const std::string& HTTPRequest::getHost() const
{
return get(HOST);
}
void HTTPRequest::setCookies(const NameValueCollection& cookies)
{
std::string cookie;
for (NameValueCollection::ConstIterator it = cookies.begin(); it != cookies.end(); ++it)
{
if (it != cookies.begin())
cookie.append("; ");
cookie.append(it->first);
cookie.append("=");
cookie.append(it->second);
}
add(COOKIE, cookie);
}
void HTTPRequest::getCookies(NameValueCollection& cookies) const
{
NameValueCollection::ConstIterator it = find(COOKIE);
while (it != end() && it->first == COOKIE)
{
splitParameters(it->second.begin(), it->second.end(), cookies);
++it;
}
}
bool HTTPRequest::hasCredentials() const
{
return has(AUTHORIZATION);
}
void HTTPRequest::getCredentials(std::string& scheme, std::string& authInfo) const
{
scheme.clear();
authInfo.clear();
if (has(AUTHORIZATION))
{
const std::string& auth = get(AUTHORIZATION);
std::string::const_iterator it = auth.begin();
std::string::const_iterator end = auth.end();
while (it != end && isspace(*it)) ++it;
while (it != end && !isspace(*it)) scheme += *it++;
while (it != end && isspace(*it)) ++it;
while (it != end) authInfo += *it++;
}
else throw NotAuthenticatedException();
}
void HTTPRequest::setCredentials(const std::string& scheme, const std::string& authInfo)
{
std::string auth(scheme);
auth.append(" ");
auth.append(authInfo);
set(AUTHORIZATION, auth);
}
void HTTPRequest::write(std::ostream& ostr) const
{
ostr << _method << " " << _uri << " " << getVersion() << "\r\n";
HTTPMessage::write(ostr);
ostr << "\r\n";
}
void HTTPRequest::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
std::string method;
std::string uri;
std::string version;
int ch = istr.get();
while (isspace(ch)) ch = istr.get();
if (ch == eof) throw MessageException("No HTTP request header");
while (!isspace(ch) && ch != eof && method.length() < MAX_METHOD_LENGTH) { method += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP request method too long");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && uri.length() < MAX_URI_LENGTH) { uri += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP request URI too long");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && version.length() < MAX_VERSION_LENGTH) { version += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP version string");
while (ch != '\n' && ch != eof) { ch = istr.get(); }
HTTPMessage::read(istr);
ch = istr.get();
while (ch != '\n' && ch != eof) { ch = istr.get(); }
setMethod(method);
setURI(uri);
setVersion(version);
}
} } // namespace Poco::Net
//
// HTTPRequest.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequest.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPRequest
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/NumberFormatter.h"
#include <ctype.h>
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
const std::string HTTPRequest::HTTP_GET = "GET";
const std::string HTTPRequest::HTTP_HEAD = "HEAD";
const std::string HTTPRequest::HTTP_PUT = "PUT";
const std::string HTTPRequest::HTTP_POST = "POST";
const std::string HTTPRequest::HTTP_OPTIONS = "OPTIONS";
const std::string HTTPRequest::HTTP_DELETE = "DELETE";
const std::string HTTPRequest::HTTP_TRACE = "TRACE";
const std::string HTTPRequest::HTTP_CONNECT = "CONNECT";
const std::string HTTPRequest::HOST = "Host";
const std::string HTTPRequest::COOKIE = "Cookie";
const std::string HTTPRequest::AUTHORIZATION = "Authorization";
HTTPRequest::HTTPRequest():
_method(HTTP_GET),
_uri("/")
{
}
HTTPRequest::HTTPRequest(const std::string& version):
HTTPMessage(version),
_method(HTTP_GET),
_uri("/")
{
}
HTTPRequest::HTTPRequest(const std::string& method, const std::string& uri):
_method(method),
_uri(uri)
{
}
HTTPRequest::HTTPRequest(const std::string& method, const std::string& uri, const std::string& version):
HTTPMessage(version),
_method(method),
_uri(uri)
{
}
HTTPRequest::~HTTPRequest()
{
}
void HTTPRequest::setMethod(const std::string& method)
{
_method = method;
}
void HTTPRequest::setURI(const std::string& uri)
{
_uri = uri;
}
void HTTPRequest::setHost(const std::string& host)
{
set(HOST, host);
}
void HTTPRequest::setHost(const std::string& host, Poco::UInt16 port)
{
std::string value(host);
if (port != HTTPSession::HTTP_PORT)
{
value.append(":");
value.append(NumberFormatter::format(port));
}
setHost(value);
}
const std::string& HTTPRequest::getHost() const
{
return get(HOST);
}
void HTTPRequest::setCookies(const NameValueCollection& cookies)
{
std::string cookie;
for (NameValueCollection::ConstIterator it = cookies.begin(); it != cookies.end(); ++it)
{
if (it != cookies.begin())
cookie.append("; ");
cookie.append(it->first);
cookie.append("=");
cookie.append(it->second);
}
add(COOKIE, cookie);
}
void HTTPRequest::getCookies(NameValueCollection& cookies) const
{
NameValueCollection::ConstIterator it = find(COOKIE);
while (it != end() && it->first == COOKIE)
{
splitParameters(it->second.begin(), it->second.end(), cookies);
++it;
}
}
bool HTTPRequest::hasCredentials() const
{
return has(AUTHORIZATION);
}
void HTTPRequest::getCredentials(std::string& scheme, std::string& authInfo) const
{
scheme.clear();
authInfo.clear();
if (has(AUTHORIZATION))
{
const std::string& auth = get(AUTHORIZATION);
std::string::const_iterator it = auth.begin();
std::string::const_iterator end = auth.end();
while (it != end && isspace(*it)) ++it;
while (it != end && !isspace(*it)) scheme += *it++;
while (it != end && isspace(*it)) ++it;
while (it != end) authInfo += *it++;
}
else throw NotAuthenticatedException();
}
void HTTPRequest::setCredentials(const std::string& scheme, const std::string& authInfo)
{
std::string auth(scheme);
auth.append(" ");
auth.append(authInfo);
set(AUTHORIZATION, auth);
}
void HTTPRequest::write(std::ostream& ostr) const
{
ostr << _method << " " << _uri << " " << getVersion() << "\r\n";
HTTPMessage::write(ostr);
ostr << "\r\n";
}
void HTTPRequest::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
std::string method;
std::string uri;
std::string version;
int ch = istr.get();
while (isspace(ch)) ch = istr.get();
if (ch == eof) throw MessageException("No HTTP request header");
while (!isspace(ch) && ch != eof && method.length() < MAX_METHOD_LENGTH) { method += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP request method too long");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && uri.length() < MAX_URI_LENGTH) { uri += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP request URI too long");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && version.length() < MAX_VERSION_LENGTH) { version += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP version string");
while (ch != '\n' && ch != eof) { ch = istr.get(); }
HTTPMessage::read(istr);
ch = istr.get();
while (ch != '\n' && ch != eof) { ch = istr.get(); }
setMethod(method);
setURI(uri);
setVersion(version);
}
} } // namespace Poco::Net

View File

@@ -1,54 +1,54 @@
//
// HTTPRequestHandler.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequestHandler.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPRequestHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequestHandler.h"
namespace Poco {
namespace Net {
HTTPRequestHandler::HTTPRequestHandler()
{
}
HTTPRequestHandler::~HTTPRequestHandler()
{
}
} } // namespace Poco::Net
//
// HTTPRequestHandler.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequestHandler.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPRequestHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequestHandler.h"
namespace Poco {
namespace Net {
HTTPRequestHandler::HTTPRequestHandler()
{
}
HTTPRequestHandler::~HTTPRequestHandler()
{
}
} } // namespace Poco::Net

View File

@@ -1,54 +1,54 @@
//
// HTTPRequestHandlerFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequestHandlerFactory.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPRequestHandlerFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequestHandlerFactory.h"
namespace Poco {
namespace Net {
HTTPRequestHandlerFactory::HTTPRequestHandlerFactory()
{
}
HTTPRequestHandlerFactory::~HTTPRequestHandlerFactory()
{
}
} } // namespace Poco::Net
//
// HTTPRequestHandlerFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPRequestHandlerFactory.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPRequestHandlerFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPRequestHandlerFactory.h"
namespace Poco {
namespace Net {
HTTPRequestHandlerFactory::HTTPRequestHandlerFactory()
{
}
HTTPRequestHandlerFactory::~HTTPRequestHandlerFactory()
{
}
} } // namespace Poco::Net

View File

@@ -1,341 +1,341 @@
//
// HTTPResponse.cpp
//
// $Id: //poco/1.2/Net/src/HTTPResponse.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPResponse
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeParser.h"
#include <ctype.h>
using Poco::DateTime;
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::DateTimeParser;
namespace Poco {
namespace Net {
const std::string HTTPResponse::HTTP_REASON_CONTINUE = "Continue";
const std::string HTTPResponse::HTTP_REASON_SWITCHING_PROTOCOLS = "Switching Protocols";
const std::string HTTPResponse::HTTP_REASON_OK = "OK";
const std::string HTTPResponse::HTTP_REASON_CREATED = "Created";
const std::string HTTPResponse::HTTP_REASON_ACCEPTED = "Accepted";
const std::string HTTPResponse::HTTP_REASON_NONAUTHORITATIVE = "Non-Authoritative Information";
const std::string HTTPResponse::HTTP_REASON_NO_CONTENT = "No Content";
const std::string HTTPResponse::HTTP_REASON_RESET_CONTENT = "Reset Content";
const std::string HTTPResponse::HTTP_REASON_PARTIAL_CONTENT = "Partial Content";
const std::string HTTPResponse::HTTP_REASON_MULTIPLE_CHOICES = "Multiple Choices";
const std::string HTTPResponse::HTTP_REASON_MOVED_PERMANENTLY = "Moved Permanently";
const std::string HTTPResponse::HTTP_REASON_FOUND = "Found";
const std::string HTTPResponse::HTTP_REASON_SEE_OTHER = "See Other";
const std::string HTTPResponse::HTTP_REASON_NOT_MODIFIED = "Not Modified";
const std::string HTTPResponse::HTTP_REASON_USEPROXY = "Use Proxy";
const std::string HTTPResponse::HTTP_REASON_TEMPORARY_REDIRECT = "Temporary Redirect";
const std::string HTTPResponse::HTTP_REASON_BAD_REQUEST = "Bad Request";
const std::string HTTPResponse::HTTP_REASON_UNAUTHORIZED = "Unauthorized";
const std::string HTTPResponse::HTTP_REASON_PAYMENT_REQUIRED = "Payment Required";
const std::string HTTPResponse::HTTP_REASON_FORBIDDEN = "Forbidden";
const std::string HTTPResponse::HTTP_REASON_NOT_FOUND = "Not Found";
const std::string HTTPResponse::HTTP_REASON_METHOD_NOT_ALLOWED = "Method Not Allowed";
const std::string HTTPResponse::HTTP_REASON_NOT_ACCEPTABLE = "Not Acceptable";
const std::string HTTPResponse::HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED = "Proxy Authentication Required";
const std::string HTTPResponse::HTTP_REASON_REQUEST_TIMEOUT = "Request Time-out";
const std::string HTTPResponse::HTTP_REASON_CONFLICT = "Conflict";
const std::string HTTPResponse::HTTP_REASON_GONE = "Gone";
const std::string HTTPResponse::HTTP_REASON_LENGTH_REQUIRED = "Length Required";
const std::string HTTPResponse::HTTP_REASON_PRECONDITION_FAILED = "Precondition Failed";
const std::string HTTPResponse::HTTP_REASON_REQUESTENTITYTOOLARGE = "Request Entity Too Large";
const std::string HTTPResponse::HTTP_REASON_REQUESTURITOOLONG = "Request-URI Too Large";
const std::string HTTPResponse::HTTP_REASON_UNSUPPORTEDMEDIATYPE = "Unsupported Media Type";
const std::string HTTPResponse::HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE = "Requested Range Not Satisfiable";
const std::string HTTPResponse::HTTP_REASON_EXPECTATION_FAILED = "Expectation Failed";
const std::string HTTPResponse::HTTP_REASON_INTERNAL_SERVER_ERROR = "Internal Server Error";
const std::string HTTPResponse::HTTP_REASON_NOT_IMPLEMENTED = "Not Implemented";
const std::string HTTPResponse::HTTP_REASON_BAD_GATEWAY = "Bad Gateway";
const std::string HTTPResponse::HTTP_REASON_SERVICE_UNAVAILABLE = "Service Unavailable";
const std::string HTTPResponse::HTTP_REASON_GATEWAY_TIMEOUT = "Gateway Time-out";
const std::string HTTPResponse::HTTP_REASON_VERSION_NOT_SUPPORTED = "HTTP Version not supported";
const std::string HTTPResponse::HTTP_REASON_UNKNOWN = "???";
const std::string HTTPResponse::DATE = "Date";
const std::string HTTPResponse::SET_COOKIE = "Set-Cookie";
HTTPResponse::HTTPResponse():
_status(HTTP_OK),
_reason(getReasonForStatus(HTTP_OK))
{
}
HTTPResponse::HTTPResponse(HTTPStatus status, const std::string& reason):
_status(status),
_reason(reason)
{
}
HTTPResponse::HTTPResponse(const std::string& version, HTTPStatus status, const std::string& reason):
HTTPMessage(version),
_status(status),
_reason(reason)
{
}
HTTPResponse::HTTPResponse(HTTPStatus status):
_status(status),
_reason(getReasonForStatus(status))
{
}
HTTPResponse::HTTPResponse(const std::string& version, HTTPStatus status):
HTTPMessage(version),
_status(status),
_reason(getReasonForStatus(status))
{
}
HTTPResponse::~HTTPResponse()
{
}
void HTTPResponse::setStatus(HTTPStatus status)
{
_status = status;
}
void HTTPResponse::setStatus(const std::string& status)
{
setStatus((HTTPStatus) NumberParser::parse(status));
}
void HTTPResponse::setReason(const std::string& reason)
{
_reason = reason;
}
void HTTPResponse::setStatusAndReason(HTTPStatus status, const std::string& reason)
{
_status = status;
_reason = reason;
}
void HTTPResponse::setStatusAndReason(HTTPStatus status)
{
setStatusAndReason(status, getReasonForStatus(status));
}
void HTTPResponse::setDate(const Poco::Timestamp& dateTime)
{
set(DATE, DateTimeFormatter::format(dateTime, DateTimeFormat::HTTP_FORMAT));
}
Poco::Timestamp HTTPResponse::getDate() const
{
const std::string& dateTime = get(DATE);
int tzd;
return DateTimeParser::parse(dateTime, tzd).timestamp();
}
void HTTPResponse::addCookie(const HTTPCookie& cookie)
{
add(SET_COOKIE, cookie.toString());
}
void HTTPResponse::getCookies(std::vector<HTTPCookie>& cookies) const
{
cookies.clear();
NameValueCollection::ConstIterator it = find(SET_COOKIE);
while (it != end() && it->first == SET_COOKIE)
{
NameValueCollection nvc;
splitParameters(it->second.begin(), it->second.end(), nvc);
cookies.push_back(HTTPCookie(nvc));
++it;
}
}
void HTTPResponse::write(std::ostream& ostr) const
{
ostr << getVersion() << " " << NumberFormatter::format((int) _status) << " " << _reason << "\r\n";
HTTPMessage::write(ostr);
ostr << "\r\n";
}
void HTTPResponse::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
std::string version;
std::string status;
std::string reason;
int ch = istr.get();
while (isspace(ch)) ch = istr.get();
if (ch == eof) throw MessageException("No HTTP response header");
while (!isspace(ch) && ch != eof && version.length() < MAX_VERSION_LENGTH) { version += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP version string");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && status.length() < MAX_STATUS_LENGTH) { status += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP status code");
while (isspace(ch)) ch = istr.get();
while (ch != '\r' && ch != '\n' && ch != eof && reason.length() < MAX_REASON_LENGTH) { reason += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP reason string too long");
if (ch == '\r') ch = istr.get();
HTTPMessage::read(istr);
ch = istr.get();
while (ch != '\n' && ch != eof) { ch = istr.get(); }
setVersion(version);
setStatus(status);
setReason(reason);
}
const std::string& HTTPResponse::getReasonForStatus(HTTPStatus status)
{
switch (status)
{
case HTTP_CONTINUE:
return HTTP_REASON_CONTINUE;
case HTTP_SWITCHING_PROTOCOLS:
return HTTP_REASON_SWITCHING_PROTOCOLS;
case HTTP_OK:
return HTTP_REASON_OK;
case HTTP_CREATED:
return HTTP_REASON_CREATED;
case HTTP_ACCEPTED:
return HTTP_REASON_ACCEPTED;
case HTTP_NONAUTHORITATIVE:
return HTTP_REASON_NONAUTHORITATIVE;
case HTTP_NO_CONTENT:
return HTTP_REASON_NO_CONTENT;
case HTTP_RESET_CONTENT:
return HTTP_REASON_RESET_CONTENT;
case HTTP_PARTIAL_CONTENT:
return HTTP_REASON_PARTIAL_CONTENT;
case HTTP_MULTIPLE_CHOICES:
return HTTP_REASON_MULTIPLE_CHOICES;
case HTTP_MOVED_PERMANENTLY:
return HTTP_REASON_MOVED_PERMANENTLY;
case HTTP_FOUND:
return HTTP_REASON_FOUND;
case HTTP_SEE_OTHER:
return HTTP_REASON_SEE_OTHER;
case HTTP_NOT_MODIFIED:
return HTTP_REASON_NOT_MODIFIED;
case HTTP_USEPROXY:
return HTTP_REASON_USEPROXY;
case HTTP_TEMPORARY_REDIRECT:
return HTTP_REASON_TEMPORARY_REDIRECT;
case HTTP_BAD_REQUEST:
return HTTP_REASON_BAD_REQUEST;
case HTTP_UNAUTHORIZED:
return HTTP_REASON_UNAUTHORIZED;
case HTTP_PAYMENT_REQUIRED:
return HTTP_REASON_PAYMENT_REQUIRED;
case HTTP_FORBIDDEN:
return HTTP_REASON_FORBIDDEN;
case HTTP_NOT_FOUND:
return HTTP_REASON_NOT_FOUND;
case HTTP_METHOD_NOT_ALLOWED:
return HTTP_REASON_METHOD_NOT_ALLOWED;
case HTTP_NOT_ACCEPTABLE:
return HTTP_REASON_NOT_ACCEPTABLE;
case HTTP_PROXY_AUTHENTICATION_REQUIRED:
return HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED;
case HTTP_REQUEST_TIMEOUT:
return HTTP_REASON_REQUEST_TIMEOUT;
case HTTP_CONFLICT:
return HTTP_REASON_CONFLICT;
case HTTP_GONE:
return HTTP_REASON_GONE;
case HTTP_LENGTH_REQUIRED:
return HTTP_REASON_LENGTH_REQUIRED;
case HTTP_PRECONDITION_FAILED:
return HTTP_REASON_PRECONDITION_FAILED;
case HTTP_REQUESTENTITYTOOLARGE:
return HTTP_REASON_REQUESTENTITYTOOLARGE;
case HTTP_REQUESTURITOOLONG:
return HTTP_REASON_REQUESTURITOOLONG;
case HTTP_UNSUPPORTEDMEDIATYPE:
return HTTP_REASON_UNSUPPORTEDMEDIATYPE;
case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
return HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE;
case HTTP_EXPECTATION_FAILED:
return HTTP_REASON_EXPECTATION_FAILED;
case HTTP_INTERNAL_SERVER_ERROR:
return HTTP_REASON_INTERNAL_SERVER_ERROR;
case HTTP_NOT_IMPLEMENTED:
return HTTP_REASON_NOT_IMPLEMENTED;
case HTTP_BAD_GATEWAY:
return HTTP_REASON_BAD_GATEWAY;
case HTTP_SERVICE_UNAVAILABLE:
return HTTP_REASON_SERVICE_UNAVAILABLE;
case HTTP_GATEWAY_TIMEOUT:
return HTTP_REASON_GATEWAY_TIMEOUT;
case HTTP_VERSION_NOT_SUPPORTED:
return HTTP_REASON_VERSION_NOT_SUPPORTED;
default:
return HTTP_REASON_UNKNOWN;
}
}
} } // namespace Poco::Net
//
// HTTPResponse.cpp
//
// $Id: //poco/1.2/Net/src/HTTPResponse.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPResponse
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeParser.h"
#include <ctype.h>
using Poco::DateTime;
using Poco::NumberFormatter;
using Poco::NumberParser;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::DateTimeParser;
namespace Poco {
namespace Net {
const std::string HTTPResponse::HTTP_REASON_CONTINUE = "Continue";
const std::string HTTPResponse::HTTP_REASON_SWITCHING_PROTOCOLS = "Switching Protocols";
const std::string HTTPResponse::HTTP_REASON_OK = "OK";
const std::string HTTPResponse::HTTP_REASON_CREATED = "Created";
const std::string HTTPResponse::HTTP_REASON_ACCEPTED = "Accepted";
const std::string HTTPResponse::HTTP_REASON_NONAUTHORITATIVE = "Non-Authoritative Information";
const std::string HTTPResponse::HTTP_REASON_NO_CONTENT = "No Content";
const std::string HTTPResponse::HTTP_REASON_RESET_CONTENT = "Reset Content";
const std::string HTTPResponse::HTTP_REASON_PARTIAL_CONTENT = "Partial Content";
const std::string HTTPResponse::HTTP_REASON_MULTIPLE_CHOICES = "Multiple Choices";
const std::string HTTPResponse::HTTP_REASON_MOVED_PERMANENTLY = "Moved Permanently";
const std::string HTTPResponse::HTTP_REASON_FOUND = "Found";
const std::string HTTPResponse::HTTP_REASON_SEE_OTHER = "See Other";
const std::string HTTPResponse::HTTP_REASON_NOT_MODIFIED = "Not Modified";
const std::string HTTPResponse::HTTP_REASON_USEPROXY = "Use Proxy";
const std::string HTTPResponse::HTTP_REASON_TEMPORARY_REDIRECT = "Temporary Redirect";
const std::string HTTPResponse::HTTP_REASON_BAD_REQUEST = "Bad Request";
const std::string HTTPResponse::HTTP_REASON_UNAUTHORIZED = "Unauthorized";
const std::string HTTPResponse::HTTP_REASON_PAYMENT_REQUIRED = "Payment Required";
const std::string HTTPResponse::HTTP_REASON_FORBIDDEN = "Forbidden";
const std::string HTTPResponse::HTTP_REASON_NOT_FOUND = "Not Found";
const std::string HTTPResponse::HTTP_REASON_METHOD_NOT_ALLOWED = "Method Not Allowed";
const std::string HTTPResponse::HTTP_REASON_NOT_ACCEPTABLE = "Not Acceptable";
const std::string HTTPResponse::HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED = "Proxy Authentication Required";
const std::string HTTPResponse::HTTP_REASON_REQUEST_TIMEOUT = "Request Time-out";
const std::string HTTPResponse::HTTP_REASON_CONFLICT = "Conflict";
const std::string HTTPResponse::HTTP_REASON_GONE = "Gone";
const std::string HTTPResponse::HTTP_REASON_LENGTH_REQUIRED = "Length Required";
const std::string HTTPResponse::HTTP_REASON_PRECONDITION_FAILED = "Precondition Failed";
const std::string HTTPResponse::HTTP_REASON_REQUESTENTITYTOOLARGE = "Request Entity Too Large";
const std::string HTTPResponse::HTTP_REASON_REQUESTURITOOLONG = "Request-URI Too Large";
const std::string HTTPResponse::HTTP_REASON_UNSUPPORTEDMEDIATYPE = "Unsupported Media Type";
const std::string HTTPResponse::HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE = "Requested Range Not Satisfiable";
const std::string HTTPResponse::HTTP_REASON_EXPECTATION_FAILED = "Expectation Failed";
const std::string HTTPResponse::HTTP_REASON_INTERNAL_SERVER_ERROR = "Internal Server Error";
const std::string HTTPResponse::HTTP_REASON_NOT_IMPLEMENTED = "Not Implemented";
const std::string HTTPResponse::HTTP_REASON_BAD_GATEWAY = "Bad Gateway";
const std::string HTTPResponse::HTTP_REASON_SERVICE_UNAVAILABLE = "Service Unavailable";
const std::string HTTPResponse::HTTP_REASON_GATEWAY_TIMEOUT = "Gateway Time-out";
const std::string HTTPResponse::HTTP_REASON_VERSION_NOT_SUPPORTED = "HTTP Version not supported";
const std::string HTTPResponse::HTTP_REASON_UNKNOWN = "???";
const std::string HTTPResponse::DATE = "Date";
const std::string HTTPResponse::SET_COOKIE = "Set-Cookie";
HTTPResponse::HTTPResponse():
_status(HTTP_OK),
_reason(getReasonForStatus(HTTP_OK))
{
}
HTTPResponse::HTTPResponse(HTTPStatus status, const std::string& reason):
_status(status),
_reason(reason)
{
}
HTTPResponse::HTTPResponse(const std::string& version, HTTPStatus status, const std::string& reason):
HTTPMessage(version),
_status(status),
_reason(reason)
{
}
HTTPResponse::HTTPResponse(HTTPStatus status):
_status(status),
_reason(getReasonForStatus(status))
{
}
HTTPResponse::HTTPResponse(const std::string& version, HTTPStatus status):
HTTPMessage(version),
_status(status),
_reason(getReasonForStatus(status))
{
}
HTTPResponse::~HTTPResponse()
{
}
void HTTPResponse::setStatus(HTTPStatus status)
{
_status = status;
}
void HTTPResponse::setStatus(const std::string& status)
{
setStatus((HTTPStatus) NumberParser::parse(status));
}
void HTTPResponse::setReason(const std::string& reason)
{
_reason = reason;
}
void HTTPResponse::setStatusAndReason(HTTPStatus status, const std::string& reason)
{
_status = status;
_reason = reason;
}
void HTTPResponse::setStatusAndReason(HTTPStatus status)
{
setStatusAndReason(status, getReasonForStatus(status));
}
void HTTPResponse::setDate(const Poco::Timestamp& dateTime)
{
set(DATE, DateTimeFormatter::format(dateTime, DateTimeFormat::HTTP_FORMAT));
}
Poco::Timestamp HTTPResponse::getDate() const
{
const std::string& dateTime = get(DATE);
int tzd;
return DateTimeParser::parse(dateTime, tzd).timestamp();
}
void HTTPResponse::addCookie(const HTTPCookie& cookie)
{
add(SET_COOKIE, cookie.toString());
}
void HTTPResponse::getCookies(std::vector<HTTPCookie>& cookies) const
{
cookies.clear();
NameValueCollection::ConstIterator it = find(SET_COOKIE);
while (it != end() && it->first == SET_COOKIE)
{
NameValueCollection nvc;
splitParameters(it->second.begin(), it->second.end(), nvc);
cookies.push_back(HTTPCookie(nvc));
++it;
}
}
void HTTPResponse::write(std::ostream& ostr) const
{
ostr << getVersion() << " " << NumberFormatter::format((int) _status) << " " << _reason << "\r\n";
HTTPMessage::write(ostr);
ostr << "\r\n";
}
void HTTPResponse::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
std::string version;
std::string status;
std::string reason;
int ch = istr.get();
while (isspace(ch)) ch = istr.get();
if (ch == eof) throw MessageException("No HTTP response header");
while (!isspace(ch) && ch != eof && version.length() < MAX_VERSION_LENGTH) { version += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP version string");
while (isspace(ch)) ch = istr.get();
while (!isspace(ch) && ch != eof && status.length() < MAX_STATUS_LENGTH) { status += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("Invalid HTTP status code");
while (isspace(ch)) ch = istr.get();
while (ch != '\r' && ch != '\n' && ch != eof && reason.length() < MAX_REASON_LENGTH) { reason += (char) ch; ch = istr.get(); }
if (!isspace(ch)) throw MessageException("HTTP reason string too long");
if (ch == '\r') ch = istr.get();
HTTPMessage::read(istr);
ch = istr.get();
while (ch != '\n' && ch != eof) { ch = istr.get(); }
setVersion(version);
setStatus(status);
setReason(reason);
}
const std::string& HTTPResponse::getReasonForStatus(HTTPStatus status)
{
switch (status)
{
case HTTP_CONTINUE:
return HTTP_REASON_CONTINUE;
case HTTP_SWITCHING_PROTOCOLS:
return HTTP_REASON_SWITCHING_PROTOCOLS;
case HTTP_OK:
return HTTP_REASON_OK;
case HTTP_CREATED:
return HTTP_REASON_CREATED;
case HTTP_ACCEPTED:
return HTTP_REASON_ACCEPTED;
case HTTP_NONAUTHORITATIVE:
return HTTP_REASON_NONAUTHORITATIVE;
case HTTP_NO_CONTENT:
return HTTP_REASON_NO_CONTENT;
case HTTP_RESET_CONTENT:
return HTTP_REASON_RESET_CONTENT;
case HTTP_PARTIAL_CONTENT:
return HTTP_REASON_PARTIAL_CONTENT;
case HTTP_MULTIPLE_CHOICES:
return HTTP_REASON_MULTIPLE_CHOICES;
case HTTP_MOVED_PERMANENTLY:
return HTTP_REASON_MOVED_PERMANENTLY;
case HTTP_FOUND:
return HTTP_REASON_FOUND;
case HTTP_SEE_OTHER:
return HTTP_REASON_SEE_OTHER;
case HTTP_NOT_MODIFIED:
return HTTP_REASON_NOT_MODIFIED;
case HTTP_USEPROXY:
return HTTP_REASON_USEPROXY;
case HTTP_TEMPORARY_REDIRECT:
return HTTP_REASON_TEMPORARY_REDIRECT;
case HTTP_BAD_REQUEST:
return HTTP_REASON_BAD_REQUEST;
case HTTP_UNAUTHORIZED:
return HTTP_REASON_UNAUTHORIZED;
case HTTP_PAYMENT_REQUIRED:
return HTTP_REASON_PAYMENT_REQUIRED;
case HTTP_FORBIDDEN:
return HTTP_REASON_FORBIDDEN;
case HTTP_NOT_FOUND:
return HTTP_REASON_NOT_FOUND;
case HTTP_METHOD_NOT_ALLOWED:
return HTTP_REASON_METHOD_NOT_ALLOWED;
case HTTP_NOT_ACCEPTABLE:
return HTTP_REASON_NOT_ACCEPTABLE;
case HTTP_PROXY_AUTHENTICATION_REQUIRED:
return HTTP_REASON_PROXY_AUTHENTICATION_REQUIRED;
case HTTP_REQUEST_TIMEOUT:
return HTTP_REASON_REQUEST_TIMEOUT;
case HTTP_CONFLICT:
return HTTP_REASON_CONFLICT;
case HTTP_GONE:
return HTTP_REASON_GONE;
case HTTP_LENGTH_REQUIRED:
return HTTP_REASON_LENGTH_REQUIRED;
case HTTP_PRECONDITION_FAILED:
return HTTP_REASON_PRECONDITION_FAILED;
case HTTP_REQUESTENTITYTOOLARGE:
return HTTP_REASON_REQUESTENTITYTOOLARGE;
case HTTP_REQUESTURITOOLONG:
return HTTP_REASON_REQUESTURITOOLONG;
case HTTP_UNSUPPORTEDMEDIATYPE:
return HTTP_REASON_UNSUPPORTEDMEDIATYPE;
case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
return HTTP_REASON_REQUESTED_RANGE_NOT_SATISFIABLE;
case HTTP_EXPECTATION_FAILED:
return HTTP_REASON_EXPECTATION_FAILED;
case HTTP_INTERNAL_SERVER_ERROR:
return HTTP_REASON_INTERNAL_SERVER_ERROR;
case HTTP_NOT_IMPLEMENTED:
return HTTP_REASON_NOT_IMPLEMENTED;
case HTTP_BAD_GATEWAY:
return HTTP_REASON_BAD_GATEWAY;
case HTTP_SERVICE_UNAVAILABLE:
return HTTP_REASON_SERVICE_UNAVAILABLE;
case HTTP_GATEWAY_TIMEOUT:
return HTTP_REASON_GATEWAY_TIMEOUT;
case HTTP_VERSION_NOT_SUPPORTED:
return HTTP_REASON_VERSION_NOT_SUPPORTED;
default:
return HTTP_REASON_UNKNOWN;
}
}
} } // namespace Poco::Net

View File

@@ -1,63 +1,63 @@
//
// HTTPServer.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServer.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServer
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerConnectionFactory.h"
namespace Poco {
namespace Net {
HTTPServer::HTTPServer(HTTPRequestHandlerFactory* pFactory, const ServerSocket& socket, HTTPServerParams* pParams):
TCPServer(new HTTPServerConnectionFactory(pParams, pFactory), socket, pParams)
{
}
HTTPServer::HTTPServer(HTTPRequestHandlerFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, HTTPServerParams* pParams):
TCPServer(new HTTPServerConnectionFactory(pParams, pFactory), threadPool, socket, pParams)
{
}
HTTPServer::~HTTPServer()
{
}
} } // namespace Poco::Net
//
// HTTPServer.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServer.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServer
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerConnectionFactory.h"
namespace Poco {
namespace Net {
HTTPServer::HTTPServer(HTTPRequestHandlerFactory* pFactory, const ServerSocket& socket, HTTPServerParams* pParams):
TCPServer(new HTTPServerConnectionFactory(pParams, pFactory), socket, pParams)
{
}
HTTPServer::HTTPServer(HTTPRequestHandlerFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, HTTPServerParams* pParams):
TCPServer(new HTTPServerConnectionFactory(pParams, pFactory), threadPool, socket, pParams)
{
}
HTTPServer::~HTTPServer()
{
}
} } // namespace Poco::Net

View File

@@ -1,103 +1,103 @@
//
// HTTPServerConnection.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerConnection.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerConnection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerConnection.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
#include <memory>
namespace Poco {
namespace Net {
HTTPServerConnection::HTTPServerConnection(const StreamSocket& socket, HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory):
TCPServerConnection(socket),
_pParams(pParams),
_pFactory(pFactory)
{
poco_check_ptr (pFactory);
poco_check_ptr (pParams);
_pParams->duplicate();
}
HTTPServerConnection::~HTTPServerConnection()
{
_pParams->release();
}
void HTTPServerConnection::run()
{
std::string server = _pParams->getSoftwareVersion();
HTTPServerSession session(socket(), _pParams);
while (session.hasMoreRequests())
{
HTTPServerRequest request(session, _pParams);
HTTPServerResponse response(session);
response.setVersion(request.getVersion());
response.setKeepAlive(_pParams->getKeepAlive() && request.getKeepAlive());
if (!server.empty())
response.set("Server", server);
std::auto_ptr<HTTPRequestHandler> pHandler(_pFactory->createRequestHandler(request));
if (pHandler.get())
{
if (request.expectContinue())
response.sendContinue();
pHandler->handleRequest(request, response);
session.setKeepAlive(_pParams->getKeepAlive() && response.getKeepAlive());
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_NOT_IMPLEMENTED);
response.setKeepAlive(false);
response.send();
session.setKeepAlive(false);
}
}
}
} } // namespace Poco::Net
//
// HTTPServerConnection.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerConnection.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerConnection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerConnection.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
#include <memory>
namespace Poco {
namespace Net {
HTTPServerConnection::HTTPServerConnection(const StreamSocket& socket, HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory):
TCPServerConnection(socket),
_pParams(pParams),
_pFactory(pFactory)
{
poco_check_ptr (pFactory);
poco_check_ptr (pParams);
_pParams->duplicate();
}
HTTPServerConnection::~HTTPServerConnection()
{
_pParams->release();
}
void HTTPServerConnection::run()
{
std::string server = _pParams->getSoftwareVersion();
HTTPServerSession session(socket(), _pParams);
while (session.hasMoreRequests())
{
HTTPServerRequest request(session, _pParams);
HTTPServerResponse response(session);
response.setVersion(request.getVersion());
response.setKeepAlive(_pParams->getKeepAlive() && request.getKeepAlive());
if (!server.empty())
response.set("Server", server);
std::auto_ptr<HTTPRequestHandler> pHandler(_pFactory->createRequestHandler(request));
if (pHandler.get())
{
if (request.expectContinue())
response.sendContinue();
pHandler->handleRequest(request, response);
session.setKeepAlive(_pParams->getKeepAlive() && response.getKeepAlive());
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_NOT_IMPLEMENTED);
response.setKeepAlive(false);
response.send();
session.setKeepAlive(false);
}
}
}
} } // namespace Poco::Net

View File

@@ -1,71 +1,71 @@
//
// HTTPServerConnectionFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerConnectionFactory.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerConnectionFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerConnectionFactory.h"
#include "Poco/Net/HTTPServerConnection.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
namespace Poco {
namespace Net {
HTTPServerConnectionFactory::HTTPServerConnectionFactory(HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory):
_pParams(pParams),
_pFactory(pFactory)
{
poco_check_ptr (pParams);
poco_check_ptr (pFactory);
_pParams->duplicate();
}
HTTPServerConnectionFactory::~HTTPServerConnectionFactory()
{
_pParams->release();
delete _pFactory;
}
TCPServerConnection* HTTPServerConnectionFactory::createConnection(const StreamSocket& socket)
{
return new HTTPServerConnection(socket, _pParams, _pFactory);
}
} } // namespace Poco::Net
//
// HTTPServerConnectionFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerConnectionFactory.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerConnectionFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerConnectionFactory.h"
#include "Poco/Net/HTTPServerConnection.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
namespace Poco {
namespace Net {
HTTPServerConnectionFactory::HTTPServerConnectionFactory(HTTPServerParams* pParams, HTTPRequestHandlerFactory* pFactory):
_pParams(pParams),
_pFactory(pFactory)
{
poco_check_ptr (pParams);
poco_check_ptr (pFactory);
_pParams->duplicate();
}
HTTPServerConnectionFactory::~HTTPServerConnectionFactory()
{
_pParams->release();
delete _pFactory;
}
TCPServerConnection* HTTPServerConnectionFactory::createConnection(const StreamSocket& socket)
{
return new HTTPServerConnection(socket, _pParams, _pFactory);
}
} } // namespace Poco::Net

View File

@@ -1,95 +1,95 @@
//
// HTTPServerParams.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerParams.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerParams
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerParams.h"
namespace Poco {
namespace Net {
HTTPServerParams::HTTPServerParams():
_timeout(60000000),
_keepAlive(true),
_maxKeepAliveRequests(0),
_keepAliveTimeout(15000000)
{
}
HTTPServerParams::~HTTPServerParams()
{
}
void HTTPServerParams::setServerName(const std::string& serverName)
{
_serverName = serverName;
}
void HTTPServerParams::setSoftwareVersion(const std::string& softwareVersion)
{
_softwareVersion = softwareVersion;
}
void HTTPServerParams::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
void HTTPServerParams::setKeepAlive(bool keepAlive)
{
_keepAlive = keepAlive;
}
void HTTPServerParams::setKeepAliveTimeout(const Poco::Timespan& timeout)
{
_keepAliveTimeout = timeout;
}
void HTTPServerParams::setMaxKeepAliveRequests(int maxKeepAliveRequests)
{
poco_assert (maxKeepAliveRequests >= 0);
_maxKeepAliveRequests = maxKeepAliveRequests;
}
} } // namespace Poco::Net
//
// HTTPServerParams.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerParams.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerParams
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerParams.h"
namespace Poco {
namespace Net {
HTTPServerParams::HTTPServerParams():
_timeout(60000000),
_keepAlive(true),
_maxKeepAliveRequests(0),
_keepAliveTimeout(15000000)
{
}
HTTPServerParams::~HTTPServerParams()
{
}
void HTTPServerParams::setServerName(const std::string& serverName)
{
_serverName = serverName;
}
void HTTPServerParams::setSoftwareVersion(const std::string& softwareVersion)
{
_softwareVersion = softwareVersion;
}
void HTTPServerParams::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
void HTTPServerParams::setKeepAlive(bool keepAlive)
{
_keepAlive = keepAlive;
}
void HTTPServerParams::setKeepAliveTimeout(const Poco::Timespan& timeout)
{
_keepAliveTimeout = timeout;
}
void HTTPServerParams::setMaxKeepAliveRequests(int maxKeepAliveRequests)
{
poco_assert (maxKeepAliveRequests >= 0);
_maxKeepAliveRequests = maxKeepAliveRequests;
}
} } // namespace Poco::Net

View File

@@ -1,91 +1,91 @@
//
// HTTPServerRequest.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerRequest.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerRequest
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/String.h"
using Poco::icompare;
namespace Poco {
namespace Net {
HTTPServerRequest::HTTPServerRequest(HTTPServerSession& session, HTTPServerParams* pParams):
_pStream(0),
_pParams(pParams),
_clientAddress(session.clientAddress()),
_serverAddress(session.serverAddress())
{
poco_check_ptr (_pParams);
_pParams->duplicate();
HTTPHeaderInputStream hs(session);
read(hs);
if (getChunkedTransferEncoding())
_pStream = new HTTPChunkedInputStream(session);
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pStream = new HTTPFixedLengthInputStream(session, getContentLength());
else if (getMethod() == HTTPRequest::HTTP_GET || getMethod() == HTTPRequest::HTTP_HEAD)
_pStream = new HTTPFixedLengthInputStream(session, 0);
else
_pStream = new HTTPInputStream(session);
}
HTTPServerRequest::~HTTPServerRequest()
{
_pParams->release();
delete _pStream;
}
bool HTTPServerRequest::expectContinue() const
{
return has("Expect") && icompare(get("Expect"), "100-continue") == 0;
}
} } // namespace Poco::Net
//
// HTTPServerRequest.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerRequest.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerRequest
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/String.h"
using Poco::icompare;
namespace Poco {
namespace Net {
HTTPServerRequest::HTTPServerRequest(HTTPServerSession& session, HTTPServerParams* pParams):
_pStream(0),
_pParams(pParams),
_clientAddress(session.clientAddress()),
_serverAddress(session.serverAddress())
{
poco_check_ptr (_pParams);
_pParams->duplicate();
HTTPHeaderInputStream hs(session);
read(hs);
if (getChunkedTransferEncoding())
_pStream = new HTTPChunkedInputStream(session);
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
_pStream = new HTTPFixedLengthInputStream(session, getContentLength());
else if (getMethod() == HTTPRequest::HTTP_GET || getMethod() == HTTPRequest::HTTP_HEAD)
_pStream = new HTTPFixedLengthInputStream(session, 0);
else
_pStream = new HTTPInputStream(session);
}
HTTPServerRequest::~HTTPServerRequest()
{
_pParams->release();
delete _pStream;
}
bool HTTPServerRequest::expectContinue() const
{
return has("Expect") && icompare(get("Expect"), "100-continue") == 0;
}
} } // namespace Poco::Net

View File

@@ -1,151 +1,151 @@
//
// HTTPServerResponse.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerResponse.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerResponse
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/File.h"
#include "Poco/Timestamp.h"
#include "Poco/NumberFormatter.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include <fstream>
using Poco::File;
using Poco::Timestamp;
using Poco::NumberFormatter;
using Poco::StreamCopier;
using Poco::OpenFileException;
namespace Poco {
namespace Net {
HTTPServerResponse::HTTPServerResponse(HTTPServerSession& session):
_session(session),
_pStream(0)
{
}
HTTPServerResponse::~HTTPServerResponse()
{
delete _pStream;
}
void HTTPServerResponse::sendContinue()
{
HTTPHeaderOutputStream hs(_session);
hs << getVersion() << " 100 Continue\r\n\r\n";
}
std::ostream& HTTPServerResponse::send()
{
poco_assert (!_pStream);
if (getChunkedTransferEncoding())
{
_pStream = new HTTPChunkedOutputStream(_session);
}
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
{
_pStream = new HTTPFixedLengthOutputStream(_session, getContentLength());
}
else
{
_pStream = new HTTPOutputStream(_session);
setKeepAlive(false);
}
HTTPHeaderOutputStream hs(_session);
write(hs);
return *_pStream;
}
void HTTPServerResponse::sendFile(const std::string& path, const std::string& mediaType)
{
poco_assert (!_pStream);
File f(path);
Timestamp dateTime = f.getLastModified();
File::FileSize length = f.getSize();
setDate(dateTime);
setContentLength((int) length);
setContentType(mediaType);
std::ifstream istr(path.c_str(), std::ios::binary | std::ios::in);
if (istr.good())
{
send();
StreamCopier::copyStream(istr, *_pStream);
}
else throw OpenFileException(path);
}
void HTTPServerResponse::redirect(const std::string& uri)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_FOUND);
set("Location", uri);
HTTPHeaderOutputStream hs(_session);
write(hs);
}
void HTTPServerResponse::requireAuthentication(const std::string& realm)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_UNAUTHORIZED);
std::string auth("Basic realm=\"");
auth.append(realm);
auth.append("\"");
set("WWW-Authenticate", auth);
}
} } // namespace Poco::Net
//
// HTTPServerResponse.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerResponse.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerResponse
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/File.h"
#include "Poco/Timestamp.h"
#include "Poco/NumberFormatter.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include <fstream>
using Poco::File;
using Poco::Timestamp;
using Poco::NumberFormatter;
using Poco::StreamCopier;
using Poco::OpenFileException;
namespace Poco {
namespace Net {
HTTPServerResponse::HTTPServerResponse(HTTPServerSession& session):
_session(session),
_pStream(0)
{
}
HTTPServerResponse::~HTTPServerResponse()
{
delete _pStream;
}
void HTTPServerResponse::sendContinue()
{
HTTPHeaderOutputStream hs(_session);
hs << getVersion() << " 100 Continue\r\n\r\n";
}
std::ostream& HTTPServerResponse::send()
{
poco_assert (!_pStream);
if (getChunkedTransferEncoding())
{
_pStream = new HTTPChunkedOutputStream(_session);
}
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
{
_pStream = new HTTPFixedLengthOutputStream(_session, getContentLength());
}
else
{
_pStream = new HTTPOutputStream(_session);
setKeepAlive(false);
}
HTTPHeaderOutputStream hs(_session);
write(hs);
return *_pStream;
}
void HTTPServerResponse::sendFile(const std::string& path, const std::string& mediaType)
{
poco_assert (!_pStream);
File f(path);
Timestamp dateTime = f.getLastModified();
File::FileSize length = f.getSize();
setDate(dateTime);
setContentLength((int) length);
setContentType(mediaType);
std::ifstream istr(path.c_str(), std::ios::binary | std::ios::in);
if (istr.good())
{
send();
StreamCopier::copyStream(istr, *_pStream);
}
else throw OpenFileException(path);
}
void HTTPServerResponse::redirect(const std::string& uri)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_FOUND);
set("Location", uri);
HTTPHeaderOutputStream hs(_session);
write(hs);
}
void HTTPServerResponse::requireAuthentication(const std::string& realm)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_UNAUTHORIZED);
std::string auth("Basic realm=\"");
auth.append(realm);
auth.append("\"");
set("WWW-Authenticate", auth);
}
} } // namespace Poco::Net

View File

@@ -1,88 +1,88 @@
//
// HTTPServerSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerSession.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPServerParams.h"
namespace Poco {
namespace Net {
HTTPServerSession::HTTPServerSession(const StreamSocket& socket, HTTPServerParams* pParams):
HTTPSession(socket, pParams->getKeepAlive()),
_firstRequest(true),
_keepAliveTimeout(pParams->getKeepAliveTimeout()),
_maxKeepAliveRequests(pParams->getMaxKeepAliveRequests())
{
}
HTTPServerSession::~HTTPServerSession()
{
}
bool HTTPServerSession::hasMoreRequests()
{
if (_firstRequest)
{
_firstRequest = false;
--_maxKeepAliveRequests;
return socket().poll(getTimeout(), Socket::SELECT_READ);
}
else if (_maxKeepAliveRequests > 0 && getKeepAlive())
{
--_maxKeepAliveRequests;
return socket().poll(_keepAliveTimeout, Socket::SELECT_READ);
}
else return false;
}
SocketAddress HTTPServerSession::clientAddress()
{
return socket().peerAddress();
}
SocketAddress HTTPServerSession::serverAddress()
{
return socket().address();
}
} } // namespace Poco::Net
//
// HTTPServerSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPServerSession.cpp#1 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPServerParams.h"
namespace Poco {
namespace Net {
HTTPServerSession::HTTPServerSession(const StreamSocket& socket, HTTPServerParams* pParams):
HTTPSession(socket, pParams->getKeepAlive()),
_firstRequest(true),
_keepAliveTimeout(pParams->getKeepAliveTimeout()),
_maxKeepAliveRequests(pParams->getMaxKeepAliveRequests())
{
}
HTTPServerSession::~HTTPServerSession()
{
}
bool HTTPServerSession::hasMoreRequests()
{
if (_firstRequest)
{
_firstRequest = false;
--_maxKeepAliveRequests;
return socket().poll(getTimeout(), Socket::SELECT_READ);
}
else if (_maxKeepAliveRequests > 0 && getKeepAlive())
{
--_maxKeepAliveRequests;
return socket().poll(_keepAliveTimeout, Socket::SELECT_READ);
}
else return false;
}
SocketAddress HTTPServerSession::clientAddress()
{
return socket().peerAddress();
}
SocketAddress HTTPServerSession::serverAddress()
{
return socket().address();
}
} } // namespace Poco::Net

View File

@@ -1,218 +1,218 @@
//
// HTTPSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSession.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSession.h"
#include "Poco/Net/HTTPBufferAllocator.h"
#include "Poco/Net/NetException.h"
#include <string.h>
using Poco::TimeoutException;
namespace Poco {
namespace Net {
HTTPSession::HTTPSession():
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(false),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::HTTPSession(const StreamSocket& socket):
_socket(socket),
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(false),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::HTTPSession(const StreamSocket& socket, bool keepAlive):
_socket(socket),
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(keepAlive),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::~HTTPSession()
{
if (_pBuffer) HTTPBufferAllocator::deallocate(_pBuffer, HTTPBufferAllocator::BUFFER_SIZE);
close();
delete _pException;
}
void HTTPSession::setKeepAlive(bool keepAlive)
{
_keepAlive = keepAlive;
}
void HTTPSession::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
int HTTPSession::get()
{
if (_pCurrent == _pEnd)
refill();
if (_pCurrent < _pEnd)
return *_pCurrent++;
else
return std::char_traits<char>::eof();
}
int HTTPSession::peek()
{
if (_pCurrent == _pEnd)
refill();
if (_pCurrent < _pEnd)
return *_pCurrent;
else
return std::char_traits<char>::eof();
}
int HTTPSession::read(char* buffer, std::streamsize length)
{
if (_pCurrent < _pEnd)
{
int n = (int) (_pEnd - _pCurrent);
if (n > length) n = (int) length;
memcpy(buffer, _pCurrent, n);
_pCurrent += n;
return n;
}
else return receive(buffer, (int) length);
}
int HTTPSession::write(const char* buffer, std::streamsize length)
{
try
{
return _socket.sendBytes(buffer, (int) length);
}
catch (Poco::Exception& exc)
{
setException(exc);
throw;
}
}
int HTTPSession::receive(char* buffer, int length)
{
try
{
if (_socket.poll(_timeout, Socket::SELECT_READ))
return _socket.receiveBytes(buffer, length);
else
throw TimeoutException();
}
catch (Poco::Exception& exc)
{
setException(exc);
throw;
}
}
void HTTPSession::refill()
{
if (!_pBuffer)
{
_pBuffer = HTTPBufferAllocator::allocate(HTTPBufferAllocator::BUFFER_SIZE);
}
_pCurrent = _pEnd = _pBuffer;
int n = receive(_pBuffer, HTTPBufferAllocator::BUFFER_SIZE);
_pEnd += n;
}
bool HTTPSession::connected() const
{
return _socket.impl()->initialized();
}
void HTTPSession::connect(const SocketAddress& address)
{
_socket.connect(address, _timeout);
}
void HTTPSession::abort()
{
_socket.shutdown();
close();
}
void HTTPSession::close()
{
_socket.close();
}
void HTTPSession::setException(const Poco::Exception& exc)
{
delete _pException;
_pException = exc.clone();
}
} } // namespace Poco::Net
//
// HTTPSession.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSession.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSession.h"
#include "Poco/Net/HTTPBufferAllocator.h"
#include "Poco/Net/NetException.h"
#include <string.h>
using Poco::TimeoutException;
namespace Poco {
namespace Net {
HTTPSession::HTTPSession():
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(false),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::HTTPSession(const StreamSocket& socket):
_socket(socket),
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(false),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::HTTPSession(const StreamSocket& socket, bool keepAlive):
_socket(socket),
_pBuffer(0),
_pCurrent(0),
_pEnd(0),
_keepAlive(keepAlive),
_timeout(HTTP_DEFAULT_TIMEOUT),
_pException(0)
{
}
HTTPSession::~HTTPSession()
{
if (_pBuffer) HTTPBufferAllocator::deallocate(_pBuffer, HTTPBufferAllocator::BUFFER_SIZE);
close();
delete _pException;
}
void HTTPSession::setKeepAlive(bool keepAlive)
{
_keepAlive = keepAlive;
}
void HTTPSession::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
int HTTPSession::get()
{
if (_pCurrent == _pEnd)
refill();
if (_pCurrent < _pEnd)
return *_pCurrent++;
else
return std::char_traits<char>::eof();
}
int HTTPSession::peek()
{
if (_pCurrent == _pEnd)
refill();
if (_pCurrent < _pEnd)
return *_pCurrent;
else
return std::char_traits<char>::eof();
}
int HTTPSession::read(char* buffer, std::streamsize length)
{
if (_pCurrent < _pEnd)
{
int n = (int) (_pEnd - _pCurrent);
if (n > length) n = (int) length;
memcpy(buffer, _pCurrent, n);
_pCurrent += n;
return n;
}
else return receive(buffer, (int) length);
}
int HTTPSession::write(const char* buffer, std::streamsize length)
{
try
{
return _socket.sendBytes(buffer, (int) length);
}
catch (Poco::Exception& exc)
{
setException(exc);
throw;
}
}
int HTTPSession::receive(char* buffer, int length)
{
try
{
if (_socket.poll(_timeout, Socket::SELECT_READ))
return _socket.receiveBytes(buffer, length);
else
throw TimeoutException();
}
catch (Poco::Exception& exc)
{
setException(exc);
throw;
}
}
void HTTPSession::refill()
{
if (!_pBuffer)
{
_pBuffer = HTTPBufferAllocator::allocate(HTTPBufferAllocator::BUFFER_SIZE);
}
_pCurrent = _pEnd = _pBuffer;
int n = receive(_pBuffer, HTTPBufferAllocator::BUFFER_SIZE);
_pEnd += n;
}
bool HTTPSession::connected() const
{
return _socket.impl()->initialized();
}
void HTTPSession::connect(const SocketAddress& address)
{
_socket.connect(address, _timeout);
}
void HTTPSession::abort()
{
_socket.shutdown();
close();
}
void HTTPSession::close()
{
_socket.close();
}
void HTTPSession::setException(const Poco::Exception& exc)
{
delete _pException;
_pException = exc.clone();
}
} } // namespace Poco::Net

View File

@@ -1,153 +1,153 @@
//
// HTTPSessionFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSessionFactory.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPSessionFactory
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Exception.h"
using Poco::SingletonHolder;
using Poco::FastMutex;
using Poco::NotFoundException;
using Poco::ExistsException;
namespace Poco {
namespace Net {
HTTPSessionFactory::HTTPSessionFactory():
_proxyPort(0)
{
}
HTTPSessionFactory::HTTPSessionFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPSessionFactory::~HTTPSessionFactory()
{
for (Instantiators::iterator it = _instantiators.begin(); it != _instantiators.end(); ++it)
{
delete it->second.pIn;
}
}
void HTTPSessionFactory::registerProtocol(const std::string& protocol, HTTPSessionInstantiator* pSessionInstantiator)
{
poco_assert_dbg(pSessionInstantiator);
FastMutex::ScopedLock lock(_mutex);
std::pair<Instantiators::iterator, bool> tmp = _instantiators.insert(make_pair(protocol, InstantiatorInfo(pSessionInstantiator)));
if (!tmp.second)
{
++tmp.first->second.cnt;
delete pSessionInstantiator;
}
}
void HTTPSessionFactory::unregisterProtocol(const std::string& protocol)
{
FastMutex::ScopedLock lock(_mutex);
Instantiators::iterator it = _instantiators.find(protocol);
if (it != _instantiators.end())
{
if (it->second.cnt == 1)
{
delete it->second.pIn;
_instantiators.erase(it);
}
else --it->second.cnt;
}
else throw NotFoundException("No HTTPSessionInstantiator registered for", protocol);
}
bool HTTPSessionFactory::supportsProtocol(const std::string& protocol)
{
FastMutex::ScopedLock lock(_mutex);
Instantiators::iterator it = _instantiators.find(protocol);
return it != _instantiators.end();
}
HTTPClientSession* HTTPSessionFactory::createClientSession(const Poco::URI& uri)
{
FastMutex::ScopedLock lock(_mutex);
if (uri.isRelative()) throw Poco::UnknownURISchemeException("Relative URIs are not supported by HTTPSessionFactory.");
Instantiators::iterator it = _instantiators.find(uri.getScheme());
if (it != _instantiators.end())
{
it->second.pIn->setProxy(_proxyHost, _proxyPort);
return it->second.pIn->createClientSession(uri);
}
else throw Poco::UnknownURISchemeException(uri.getScheme());
}
void HTTPSessionFactory::setProxy(const std::string& host, Poco::UInt16 port)
{
FastMutex::ScopedLock lock(_mutex);
_proxyHost = host;
_proxyPort = port;
}
HTTPSessionFactory& HTTPSessionFactory::defaultFactory()
{
static SingletonHolder<HTTPSessionFactory> singleton;
return *singleton.get();
}
HTTPSessionFactory::InstantiatorInfo::InstantiatorInfo(HTTPSessionInstantiator* pInst): pIn(pInst), cnt(1)
{
poco_check_ptr (pIn);
}
} } // namespace Poco::Net
//
// HTTPSessionFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSessionFactory.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPSessionFactory
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Exception.h"
using Poco::SingletonHolder;
using Poco::FastMutex;
using Poco::NotFoundException;
using Poco::ExistsException;
namespace Poco {
namespace Net {
HTTPSessionFactory::HTTPSessionFactory():
_proxyPort(0)
{
}
HTTPSessionFactory::HTTPSessionFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPSessionFactory::~HTTPSessionFactory()
{
for (Instantiators::iterator it = _instantiators.begin(); it != _instantiators.end(); ++it)
{
delete it->second.pIn;
}
}
void HTTPSessionFactory::registerProtocol(const std::string& protocol, HTTPSessionInstantiator* pSessionInstantiator)
{
poco_assert_dbg(pSessionInstantiator);
FastMutex::ScopedLock lock(_mutex);
std::pair<Instantiators::iterator, bool> tmp = _instantiators.insert(make_pair(protocol, InstantiatorInfo(pSessionInstantiator)));
if (!tmp.second)
{
++tmp.first->second.cnt;
delete pSessionInstantiator;
}
}
void HTTPSessionFactory::unregisterProtocol(const std::string& protocol)
{
FastMutex::ScopedLock lock(_mutex);
Instantiators::iterator it = _instantiators.find(protocol);
if (it != _instantiators.end())
{
if (it->second.cnt == 1)
{
delete it->second.pIn;
_instantiators.erase(it);
}
else --it->second.cnt;
}
else throw NotFoundException("No HTTPSessionInstantiator registered for", protocol);
}
bool HTTPSessionFactory::supportsProtocol(const std::string& protocol)
{
FastMutex::ScopedLock lock(_mutex);
Instantiators::iterator it = _instantiators.find(protocol);
return it != _instantiators.end();
}
HTTPClientSession* HTTPSessionFactory::createClientSession(const Poco::URI& uri)
{
FastMutex::ScopedLock lock(_mutex);
if (uri.isRelative()) throw Poco::UnknownURISchemeException("Relative URIs are not supported by HTTPSessionFactory.");
Instantiators::iterator it = _instantiators.find(uri.getScheme());
if (it != _instantiators.end())
{
it->second.pIn->setProxy(_proxyHost, _proxyPort);
return it->second.pIn->createClientSession(uri);
}
else throw Poco::UnknownURISchemeException(uri.getScheme());
}
void HTTPSessionFactory::setProxy(const std::string& host, Poco::UInt16 port)
{
FastMutex::ScopedLock lock(_mutex);
_proxyHost = host;
_proxyPort = port;
}
HTTPSessionFactory& HTTPSessionFactory::defaultFactory()
{
static SingletonHolder<HTTPSessionFactory> singleton;
return *singleton.get();
}
HTTPSessionFactory::InstantiatorInfo::InstantiatorInfo(HTTPSessionInstantiator* pInst): pIn(pInst), cnt(1)
{
poco_check_ptr (pIn);
}
} } // namespace Poco::Net

View File

@@ -1,88 +1,88 @@
//
// HTTPSessionInstantiator.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSessionInstantiator.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPSessionInstantiator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPClientSession.h"
using Poco::URI;
namespace Poco {
namespace Net {
HTTPSessionInstantiator::HTTPSessionInstantiator():
_proxyPort(0)
{
}
HTTPSessionInstantiator::~HTTPSessionInstantiator()
{
}
HTTPClientSession* HTTPSessionInstantiator::createClientSession(const Poco::URI& uri)
{
poco_assert (uri.getScheme() == "http");
HTTPClientSession* pSession = new HTTPClientSession(uri.getHost(), uri.getPort());
pSession->setProxy(proxyHost(), proxyPort());
return pSession;
}
void HTTPSessionInstantiator::registerInstantiator()
{
HTTPSessionFactory::defaultFactory().registerProtocol("http", new HTTPSessionInstantiator);
}
void HTTPSessionInstantiator::unregisterInstantiator()
{
HTTPSessionFactory::defaultFactory().unregisterProtocol("http");
}
void HTTPSessionInstantiator::setProxy(const std::string& host, Poco::UInt16 port)
{
_proxyHost = host;
_proxyPort = port;
}
} } // namespace Poco::Net
//
// HTTPSessionInstantiator.cpp
//
// $Id: //poco/1.2/Net/src/HTTPSessionInstantiator.cpp#1 $
//
// Library: Net
// Package: HTTPClient
// Module: HTTPSessionInstantiator
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPClientSession.h"
using Poco::URI;
namespace Poco {
namespace Net {
HTTPSessionInstantiator::HTTPSessionInstantiator():
_proxyPort(0)
{
}
HTTPSessionInstantiator::~HTTPSessionInstantiator()
{
}
HTTPClientSession* HTTPSessionInstantiator::createClientSession(const Poco::URI& uri)
{
poco_assert (uri.getScheme() == "http");
HTTPClientSession* pSession = new HTTPClientSession(uri.getHost(), uri.getPort());
pSession->setProxy(proxyHost(), proxyPort());
return pSession;
}
void HTTPSessionInstantiator::registerInstantiator()
{
HTTPSessionFactory::defaultFactory().registerProtocol("http", new HTTPSessionInstantiator);
}
void HTTPSessionInstantiator::unregisterInstantiator()
{
HTTPSessionFactory::defaultFactory().unregisterProtocol("http");
}
void HTTPSessionInstantiator::setProxy(const std::string& host, Poco::UInt16 port)
{
_proxyHost = host;
_proxyPort = port;
}
} } // namespace Poco::Net

View File

@@ -1,180 +1,180 @@
//
// HTTPStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPSession.h"
namespace Poco {
namespace Net {
//
// HTTPStreamBuf
//
HTTPStreamBuf::HTTPStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_mode(mode)
{
}
HTTPStreamBuf::~HTTPStreamBuf()
{
}
void HTTPStreamBuf::close()
{
if (_mode & std::ios::out)
{
sync();
_session.socket().shutdownSend();
}
}
int HTTPStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
return _session.read(buffer, length);
}
int HTTPStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _session.write(buffer, length);
}
//
// HTTPIOS
//
HTTPIOS::HTTPIOS(HTTPSession& session, HTTPStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPIOS::~HTTPIOS()
{
try
{
_buf.close();
}
catch (...)
{
}
}
HTTPStreamBuf* HTTPIOS::rdbuf()
{
return &_buf;
}
//
// HTTPInputStream
//
Poco::MemoryPool HTTPInputStream::_pool(sizeof(HTTPInputStream));
HTTPInputStream::HTTPInputStream(HTTPSession& session):
HTTPIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPInputStream::~HTTPInputStream()
{
}
void* HTTPInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPOutputStream
//
Poco::MemoryPool HTTPOutputStream::_pool(sizeof(HTTPOutputStream));
HTTPOutputStream::HTTPOutputStream(HTTPSession& session):
HTTPIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPOutputStream::~HTTPOutputStream()
{
}
void* HTTPOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net
//
// HTTPStream.cpp
//
// $Id: //poco/1.2/Net/src/HTTPStream.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPSession.h"
namespace Poco {
namespace Net {
//
// HTTPStreamBuf
//
HTTPStreamBuf::HTTPStreamBuf(HTTPSession& session, openmode mode):
HTTPBasicStreamBuf(HTTPBufferAllocator::BUFFER_SIZE, mode),
_session(session),
_mode(mode)
{
}
HTTPStreamBuf::~HTTPStreamBuf()
{
}
void HTTPStreamBuf::close()
{
if (_mode & std::ios::out)
{
sync();
_session.socket().shutdownSend();
}
}
int HTTPStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
return _session.read(buffer, length);
}
int HTTPStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _session.write(buffer, length);
}
//
// HTTPIOS
//
HTTPIOS::HTTPIOS(HTTPSession& session, HTTPStreamBuf::openmode mode):
_buf(session, mode)
{
poco_ios_init(&_buf);
}
HTTPIOS::~HTTPIOS()
{
try
{
_buf.close();
}
catch (...)
{
}
}
HTTPStreamBuf* HTTPIOS::rdbuf()
{
return &_buf;
}
//
// HTTPInputStream
//
Poco::MemoryPool HTTPInputStream::_pool(sizeof(HTTPInputStream));
HTTPInputStream::HTTPInputStream(HTTPSession& session):
HTTPIOS(session, std::ios::in),
std::istream(&_buf)
{
}
HTTPInputStream::~HTTPInputStream()
{
}
void* HTTPInputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPInputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
//
// HTTPOutputStream
//
Poco::MemoryPool HTTPOutputStream::_pool(sizeof(HTTPOutputStream));
HTTPOutputStream::HTTPOutputStream(HTTPSession& session):
HTTPIOS(session, std::ios::out),
std::ostream(&_buf)
{
}
HTTPOutputStream::~HTTPOutputStream()
{
}
void* HTTPOutputStream::operator new(size_t size)
{
return _pool.get();
}
void HTTPOutputStream::operator delete(void* ptr)
{
_pool.release(ptr);
}
} } // namespace Poco::Net

View File

@@ -1,128 +1,128 @@
//
// HTTPStreamFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPStreamFactory.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPStreamFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPStreamFactory::HTTPStreamFactory():
_proxyPort(HTTPSession::HTTP_PORT)
{
}
HTTPStreamFactory::HTTPStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPStreamFactory::~HTTPStreamFactory()
{
}
std::istream* HTTPStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "http");
URI resolvedURI(uri);
HTTPClientSession* pSession = 0;
try
{
int redirects = 0;
do
{
pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());
pSession->setProxy(_proxyHost, _proxyPort);
std::string path = resolvedURI.getPathAndQuery();
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
pSession->sendRequest(req);
HTTPResponse res;
std::istream& rs = pSession->receiveResponse(res);
bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY ||
res.getStatus() == HTTPResponse::HTTP_FOUND ||
res.getStatus() == HTTPResponse::HTTP_SEE_OTHER);
if (moved)
{
resolvedURI.resolve(res.get("Location"));
delete pSession;
if (resolvedURI.getScheme() != "http") throw UnsupportedRedirectException(uri.toString());
++redirects;
}
else if (res.getStatus() == HTTPResponse::HTTP_OK)
{
return new HTTPResponseStream(rs, pSession);
}
else throw HTTPException(res.getReason(), uri.toString());
}
while (redirects < MAX_REDIRECTS);
throw HTTPException("Too many redirects", uri.toString());
}
catch (...)
{
delete pSession;
throw;
}
}
void HTTPStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("http", new HTTPStreamFactory);
}
} } // namespace Poco::Net
//
// HTTPStreamFactory.cpp
//
// $Id: //poco/1.2/Net/src/HTTPStreamFactory.cpp#1 $
//
// Library: Net
// Package: HTTP
// Module: HTTPStreamFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPStreamFactory::HTTPStreamFactory():
_proxyPort(HTTPSession::HTTP_PORT)
{
}
HTTPStreamFactory::HTTPStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPStreamFactory::~HTTPStreamFactory()
{
}
std::istream* HTTPStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "http");
URI resolvedURI(uri);
HTTPClientSession* pSession = 0;
try
{
int redirects = 0;
do
{
pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());
pSession->setProxy(_proxyHost, _proxyPort);
std::string path = resolvedURI.getPathAndQuery();
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
pSession->sendRequest(req);
HTTPResponse res;
std::istream& rs = pSession->receiveResponse(res);
bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY ||
res.getStatus() == HTTPResponse::HTTP_FOUND ||
res.getStatus() == HTTPResponse::HTTP_SEE_OTHER);
if (moved)
{
resolvedURI.resolve(res.get("Location"));
delete pSession;
if (resolvedURI.getScheme() != "http") throw UnsupportedRedirectException(uri.toString());
++redirects;
}
else if (res.getStatus() == HTTPResponse::HTTP_OK)
{
return new HTTPResponseStream(rs, pSession);
}
else throw HTTPException(res.getReason(), uri.toString());
}
while (redirects < MAX_REDIRECTS);
throw HTTPException("Too many redirects", uri.toString());
}
catch (...)
{
delete pSession;
throw;
}
}
void HTTPStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("http", new HTTPStreamFactory);
}
} } // namespace Poco::Net

View File

@@ -1,130 +1,130 @@
//
// HostEntry.cpp
//
// $Id: //poco/1.2/Net/src/HostEntry.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: HostEntry
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HostEntry.h"
#include "Poco/Exception.h"
#include <algorithm>
namespace Poco {
namespace Net {
HostEntry::HostEntry()
{
}
HostEntry::HostEntry(struct hostent* entry)
{
poco_check_ptr (entry);
_name = entry->h_name;
char** alias = entry->h_aliases;
if (alias)
{
while (*alias)
{
_aliases.push_back(std::string(*alias));
++alias;
}
}
char** address = entry->h_addr_list;
if (address)
{
while (*address)
{
_addresses.push_back(IPAddress(*address, entry->h_length));
++address;
}
}
}
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
HostEntry::HostEntry(struct addrinfo* ainfo)
{
poco_check_ptr (ainfo);
for (struct addrinfo* ai = ainfo; ai; ai = ai->ai_next)
{
if (ai->ai_canonname)
_name.assign(ai->ai_canonname);
else if (ai->ai_addrlen && ai->ai_addr)
_addresses.push_back(IPAddress(ai->ai_addr, (poco_socklen_t) ai->ai_addrlen));
}
}
#endif
HostEntry::HostEntry(const HostEntry& entry):
_name(entry._name),
_aliases(entry._aliases),
_addresses(entry._addresses)
{
}
HostEntry& HostEntry::operator = (const HostEntry& entry)
{
if (&entry != this)
{
_name = entry._name;
_aliases = entry._aliases;
_addresses = entry._addresses;
}
return *this;
}
void HostEntry::swap(HostEntry& hostEntry)
{
std::swap(_name, hostEntry._name);
std::swap(_aliases, hostEntry._aliases);
std::swap(_addresses, hostEntry._addresses);
}
HostEntry::~HostEntry()
{
}
} } // namespace Poco::Net
//
// HostEntry.cpp
//
// $Id: //poco/1.2/Net/src/HostEntry.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: HostEntry
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/HostEntry.h"
#include "Poco/Exception.h"
#include <algorithm>
namespace Poco {
namespace Net {
HostEntry::HostEntry()
{
}
HostEntry::HostEntry(struct hostent* entry)
{
poco_check_ptr (entry);
_name = entry->h_name;
char** alias = entry->h_aliases;
if (alias)
{
while (*alias)
{
_aliases.push_back(std::string(*alias));
++alias;
}
}
char** address = entry->h_addr_list;
if (address)
{
while (*address)
{
_addresses.push_back(IPAddress(*address, entry->h_length));
++address;
}
}
}
#if defined(_WIN32) && defined(POCO_HAVE_IPv6)
HostEntry::HostEntry(struct addrinfo* ainfo)
{
poco_check_ptr (ainfo);
for (struct addrinfo* ai = ainfo; ai; ai = ai->ai_next)
{
if (ai->ai_canonname)
_name.assign(ai->ai_canonname);
else if (ai->ai_addrlen && ai->ai_addr)
_addresses.push_back(IPAddress(ai->ai_addr, (poco_socklen_t) ai->ai_addrlen));
}
}
#endif
HostEntry::HostEntry(const HostEntry& entry):
_name(entry._name),
_aliases(entry._aliases),
_addresses(entry._addresses)
{
}
HostEntry& HostEntry::operator = (const HostEntry& entry)
{
if (&entry != this)
{
_name = entry._name;
_aliases = entry._aliases;
_addresses = entry._addresses;
}
return *this;
}
void HostEntry::swap(HostEntry& hostEntry)
{
std::swap(_name, hostEntry._name);
std::swap(_aliases, hostEntry._aliases);
std::swap(_addresses, hostEntry._addresses);
}
HostEntry::~HostEntry()
{
}
} } // namespace Poco::Net

View File

@@ -1,166 +1,166 @@
//
// ICMPClient.cpp
//
// $Id: //poco/1.2/Net/src/ICMPClient.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPClient
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/ICMPClient.h"
#include "Poco/Net/ICMPSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/Channel.h"
#include "Poco/Message.h"
#include "Poco/Exception.h"
#include <sstream>
using Poco::Channel;
using Poco::Message;
using Poco::InvalidArgumentException;
using Poco::NotImplementedException;
using Poco::TimeoutException;
using Poco::Exception;
namespace Poco {
namespace Net {
ICMPClient::ICMPClient(IPAddress::Family family):
_family(family)
{
}
ICMPClient::~ICMPClient()
{
}
int ICMPClient::ping(const std::string& address, int repeat) const
{
if (repeat <= 0) return 0;
SocketAddress addr(address, 0);
return ping(addr, repeat);
}
int ICMPClient::ping(SocketAddress& address, int repeat) const
{
if (repeat <= 0) return 0;
ICMPSocket icmpSocket(_family);
SocketAddress returnAddress;
ICMPEventArgs eventArgs(address, repeat, icmpSocket.dataSize(), icmpSocket.ttl());
pingBegin.notify(this, eventArgs);
for (int i = 0; i < repeat; ++i)
{
icmpSocket.sendTo(address);
++eventArgs;
try
{
int t = icmpSocket.receiveFrom(returnAddress);
eventArgs.setReplyTime(i, t);
pingReply.notify(this, eventArgs);
}
catch (TimeoutException&)
{
std::ostringstream os;
os << address.host().toString() << ": Request timed out.";
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
catch (ICMPException& ex)
{
std::ostringstream os;
os << address.host().toString() << ": " << ex.what();
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
catch (Exception& ex)
{
std::ostringstream os;
os << ex.displayText();
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
}
pingEnd.notify(this, eventArgs);
return eventArgs.received();
}
int ICMPClient::pingIPv4(const std::string& address, int repeat)
{
if (repeat <= 0) return 0;
SocketAddress a(address, 0);
return ping(a, IPAddress::IPv4, repeat);
}
int ICMPClient::ping(SocketAddress& address, IPAddress::Family family, int repeat)
{
if (repeat <= 0) return 0;
ICMPSocket icmpSocket(family);
SocketAddress returnAddress;
int received = 0;
for (int i = 0; i < repeat; ++i)
{
icmpSocket.sendTo(address);
try
{
icmpSocket.receiveFrom(returnAddress);
++received;
}
catch (TimeoutException&)
{
}
catch (ICMPException&)
{
}
}
return received;
}
} } // namespace Poco::Net
//
// ICMPClient.cpp
//
// $Id: //poco/1.2/Net/src/ICMPClient.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPClient
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/ICMPClient.h"
#include "Poco/Net/ICMPSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/Channel.h"
#include "Poco/Message.h"
#include "Poco/Exception.h"
#include <sstream>
using Poco::Channel;
using Poco::Message;
using Poco::InvalidArgumentException;
using Poco::NotImplementedException;
using Poco::TimeoutException;
using Poco::Exception;
namespace Poco {
namespace Net {
ICMPClient::ICMPClient(IPAddress::Family family):
_family(family)
{
}
ICMPClient::~ICMPClient()
{
}
int ICMPClient::ping(const std::string& address, int repeat) const
{
if (repeat <= 0) return 0;
SocketAddress addr(address, 0);
return ping(addr, repeat);
}
int ICMPClient::ping(SocketAddress& address, int repeat) const
{
if (repeat <= 0) return 0;
ICMPSocket icmpSocket(_family);
SocketAddress returnAddress;
ICMPEventArgs eventArgs(address, repeat, icmpSocket.dataSize(), icmpSocket.ttl());
pingBegin.notify(this, eventArgs);
for (int i = 0; i < repeat; ++i)
{
icmpSocket.sendTo(address);
++eventArgs;
try
{
int t = icmpSocket.receiveFrom(returnAddress);
eventArgs.setReplyTime(i, t);
pingReply.notify(this, eventArgs);
}
catch (TimeoutException&)
{
std::ostringstream os;
os << address.host().toString() << ": Request timed out.";
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
catch (ICMPException& ex)
{
std::ostringstream os;
os << address.host().toString() << ": " << ex.what();
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
catch (Exception& ex)
{
std::ostringstream os;
os << ex.displayText();
eventArgs.setError(i, os.str());
pingError.notify(this, eventArgs);
continue;
}
}
pingEnd.notify(this, eventArgs);
return eventArgs.received();
}
int ICMPClient::pingIPv4(const std::string& address, int repeat)
{
if (repeat <= 0) return 0;
SocketAddress a(address, 0);
return ping(a, IPAddress::IPv4, repeat);
}
int ICMPClient::ping(SocketAddress& address, IPAddress::Family family, int repeat)
{
if (repeat <= 0) return 0;
ICMPSocket icmpSocket(family);
SocketAddress returnAddress;
int received = 0;
for (int i = 0; i < repeat; ++i)
{
icmpSocket.sendTo(address);
try
{
icmpSocket.receiveFrom(returnAddress);
++received;
}
catch (TimeoutException&)
{
}
catch (ICMPException&)
{
}
}
return received;
}
} } // namespace Poco::Net

View File

@@ -1,195 +1,195 @@
//
// ICMPEventArgs.cpp
//
// $Id: //poco/1.2/Net/src/ICMPEventArgs.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPEventArgs
//
// Implementation of ICMPEventArgs
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPEventArgs.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/DNS.h"
#include "Poco/Exception.h"
#include "Poco/Net/NetException.h"
using Poco::IOException;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ICMPEventArgs::ICMPEventArgs(const SocketAddress& address, int repetitions, int dataSize, int ttl):
_address(address),
_sent(0),
_dataSize(dataSize),
_ttl(ttl),
_rtt(0, repetitions),
_errors(repetitions)
{
}
ICMPEventArgs::~ICMPEventArgs()
{
}
std::string ICMPEventArgs::hostName() const
{
try
{
return DNS::resolve(_address.host().toString()).name();
}
catch (HostNotFoundException&)
{
}
catch (NoAddressFoundException&)
{
}
catch (DNSException&)
{
}
catch (IOException&)
{
}
return _address.host().toString();
}
std::string ICMPEventArgs::hostAddress() const
{
return _address.host().toString();
}
void ICMPEventArgs::setRepetitions(int repetitions)
{
_rtt.apply(&ICMPEventArgs::zeroVal);
if (_rtt.size() != repetitions) _rtt.resize(repetitions, 0);
_errors.assign(repetitions, "");
}
ICMPEventArgs& ICMPEventArgs::operator ++ ()
{
++_sent;
return *this;
}
ICMPEventArgs ICMPEventArgs::operator ++ (int)
{
ICMPEventArgs prev(*this);
operator ++ ();
return prev;
}
int ICMPEventArgs::received() const
{
int received = 0;
for (int i = 0; i < _rtt.size(); ++i)
{
if (_rtt[i]) ++received;
}
return received;
}
void ICMPEventArgs::setError(int index, const std::string& text)
{
if (index >= _errors.size())
throw InvalidArgumentException("Supplied index exceeds vector capacity.");
_errors[index] = text;
}
const std::string& ICMPEventArgs::error(int index) const
{
if (0 == _errors.size())
throw InvalidArgumentException("Supplied index exceeds vector capacity.");
if (-1 == index) index = _sent - 1;
return _errors[index];
}
void ICMPEventArgs::setReplyTime(int index, int time)
{
if (index >= _rtt.size())
throw InvalidArgumentException("Supplied index exceeds array capacity.");
if (0 == time) time = 1;
_rtt[index] = time;
}
int ICMPEventArgs::replyTime(int index) const
{
if (0 == _rtt.size())
throw InvalidArgumentException("Supplied index exceeds array capacity.");
if (-1 == index) index = _sent - 1;
return _rtt[index];
}
int ICMPEventArgs::avgRTT() const
{
if (0 == _rtt.size()) return 0;
return (int) (_rtt.sum() / _rtt.size());
}
float ICMPEventArgs::percent() const
{
if (0 == _rtt.size()) return 0;
return ((float) received() / (float) _rtt.size()) * (float) 100.0;
}
int ICMPEventArgs::zeroVal(int n)
{
return n*0;
}
} } // namespace Poco::Net
//
// ICMPEventArgs.cpp
//
// $Id: //poco/1.2/Net/src/ICMPEventArgs.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPEventArgs
//
// Implementation of ICMPEventArgs
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPEventArgs.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/DNS.h"
#include "Poco/Exception.h"
#include "Poco/Net/NetException.h"
using Poco::IOException;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ICMPEventArgs::ICMPEventArgs(const SocketAddress& address, int repetitions, int dataSize, int ttl):
_address(address),
_sent(0),
_dataSize(dataSize),
_ttl(ttl),
_rtt(0, repetitions),
_errors(repetitions)
{
}
ICMPEventArgs::~ICMPEventArgs()
{
}
std::string ICMPEventArgs::hostName() const
{
try
{
return DNS::resolve(_address.host().toString()).name();
}
catch (HostNotFoundException&)
{
}
catch (NoAddressFoundException&)
{
}
catch (DNSException&)
{
}
catch (IOException&)
{
}
return _address.host().toString();
}
std::string ICMPEventArgs::hostAddress() const
{
return _address.host().toString();
}
void ICMPEventArgs::setRepetitions(int repetitions)
{
_rtt.apply(&ICMPEventArgs::zeroVal);
if (_rtt.size() != repetitions) _rtt.resize(repetitions, 0);
_errors.assign(repetitions, "");
}
ICMPEventArgs& ICMPEventArgs::operator ++ ()
{
++_sent;
return *this;
}
ICMPEventArgs ICMPEventArgs::operator ++ (int)
{
ICMPEventArgs prev(*this);
operator ++ ();
return prev;
}
int ICMPEventArgs::received() const
{
int received = 0;
for (int i = 0; i < _rtt.size(); ++i)
{
if (_rtt[i]) ++received;
}
return received;
}
void ICMPEventArgs::setError(int index, const std::string& text)
{
if (index >= _errors.size())
throw InvalidArgumentException("Supplied index exceeds vector capacity.");
_errors[index] = text;
}
const std::string& ICMPEventArgs::error(int index) const
{
if (0 == _errors.size())
throw InvalidArgumentException("Supplied index exceeds vector capacity.");
if (-1 == index) index = _sent - 1;
return _errors[index];
}
void ICMPEventArgs::setReplyTime(int index, int time)
{
if (index >= _rtt.size())
throw InvalidArgumentException("Supplied index exceeds array capacity.");
if (0 == time) time = 1;
_rtt[index] = time;
}
int ICMPEventArgs::replyTime(int index) const
{
if (0 == _rtt.size())
throw InvalidArgumentException("Supplied index exceeds array capacity.");
if (-1 == index) index = _sent - 1;
return _rtt[index];
}
int ICMPEventArgs::avgRTT() const
{
if (0 == _rtt.size()) return 0;
return (int) (_rtt.sum() / _rtt.size());
}
float ICMPEventArgs::percent() const
{
if (0 == _rtt.size()) return 0;
return ((float) received() / (float) _rtt.size()) * (float) 100.0;
}
int ICMPEventArgs::zeroVal(int n)
{
return n*0;
}
} } // namespace Poco::Net

View File

@@ -1,134 +1,134 @@
//
// ICMPPacket.cpp
//
// $Id: //poco/1.2/Net/src/ICMPPacket.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPPacket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPPacket.h"
#include "Poco/Net/ICMPv4PacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::NotImplementedException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
ICMPPacket::ICMPPacket(IPAddress::Family family, int dataSize):_pImpl(0)
{
if (family == IPAddress::IPv4)
_pImpl = new ICMPv4PacketImpl(dataSize);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
throw NotImplementedException("ICMPv6 packets not implemented.");
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to ICMPPacket");
}
ICMPPacket::~ICMPPacket()
{
delete _pImpl;
}
void ICMPPacket::setDataSize(int dataSize)
{
_pImpl->setDataSize(dataSize);
}
int ICMPPacket::getDataSize() const
{
return _pImpl->getDataSize();
}
int ICMPPacket::packetSize() const
{
return _pImpl->packetSize();
}
int ICMPPacket::maxPacketSize() const
{
return _pImpl->maxPacketSize();
}
const Poco::UInt8* ICMPPacket::packet()
{
return _pImpl->packet();
}
struct timeval ICMPPacket::time(Poco::UInt8* buffer, int length) const
{
return _pImpl->time(buffer, length);
}
bool ICMPPacket::validReplyID(Poco::UInt8* buffer, int length) const
{
return _pImpl->validReplyID(buffer, length);
}
std::string ICMPPacket::errorDescription(Poco::UInt8* buffer, int length)
{
return _pImpl->errorDescription(buffer, length);
}
std::string ICMPPacket::typeDescription(int typeId)
{
return _pImpl->typeDescription(typeId);
}
} } // namespace Poco::Net
//
// ICMPPacket.cpp
//
// $Id: //poco/1.2/Net/src/ICMPPacket.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPPacket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPPacket.h"
#include "Poco/Net/ICMPv4PacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::NotImplementedException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
ICMPPacket::ICMPPacket(IPAddress::Family family, int dataSize):_pImpl(0)
{
if (family == IPAddress::IPv4)
_pImpl = new ICMPv4PacketImpl(dataSize);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
throw NotImplementedException("ICMPv6 packets not implemented.");
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to ICMPPacket");
}
ICMPPacket::~ICMPPacket()
{
delete _pImpl;
}
void ICMPPacket::setDataSize(int dataSize)
{
_pImpl->setDataSize(dataSize);
}
int ICMPPacket::getDataSize() const
{
return _pImpl->getDataSize();
}
int ICMPPacket::packetSize() const
{
return _pImpl->packetSize();
}
int ICMPPacket::maxPacketSize() const
{
return _pImpl->maxPacketSize();
}
const Poco::UInt8* ICMPPacket::packet()
{
return _pImpl->packet();
}
struct timeval ICMPPacket::time(Poco::UInt8* buffer, int length) const
{
return _pImpl->time(buffer, length);
}
bool ICMPPacket::validReplyID(Poco::UInt8* buffer, int length) const
{
return _pImpl->validReplyID(buffer, length);
}
std::string ICMPPacket::errorDescription(Poco::UInt8* buffer, int length)
{
return _pImpl->errorDescription(buffer, length);
}
std::string ICMPPacket::typeDescription(int typeId)
{
return _pImpl->typeDescription(typeId);
}
} } // namespace Poco::Net

View File

@@ -1,127 +1,127 @@
//
// ICMPPacketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPPacketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPPacketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPPacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
const UInt16 ICMPPacketImpl::MAX_PACKET_SIZE = 4096;
const UInt16 ICMPPacketImpl::MAX_SEQ_VALUE = 65535;
ICMPPacketImpl::ICMPPacketImpl(int dataSize):
_seq(0),
_pPacket(new UInt8[MAX_PACKET_SIZE]),
_dataSize(dataSize)
{
if (_dataSize > MAX_PACKET_SIZE)
throw InvalidArgumentException("Packet size must be <= " + NumberFormatter::format(MAX_PACKET_SIZE));
}
ICMPPacketImpl::~ICMPPacketImpl()
{
delete _pPacket;
}
void ICMPPacketImpl::setDataSize(int dataSize)
{
_dataSize = dataSize;
initPacket();
}
int ICMPPacketImpl::getDataSize() const
{
return _dataSize;
}
const Poco::UInt8* ICMPPacketImpl::packet(bool init)
{
if (init) initPacket();
return _pPacket;
}
unsigned short ICMPPacketImpl::checksum(UInt16 *addr, Int32 len)
{
Int32 nleft = len;
UInt16* w = addr;
UInt16 answer;
Int32 sum = 0;
while (nleft > 1)
{
sum += *w++;
nleft -= sizeof(UInt16);
}
if (nleft == 1)
{
UInt16 u = 0;
*(UInt8*) (&u) = *(UInt8*) w;
sum += u;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
} } // namespace Poco::Net
//
// ICMPPacketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPPacketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPPacketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPPacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
const UInt16 ICMPPacketImpl::MAX_PACKET_SIZE = 4096;
const UInt16 ICMPPacketImpl::MAX_SEQ_VALUE = 65535;
ICMPPacketImpl::ICMPPacketImpl(int dataSize):
_seq(0),
_pPacket(new UInt8[MAX_PACKET_SIZE]),
_dataSize(dataSize)
{
if (_dataSize > MAX_PACKET_SIZE)
throw InvalidArgumentException("Packet size must be <= " + NumberFormatter::format(MAX_PACKET_SIZE));
}
ICMPPacketImpl::~ICMPPacketImpl()
{
delete _pPacket;
}
void ICMPPacketImpl::setDataSize(int dataSize)
{
_dataSize = dataSize;
initPacket();
}
int ICMPPacketImpl::getDataSize() const
{
return _dataSize;
}
const Poco::UInt8* ICMPPacketImpl::packet(bool init)
{
if (init) initPacket();
return _pPacket;
}
unsigned short ICMPPacketImpl::checksum(UInt16 *addr, Int32 len)
{
Int32 nleft = len;
UInt16* w = addr;
UInt16 answer;
Int32 sum = 0;
while (nleft > 1)
{
sum += *w++;
nleft -= sizeof(UInt16);
}
if (nleft == 1)
{
UInt16 u = 0;
*(UInt8*) (&u) = *(UInt8*) w;
sum += u;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
} } // namespace Poco::Net

View File

@@ -1,101 +1,101 @@
//
// ICMPSocket.cpp
//
// $Id: //poco/1.2/Net/src/ICMPSocket.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPSocket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPSocket.h"
#include "Poco/Net/ICMPSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ICMPSocket::ICMPSocket(IPAddress::Family family, int dataSize, int ttl, int timeout):
Socket(new ICMPSocketImpl(family, dataSize, ttl, timeout)),
_dataSize(dataSize),
_ttl(ttl),
_timeout(timeout)
{
}
ICMPSocket::ICMPSocket(const Socket& socket):
Socket(socket)
{
if (!dynamic_cast<ICMPSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ICMPSocket::ICMPSocket(SocketImpl* pImpl):
Socket(pImpl)
{
if (!dynamic_cast<ICMPSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ICMPSocket::~ICMPSocket()
{
}
ICMPSocket& ICMPSocket::operator = (const Socket& socket)
{
if (dynamic_cast<ICMPSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
int ICMPSocket::sendTo(const SocketAddress& address, int flags)
{
return impl()->sendTo(0, 0, address, flags);
}
int ICMPSocket::receiveFrom(SocketAddress& address, int flags)
{
return impl()->receiveFrom(0, 0, address, flags);
}
} } // namespace Poco::Net
//
// ICMPSocket.cpp
//
// $Id: //poco/1.2/Net/src/ICMPSocket.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPSocket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPSocket.h"
#include "Poco/Net/ICMPSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ICMPSocket::ICMPSocket(IPAddress::Family family, int dataSize, int ttl, int timeout):
Socket(new ICMPSocketImpl(family, dataSize, ttl, timeout)),
_dataSize(dataSize),
_ttl(ttl),
_timeout(timeout)
{
}
ICMPSocket::ICMPSocket(const Socket& socket):
Socket(socket)
{
if (!dynamic_cast<ICMPSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ICMPSocket::ICMPSocket(SocketImpl* pImpl):
Socket(pImpl)
{
if (!dynamic_cast<ICMPSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ICMPSocket::~ICMPSocket()
{
}
ICMPSocket& ICMPSocket::operator = (const Socket& socket)
{
if (dynamic_cast<ICMPSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
int ICMPSocket::sendTo(const SocketAddress& address, int flags)
{
return impl()->sendTo(0, 0, address, flags);
}
int ICMPSocket::receiveFrom(SocketAddress& address, int flags)
{
return impl()->receiveFrom(0, 0, address, flags);
}
} } // namespace Poco::Net

View File

@@ -1,111 +1,111 @@
//
// ICMPSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPSocketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPSocketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPSocketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
using Poco::TimeoutException;
using Poco::Timespan;
using Poco::Exception;
namespace Poco {
namespace Net {
ICMPSocketImpl::ICMPSocketImpl(IPAddress::Family family, int dataSize, int ttl, int timeout):
RawSocketImpl(family, IPPROTO_ICMP),
_icmpPacket(family, dataSize)
{
setOption(IPPROTO_IP, IP_TTL, ttl);
setReceiveTimeout(Timespan(timeout));
}
ICMPSocketImpl::~ICMPSocketImpl()
{
}
int ICMPSocketImpl::sendTo(const void*, int, const SocketAddress& address, int flags)
{
int n = SocketImpl::sendTo(_icmpPacket.packet(), _icmpPacket.packetSize(), address, flags);
return n;
}
int ICMPSocketImpl::receiveFrom(void*, int, SocketAddress& address, int flags)
{
int maxPacketSize = _icmpPacket.maxPacketSize();
unsigned char* buffer = new unsigned char[maxPacketSize];
try
{
do
{
SocketImpl::receiveFrom(buffer, maxPacketSize, address, flags);
}
while(!_icmpPacket.validReplyID(buffer, maxPacketSize));
}
catch (TimeoutException&)
{
delete[] buffer;
throw;
}
catch (Exception&)
{
std::string err = _icmpPacket.errorDescription(buffer, maxPacketSize);
delete[] buffer;
if (!err.empty())
throw ICMPException(err);
else
throw;
}
struct timeval then = _icmpPacket.time(buffer, maxPacketSize);
struct timeval now = _icmpPacket.time();
int elapsed = (((now.tv_sec * 1000000) + now.tv_usec) - ((then.tv_sec * 1000000) + then.tv_usec))/1000;
delete[] buffer;
return elapsed;
}
} } // namespace Poco::Net
//
// ICMPSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPSocketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPSocketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPSocketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
using Poco::TimeoutException;
using Poco::Timespan;
using Poco::Exception;
namespace Poco {
namespace Net {
ICMPSocketImpl::ICMPSocketImpl(IPAddress::Family family, int dataSize, int ttl, int timeout):
RawSocketImpl(family, IPPROTO_ICMP),
_icmpPacket(family, dataSize)
{
setOption(IPPROTO_IP, IP_TTL, ttl);
setReceiveTimeout(Timespan(timeout));
}
ICMPSocketImpl::~ICMPSocketImpl()
{
}
int ICMPSocketImpl::sendTo(const void*, int, const SocketAddress& address, int flags)
{
int n = SocketImpl::sendTo(_icmpPacket.packet(), _icmpPacket.packetSize(), address, flags);
return n;
}
int ICMPSocketImpl::receiveFrom(void*, int, SocketAddress& address, int flags)
{
int maxPacketSize = _icmpPacket.maxPacketSize();
unsigned char* buffer = new unsigned char[maxPacketSize];
try
{
do
{
SocketImpl::receiveFrom(buffer, maxPacketSize, address, flags);
}
while(!_icmpPacket.validReplyID(buffer, maxPacketSize));
}
catch (TimeoutException&)
{
delete[] buffer;
throw;
}
catch (Exception&)
{
std::string err = _icmpPacket.errorDescription(buffer, maxPacketSize);
delete[] buffer;
if (!err.empty())
throw ICMPException(err);
else
throw;
}
struct timeval then = _icmpPacket.time(buffer, maxPacketSize);
struct timeval now = _icmpPacket.time();
int elapsed = (((now.tv_sec * 1000000) + now.tv_usec) - ((then.tv_sec * 1000000) + then.tv_usec))/1000;
delete[] buffer;
return elapsed;
}
} } // namespace Poco::Net

View File

@@ -1,275 +1,275 @@
//
// ICMPv4PacketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPv4PacketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPv4PacketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPv4PacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
const UInt8 ICMPv4PacketImpl::DESTINATION_UNREACHABLE_TYPE = 3;
const Poco::UInt8 ICMPv4PacketImpl::SOURCE_QUENCH_TYPE = 4;
const Poco::UInt8 ICMPv4PacketImpl::REDIRECT_MESSAGE_TYPE = 5;
const UInt8 ICMPv4PacketImpl::TIME_EXCEEDED_TYPE = 11;
const Poco::UInt8 ICMPv4PacketImpl::PARAMETER_PROBLEM_TYPE = 12;
const std::string ICMPv4PacketImpl::MESSAGE_TYPE[] =
{
"Echo Reply",
"ICMP 1",
"ICMP 2",
"Dest Unreachable",
"Source Quench",
"Redirect",
"ICMP 6",
"ICMP 7",
"Echo",
"ICMP 9",
"ICMP 10",
"Time Exceeded",
"Parameter Problem",
"Timestamp",
"Timestamp Reply",
"Info Request",
"Info Reply",
"Unknown type"
};
const std::string ICMPv4PacketImpl::DESTINATION_UNREACHABLE_CODE[] =
{
"Net unreachable",
"Host unreachable",
"Protocol unreachable",
"Port unreachable",
"Fragmentation needed and DF set",
"Source route failed",
"Unknown code"
};
const std::string ICMPv4PacketImpl::REDIRECT_MESSAGE_CODE[] =
{
"Redirect datagrams for the network",
"Redirect datagrams for the host",
"Redirect datagrams for the type of service and network",
"Redirect datagrams for the type of service and host",
"Unknown code"
};
const std::string ICMPv4PacketImpl::TIME_EXCEEDED_CODE[] =
{
"Time to live exceeded in transit",
"Fragment reassembly time exceeded",
"Unknown code"
};
const std::string ICMPv4PacketImpl::PARAMETER_PROBLEM_CODE[] =
{
"Pointer indicates the error",
"Unknown code"
};
ICMPv4PacketImpl::ICMPv4PacketImpl(int dataSize):
ICMPPacketImpl(dataSize)
{
initPacket();
}
ICMPv4PacketImpl::~ICMPv4PacketImpl()
{
}
int ICMPv4PacketImpl::packetSize() const
{
return getDataSize() + sizeof(Header);
}
void ICMPv4PacketImpl::initPacket()
{
if (_seq >= MAX_SEQ_VALUE) resetSequence();
Header* icp = (Header*) packet(false);
icp->type = ECHO;
icp->code = 0;
icp->checksum = 0;
icp->seq = ++_seq;
icp->id = static_cast<UInt16>(Process::id());
struct timeval* ptp = (struct timeval *) (icp + 1);
*ptp = time();
icp->checksum = checksum((UInt16*) icp, getDataSize() + sizeof(Header));
}
struct timeval ICMPv4PacketImpl::time(Poco::UInt8* buffer, int length) const
{
struct timeval tv;
if (0 == buffer || 0 == length)
{
Timespan value(Timestamp().epochMicroseconds());
tv.tv_sec = (long) value.totalSeconds();
tv.tv_usec = (long) value.useconds();
}
else
{
struct timeval* ptv = (struct timeval*) data(buffer, length);
if (ptv) tv = *ptv;
else throw InvalidArgumentException("Invalid packet.");
}
return tv;
}
ICMPv4PacketImpl::Header* ICMPv4PacketImpl::header(Poco::UInt8* buffer, int length) const
{
poco_check_ptr (buffer);
int offset = (buffer[0] & 0x0F) * 4;
if ((offset + sizeof(Header)) > length) return 0;
buffer += offset;
return (Header *) buffer;
}
Poco::UInt8* ICMPv4PacketImpl::data(Poco::UInt8* buffer, int length) const
{
return ((Poco::UInt8*) header(buffer, length)) + sizeof(Header);
}
bool ICMPv4PacketImpl::validReplyID(Poco::UInt8* buffer, int length) const
{
Header *icp = header(buffer, length);
return icp && (Process::id() == icp->id);
}
std::string ICMPv4PacketImpl::errorDescription(unsigned char* buffer, int length)
{
Header *icp = header(buffer, length);
if (!icp) return "Invalid header.";
if (ECHO_REPLY == icp->type) return std::string(); // not an error
UInt8 pointer = 0;
if (PARAMETER_PROBLEM == icp->type)
{
UInt8 mask = 0x00FF;
pointer = icp->id & mask;
}
MessageType type = static_cast<MessageType>(icp->type);
int code = icp->code;
std::ostringstream err;
switch (type)
{
case DESTINATION_UNREACHABLE_TYPE:
if (code >= NET_UNREACHABLE && code < DESTINATION_UNREACHABLE_UNKNOWN)
err << DESTINATION_UNREACHABLE_CODE[code];
else
err << DESTINATION_UNREACHABLE_CODE[DESTINATION_UNREACHABLE_UNKNOWN];
break;
case SOURCE_QUENCH_TYPE:
err << "Source quench";
break;
case REDIRECT_MESSAGE_TYPE:
if (code >= REDIRECT_NETWORK && code < REDIRECT_MESSAGE_UNKNOWN)
err << REDIRECT_MESSAGE_CODE[code];
else
err << REDIRECT_MESSAGE_CODE[REDIRECT_MESSAGE_UNKNOWN];
break;
case TIME_EXCEEDED_TYPE:
if (code >= TIME_TO_LIVE || code < TIME_EXCEEDED_UNKNOWN)
err << TIME_EXCEEDED_CODE[code];
else
err << TIME_EXCEEDED_CODE[TIME_EXCEEDED_UNKNOWN];
break;
case PARAMETER_PROBLEM_TYPE:
if (POINTER_INDICATES_THE_ERROR != code)
code = PARAMETER_PROBLEM_UNKNOWN;
err << PARAMETER_PROBLEM_CODE[code] << ": error in octet #" << pointer;
break;
default:
err << "Unknown type.";
break;
}
return err.str();
}
std::string ICMPv4PacketImpl::typeDescription(int typeId)
{
poco_assert (typeId >= ECHO_REPLY && typeId < MESSAGE_TYPE_LENGTH);
return MESSAGE_TYPE[typeId];
}
} } // namespace Poco::Net
//
// ICMPv4PacketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ICMPv4PacketImpl.cpp#1 $
//
// Library: Net
// Package: ICMP
// Module: ICMPv4PacketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ICMPv4PacketImpl.h"
#include "Poco/Net/NetException.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Process.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::InvalidArgumentException;
using Poco::Timestamp;
using Poco::Timespan;
using Poco::Process;
using Poco::NumberFormatter;
using Poco::UInt8;
using Poco::UInt16;
using Poco::Int32;
namespace Poco {
namespace Net {
const UInt8 ICMPv4PacketImpl::DESTINATION_UNREACHABLE_TYPE = 3;
const Poco::UInt8 ICMPv4PacketImpl::SOURCE_QUENCH_TYPE = 4;
const Poco::UInt8 ICMPv4PacketImpl::REDIRECT_MESSAGE_TYPE = 5;
const UInt8 ICMPv4PacketImpl::TIME_EXCEEDED_TYPE = 11;
const Poco::UInt8 ICMPv4PacketImpl::PARAMETER_PROBLEM_TYPE = 12;
const std::string ICMPv4PacketImpl::MESSAGE_TYPE[] =
{
"Echo Reply",
"ICMP 1",
"ICMP 2",
"Dest Unreachable",
"Source Quench",
"Redirect",
"ICMP 6",
"ICMP 7",
"Echo",
"ICMP 9",
"ICMP 10",
"Time Exceeded",
"Parameter Problem",
"Timestamp",
"Timestamp Reply",
"Info Request",
"Info Reply",
"Unknown type"
};
const std::string ICMPv4PacketImpl::DESTINATION_UNREACHABLE_CODE[] =
{
"Net unreachable",
"Host unreachable",
"Protocol unreachable",
"Port unreachable",
"Fragmentation needed and DF set",
"Source route failed",
"Unknown code"
};
const std::string ICMPv4PacketImpl::REDIRECT_MESSAGE_CODE[] =
{
"Redirect datagrams for the network",
"Redirect datagrams for the host",
"Redirect datagrams for the type of service and network",
"Redirect datagrams for the type of service and host",
"Unknown code"
};
const std::string ICMPv4PacketImpl::TIME_EXCEEDED_CODE[] =
{
"Time to live exceeded in transit",
"Fragment reassembly time exceeded",
"Unknown code"
};
const std::string ICMPv4PacketImpl::PARAMETER_PROBLEM_CODE[] =
{
"Pointer indicates the error",
"Unknown code"
};
ICMPv4PacketImpl::ICMPv4PacketImpl(int dataSize):
ICMPPacketImpl(dataSize)
{
initPacket();
}
ICMPv4PacketImpl::~ICMPv4PacketImpl()
{
}
int ICMPv4PacketImpl::packetSize() const
{
return getDataSize() + sizeof(Header);
}
void ICMPv4PacketImpl::initPacket()
{
if (_seq >= MAX_SEQ_VALUE) resetSequence();
Header* icp = (Header*) packet(false);
icp->type = ECHO;
icp->code = 0;
icp->checksum = 0;
icp->seq = ++_seq;
icp->id = static_cast<UInt16>(Process::id());
struct timeval* ptp = (struct timeval *) (icp + 1);
*ptp = time();
icp->checksum = checksum((UInt16*) icp, getDataSize() + sizeof(Header));
}
struct timeval ICMPv4PacketImpl::time(Poco::UInt8* buffer, int length) const
{
struct timeval tv;
if (0 == buffer || 0 == length)
{
Timespan value(Timestamp().epochMicroseconds());
tv.tv_sec = (long) value.totalSeconds();
tv.tv_usec = (long) value.useconds();
}
else
{
struct timeval* ptv = (struct timeval*) data(buffer, length);
if (ptv) tv = *ptv;
else throw InvalidArgumentException("Invalid packet.");
}
return tv;
}
ICMPv4PacketImpl::Header* ICMPv4PacketImpl::header(Poco::UInt8* buffer, int length) const
{
poco_check_ptr (buffer);
int offset = (buffer[0] & 0x0F) * 4;
if ((offset + sizeof(Header)) > length) return 0;
buffer += offset;
return (Header *) buffer;
}
Poco::UInt8* ICMPv4PacketImpl::data(Poco::UInt8* buffer, int length) const
{
return ((Poco::UInt8*) header(buffer, length)) + sizeof(Header);
}
bool ICMPv4PacketImpl::validReplyID(Poco::UInt8* buffer, int length) const
{
Header *icp = header(buffer, length);
return icp && (Process::id() == icp->id);
}
std::string ICMPv4PacketImpl::errorDescription(unsigned char* buffer, int length)
{
Header *icp = header(buffer, length);
if (!icp) return "Invalid header.";
if (ECHO_REPLY == icp->type) return std::string(); // not an error
UInt8 pointer = 0;
if (PARAMETER_PROBLEM == icp->type)
{
UInt8 mask = 0x00FF;
pointer = icp->id & mask;
}
MessageType type = static_cast<MessageType>(icp->type);
int code = icp->code;
std::ostringstream err;
switch (type)
{
case DESTINATION_UNREACHABLE_TYPE:
if (code >= NET_UNREACHABLE && code < DESTINATION_UNREACHABLE_UNKNOWN)
err << DESTINATION_UNREACHABLE_CODE[code];
else
err << DESTINATION_UNREACHABLE_CODE[DESTINATION_UNREACHABLE_UNKNOWN];
break;
case SOURCE_QUENCH_TYPE:
err << "Source quench";
break;
case REDIRECT_MESSAGE_TYPE:
if (code >= REDIRECT_NETWORK && code < REDIRECT_MESSAGE_UNKNOWN)
err << REDIRECT_MESSAGE_CODE[code];
else
err << REDIRECT_MESSAGE_CODE[REDIRECT_MESSAGE_UNKNOWN];
break;
case TIME_EXCEEDED_TYPE:
if (code >= TIME_TO_LIVE || code < TIME_EXCEEDED_UNKNOWN)
err << TIME_EXCEEDED_CODE[code];
else
err << TIME_EXCEEDED_CODE[TIME_EXCEEDED_UNKNOWN];
break;
case PARAMETER_PROBLEM_TYPE:
if (POINTER_INDICATES_THE_ERROR != code)
code = PARAMETER_PROBLEM_UNKNOWN;
err << PARAMETER_PROBLEM_CODE[code] << ": error in octet #" << pointer;
break;
default:
err << "Unknown type.";
break;
}
return err.str();
}
std::string ICMPv4PacketImpl::typeDescription(int typeId)
{
poco_assert (typeId >= ECHO_REPLY && typeId < MESSAGE_TYPE_LENGTH);
return MESSAGE_TYPE[typeId];
}
} } // namespace Poco::Net

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,116 +1,116 @@
//
// MailRecipient.cpp
//
// $Id: //poco/1.2/Net/src/MailRecipient.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: MailRecipient
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MailRecipient.h"
#include <algorithm>
namespace Poco {
namespace Net {
MailRecipient::MailRecipient():
_type(PRIMARY_RECIPIENT)
{
}
MailRecipient::MailRecipient(const MailRecipient& recipient):
_address(recipient._address),
_realName(recipient._realName),
_type(recipient._type)
{
}
MailRecipient::MailRecipient(RecipientType type, const std::string& address):
_address(address),
_type(type)
{
}
MailRecipient::MailRecipient(RecipientType type, const std::string& address, const std::string& realName):
_address(address),
_realName(realName),
_type(type)
{
}
MailRecipient::~MailRecipient()
{
}
MailRecipient& MailRecipient::operator = (const MailRecipient& recipient)
{
if (this != &recipient)
{
MailRecipient tmp(recipient);
swap(tmp);
}
return *this;
}
void MailRecipient::swap(MailRecipient& recipient)
{
std::swap(_type, recipient._type);
std::swap(_address, recipient._address);
std::swap(_realName, recipient._realName);
}
void MailRecipient::setType(RecipientType type)
{
_type = type;
}
void MailRecipient::setAddress(const std::string& address)
{
_address = address;
}
void MailRecipient::setRealName(const std::string& realName)
{
_realName = realName;
}
} } // namespace Poco::Net
//
// MailRecipient.cpp
//
// $Id: //poco/1.2/Net/src/MailRecipient.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: MailRecipient
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MailRecipient.h"
#include <algorithm>
namespace Poco {
namespace Net {
MailRecipient::MailRecipient():
_type(PRIMARY_RECIPIENT)
{
}
MailRecipient::MailRecipient(const MailRecipient& recipient):
_address(recipient._address),
_realName(recipient._realName),
_type(recipient._type)
{
}
MailRecipient::MailRecipient(RecipientType type, const std::string& address):
_address(address),
_type(type)
{
}
MailRecipient::MailRecipient(RecipientType type, const std::string& address, const std::string& realName):
_address(address),
_realName(realName),
_type(type)
{
}
MailRecipient::~MailRecipient()
{
}
MailRecipient& MailRecipient::operator = (const MailRecipient& recipient)
{
if (this != &recipient)
{
MailRecipient tmp(recipient);
swap(tmp);
}
return *this;
}
void MailRecipient::swap(MailRecipient& recipient)
{
std::swap(_type, recipient._type);
std::swap(_address, recipient._address);
std::swap(_realName, recipient._realName);
}
void MailRecipient::setType(RecipientType type)
{
_type = type;
}
void MailRecipient::setAddress(const std::string& address)
{
_address = address;
}
void MailRecipient::setRealName(const std::string& realName)
{
_realName = realName;
}
} } // namespace Poco::Net

View File

@@ -1,241 +1,241 @@
//
// MailStream.cpp
//
// $Id: //poco/1.2/Net/src/MailStream.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: MailStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MailStream.h"
namespace Poco {
namespace Net {
MailStreamBuf::MailStreamBuf(std::istream& istr):
_pIstr(&istr),
_pOstr(0),
_state(ST_CR_LF)
{
}
MailStreamBuf::MailStreamBuf(std::ostream& ostr):
_pIstr(0),
_pOstr(&ostr),
_state(ST_CR_LF)
{
}
MailStreamBuf::~MailStreamBuf()
{
}
void MailStreamBuf::close()
{
if (_pOstr && _state != ST_CR_LF_DOT_CR_LF)
{
if (!_buffer.empty())
_pOstr->write(_buffer.data(), (std::streamsize) _buffer.length());
if (_state != ST_CR_LF)
_pOstr->write("\r\n", 2);
_pOstr->write(".\r\n", 3);
_state = ST_CR_LF_DOT_CR_LF;
}
}
int MailStreamBuf::readFromDevice()
{
int c = std::char_traits<char>::eof();
if (!_buffer.empty())
{
c = _buffer[0];
_buffer.erase(0, 1);
}
else
{
c = readOne();
while (c != std::char_traits<char>::eof() && _state != ST_DATA && _state != ST_CR_LF_DOT_CR_LF)
c = readOne();
if (!_buffer.empty())
{
c = _buffer[0];
_buffer.erase(0, 1);
}
}
return c;
}
int MailStreamBuf::readOne()
{
int c = std::char_traits<char>::eof();
if (_state != ST_CR_LF_DOT_CR_LF)
{
c = _pIstr->get();
switch (c)
{
case '\r':
if (_state == ST_CR_LF_DOT)
_state = ST_CR_LF_DOT_CR;
else
_state = ST_CR;
break;
case '\n':
if (_state == ST_CR)
_state = ST_CR_LF;
else if (_state == ST_CR_LF_DOT_CR)
_state = ST_CR_LF_DOT_CR_LF;
else
_state = ST_DATA;
break;
case '.':
if (_state == ST_CR_LF)
_state = ST_CR_LF_DOT;
else if (_state == ST_CR_LF_DOT)
_state = ST_CR_LF_DOT_DOT;
else
_state = ST_DATA;
break;
default:
_state = ST_DATA;
}
if (_state == ST_CR_LF_DOT_DOT)
_state = ST_DATA;
else if (_state == ST_CR_LF_DOT_CR_LF)
_buffer.resize(_buffer.size() - 2);
else if (c != std::char_traits<char>::eof())
_buffer += (char) c;
}
return c;
}
int MailStreamBuf::writeToDevice(char c)
{
switch (c)
{
case '\r':
_state = ST_CR;
break;
case '\n':
if (_state == ST_CR)
_state = ST_CR_LF;
else
_state = ST_DATA;
break;
case '.':
if (_state == ST_CR_LF)
_state = ST_CR_LF_DOT;
else
_state = ST_DATA;
break;
default:
_state = ST_DATA;
}
if (_state == ST_DATA)
{
if (!_buffer.empty())
{
_pOstr->write(_buffer.data(), (std::streamsize) _buffer.length());
_buffer.clear();
}
_pOstr->put(c);
}
else if (_state == ST_CR_LF_DOT)
{
_pOstr->write("\r\n..", 4);
_state = ST_DATA;
_buffer.clear();
}
else _buffer += c;
return charToInt(c);
}
MailIOS::MailIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
MailIOS::MailIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
MailIOS::~MailIOS()
{
}
void MailIOS::close()
{
_buf.close();
}
MailStreamBuf* MailIOS::rdbuf()
{
return &_buf;
}
MailInputStream::MailInputStream(std::istream& istr):
MailIOS(istr),
std::istream(&_buf)
{
}
MailInputStream::~MailInputStream()
{
}
MailOutputStream::MailOutputStream(std::ostream& ostr):
MailIOS(ostr),
std::ostream(&_buf)
{
}
MailOutputStream::~MailOutputStream()
{
}
} } // namespace Poco::Net
//
// MailStream.cpp
//
// $Id: //poco/1.2/Net/src/MailStream.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: MailStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MailStream.h"
namespace Poco {
namespace Net {
MailStreamBuf::MailStreamBuf(std::istream& istr):
_pIstr(&istr),
_pOstr(0),
_state(ST_CR_LF)
{
}
MailStreamBuf::MailStreamBuf(std::ostream& ostr):
_pIstr(0),
_pOstr(&ostr),
_state(ST_CR_LF)
{
}
MailStreamBuf::~MailStreamBuf()
{
}
void MailStreamBuf::close()
{
if (_pOstr && _state != ST_CR_LF_DOT_CR_LF)
{
if (!_buffer.empty())
_pOstr->write(_buffer.data(), (std::streamsize) _buffer.length());
if (_state != ST_CR_LF)
_pOstr->write("\r\n", 2);
_pOstr->write(".\r\n", 3);
_state = ST_CR_LF_DOT_CR_LF;
}
}
int MailStreamBuf::readFromDevice()
{
int c = std::char_traits<char>::eof();
if (!_buffer.empty())
{
c = _buffer[0];
_buffer.erase(0, 1);
}
else
{
c = readOne();
while (c != std::char_traits<char>::eof() && _state != ST_DATA && _state != ST_CR_LF_DOT_CR_LF)
c = readOne();
if (!_buffer.empty())
{
c = _buffer[0];
_buffer.erase(0, 1);
}
}
return c;
}
int MailStreamBuf::readOne()
{
int c = std::char_traits<char>::eof();
if (_state != ST_CR_LF_DOT_CR_LF)
{
c = _pIstr->get();
switch (c)
{
case '\r':
if (_state == ST_CR_LF_DOT)
_state = ST_CR_LF_DOT_CR;
else
_state = ST_CR;
break;
case '\n':
if (_state == ST_CR)
_state = ST_CR_LF;
else if (_state == ST_CR_LF_DOT_CR)
_state = ST_CR_LF_DOT_CR_LF;
else
_state = ST_DATA;
break;
case '.':
if (_state == ST_CR_LF)
_state = ST_CR_LF_DOT;
else if (_state == ST_CR_LF_DOT)
_state = ST_CR_LF_DOT_DOT;
else
_state = ST_DATA;
break;
default:
_state = ST_DATA;
}
if (_state == ST_CR_LF_DOT_DOT)
_state = ST_DATA;
else if (_state == ST_CR_LF_DOT_CR_LF)
_buffer.resize(_buffer.size() - 2);
else if (c != std::char_traits<char>::eof())
_buffer += (char) c;
}
return c;
}
int MailStreamBuf::writeToDevice(char c)
{
switch (c)
{
case '\r':
_state = ST_CR;
break;
case '\n':
if (_state == ST_CR)
_state = ST_CR_LF;
else
_state = ST_DATA;
break;
case '.':
if (_state == ST_CR_LF)
_state = ST_CR_LF_DOT;
else
_state = ST_DATA;
break;
default:
_state = ST_DATA;
}
if (_state == ST_DATA)
{
if (!_buffer.empty())
{
_pOstr->write(_buffer.data(), (std::streamsize) _buffer.length());
_buffer.clear();
}
_pOstr->put(c);
}
else if (_state == ST_CR_LF_DOT)
{
_pOstr->write("\r\n..", 4);
_state = ST_DATA;
_buffer.clear();
}
else _buffer += c;
return charToInt(c);
}
MailIOS::MailIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
MailIOS::MailIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
MailIOS::~MailIOS()
{
}
void MailIOS::close()
{
_buf.close();
}
MailStreamBuf* MailIOS::rdbuf()
{
return &_buf;
}
MailInputStream::MailInputStream(std::istream& istr):
MailIOS(istr),
std::istream(&_buf)
{
}
MailInputStream::~MailInputStream()
{
}
MailOutputStream::MailOutputStream(std::ostream& ostr):
MailIOS(ostr),
std::ostream(&_buf)
{
}
MailOutputStream::~MailOutputStream()
{
}
} } // namespace Poco::Net

View File

@@ -1,191 +1,191 @@
//
// MediaType.cpp
//
// $Id: //poco/1.2/Net/src/MediaType.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: MediaType
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MediaType.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/String.h"
#include <algorithm>
#include <ctype.h>
using Poco::icompare;
namespace Poco {
namespace Net {
MediaType::MediaType(const std::string& mediaType)
{
parse(mediaType);
}
MediaType::MediaType(const std::string& type, const std::string& subType):
_type(type),
_subType(subType)
{
}
MediaType::MediaType(const MediaType& mediaType):
_type(mediaType._type),
_subType(mediaType._subType),
_parameters(mediaType._parameters)
{
}
MediaType::~MediaType()
{
}
MediaType& MediaType::operator = (const MediaType& mediaType)
{
if (&mediaType != this)
{
_type = mediaType._type;
_subType = mediaType._subType;
_parameters = mediaType._parameters;
}
return *this;
}
MediaType& MediaType::operator = (const std::string& mediaType)
{
parse(mediaType);
return *this;
}
void MediaType::swap(MediaType& mediaType)
{
std::swap(_type, mediaType._type);
std::swap(_subType, mediaType._subType);
_parameters.swap(mediaType._parameters);
}
void MediaType::setType(const std::string& type)
{
_type = type;
}
void MediaType::setSubType(const std::string& subType)
{
_subType = subType;
}
void MediaType::setParameter(const std::string& name, const std::string& value)
{
_parameters.set(name, value);
}
const std::string& MediaType::getParameter(const std::string& name) const
{
return _parameters.get(name);
}
bool MediaType::hasParameter(const std::string& name) const
{
return _parameters.has(name);
}
void MediaType::removeParameter(const std::string& name)
{
_parameters.erase(name);
}
std::string MediaType::toString() const
{
std::string result;
result.append(_type);
result.append("/");
result.append(_subType);
for (NameValueCollection::ConstIterator it = _parameters.begin(); it != _parameters.end(); ++it)
{
result.append("; ");
result.append(it->first);
result.append("=");
MessageHeader::quote(it->second, result);
}
return result;
}
bool MediaType::matches(const MediaType& mediaType) const
{
return matches(mediaType._type, mediaType._subType);
}
bool MediaType::matches(const std::string& type, const std::string& subType) const
{
return icompare(_type, type) == 0 && icompare(_subType, subType) == 0;
}
bool MediaType::matches(const std::string& type) const
{
return icompare(_type, type) == 0;
}
void MediaType::parse(const std::string& mediaType)
{
_type.clear();
_subType.clear();
_parameters.clear();
std::string::const_iterator it = mediaType.begin();
std::string::const_iterator end = mediaType.end();
while (it != end && isspace(*it)) ++it;
while (it != end && *it != '/') _type += *it++;
if (it != end) ++it;
while (it != end && *it != ';' && !isspace(*it)) _subType += *it++;
while (it != end && *it != ';') ++it;
MessageHeader::splitParameters(it, end, _parameters);
}
} } // namespace Poco::Net
//
// MediaType.cpp
//
// $Id: //poco/1.2/Net/src/MediaType.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: MediaType
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MediaType.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/String.h"
#include <algorithm>
#include <ctype.h>
using Poco::icompare;
namespace Poco {
namespace Net {
MediaType::MediaType(const std::string& mediaType)
{
parse(mediaType);
}
MediaType::MediaType(const std::string& type, const std::string& subType):
_type(type),
_subType(subType)
{
}
MediaType::MediaType(const MediaType& mediaType):
_type(mediaType._type),
_subType(mediaType._subType),
_parameters(mediaType._parameters)
{
}
MediaType::~MediaType()
{
}
MediaType& MediaType::operator = (const MediaType& mediaType)
{
if (&mediaType != this)
{
_type = mediaType._type;
_subType = mediaType._subType;
_parameters = mediaType._parameters;
}
return *this;
}
MediaType& MediaType::operator = (const std::string& mediaType)
{
parse(mediaType);
return *this;
}
void MediaType::swap(MediaType& mediaType)
{
std::swap(_type, mediaType._type);
std::swap(_subType, mediaType._subType);
_parameters.swap(mediaType._parameters);
}
void MediaType::setType(const std::string& type)
{
_type = type;
}
void MediaType::setSubType(const std::string& subType)
{
_subType = subType;
}
void MediaType::setParameter(const std::string& name, const std::string& value)
{
_parameters.set(name, value);
}
const std::string& MediaType::getParameter(const std::string& name) const
{
return _parameters.get(name);
}
bool MediaType::hasParameter(const std::string& name) const
{
return _parameters.has(name);
}
void MediaType::removeParameter(const std::string& name)
{
_parameters.erase(name);
}
std::string MediaType::toString() const
{
std::string result;
result.append(_type);
result.append("/");
result.append(_subType);
for (NameValueCollection::ConstIterator it = _parameters.begin(); it != _parameters.end(); ++it)
{
result.append("; ");
result.append(it->first);
result.append("=");
MessageHeader::quote(it->second, result);
}
return result;
}
bool MediaType::matches(const MediaType& mediaType) const
{
return matches(mediaType._type, mediaType._subType);
}
bool MediaType::matches(const std::string& type, const std::string& subType) const
{
return icompare(_type, type) == 0 && icompare(_subType, subType) == 0;
}
bool MediaType::matches(const std::string& type) const
{
return icompare(_type, type) == 0;
}
void MediaType::parse(const std::string& mediaType)
{
_type.clear();
_subType.clear();
_parameters.clear();
std::string::const_iterator it = mediaType.begin();
std::string::const_iterator end = mediaType.end();
while (it != end && isspace(*it)) ++it;
while (it != end && *it != '/') _type += *it++;
if (it != end) ++it;
while (it != end && *it != ';' && !isspace(*it)) _subType += *it++;
while (it != end && *it != ';') ++it;
MessageHeader::splitParameters(it, end, _parameters);
}
} } // namespace Poco::Net

View File

@@ -1,231 +1,231 @@
//
// MessageHeader.cpp
//
// $Id: //poco/1.2/Net/src/MessageHeader.cpp#2 $
//
// Library: Net
// Package: Messages
// Module: MessageHeader
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/NetException.h"
#include "Poco/String.h"
#include <ctype.h>
namespace Poco {
namespace Net {
MessageHeader::MessageHeader()
{
}
MessageHeader::MessageHeader(const MessageHeader& messageHeader):
NameValueCollection(messageHeader)
{
}
MessageHeader::~MessageHeader()
{
}
MessageHeader& MessageHeader::operator = (const MessageHeader& messageHeader)
{
NameValueCollection::operator = (messageHeader);
return *this;
}
void MessageHeader::write(std::ostream& ostr) const
{
NameValueCollection::ConstIterator it = begin();
while (it != end())
{
ostr << it->first << ": " << it->second << "\r\n";
++it;
}
}
void MessageHeader::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
int ch = istr.get();
while (ch != eof && ch != '\r' && ch != '\n')
{
std::string name;
std::string value;
while (ch != eof && ch != ':' && ch != '\n' && name.length() < MAX_NAME_LENGTH) { name += ch; ch = istr.get(); }
if (ch == '\n') { ch = istr.get(); continue; } // ignore invalid header lines
if (ch != ':') throw MessageException("Field name too long/no colon found");
if (ch != eof) ch = istr.get(); // ':'
while (isspace(ch)) ch = istr.get();
while (ch != eof && ch != '\r' && ch != '\n' && value.length() < MAX_VALUE_LENGTH) { value += ch; ch = istr.get(); }
if (ch == '\r') ch = istr.get();
if (ch == '\n')
ch = istr.get();
else if (ch != eof)
throw MessageException("Field value too long/no CRLF found");
while (ch == ' ' || ch == '\t') // folding
{
while (ch != eof && ch != '\r' && ch != '\n' && value.length() < MAX_VALUE_LENGTH) { value += ch; ch = istr.get(); }
if (ch == '\r') ch = istr.get();
if (ch == '\n')
ch = istr.get();
else if (ch != eof)
throw MessageException("Folded field value too long/no CRLF found");
}
add(name, value);
}
istr.putback(ch);
}
void MessageHeader::splitElements(const std::string& s, std::vector<std::string>& elements, bool ignoreEmpty)
{
elements.clear();
std::string::const_iterator it = s.begin();
std::string::const_iterator end = s.end();
std::string elem;
while (it != end)
{
if (*it == '"')
{
elem += *it++;
while (it != end && *it != '"')
{
if (*it == '\\')
{
++it;
if (it != end) elem += *it++;
}
else elem += *it++;
}
if (it != end) elem += *it++;
}
else if (*it == '\\')
{
++it;
if (it != end) elem += *it++;
}
else if (*it == ',')
{
Poco::trimInPlace(elem);
if (!ignoreEmpty || !elem.empty())
elements.push_back(elem);
elem.clear();
++it;
}
else elem += *it++;
}
if (!elem.empty())
{
Poco::trimInPlace(elem);
if (!ignoreEmpty || !elem.empty())
elements.push_back(elem);
}
}
void MessageHeader::splitParameters(const std::string& s, std::string& value, NameValueCollection& parameters)
{
value.clear();
parameters.clear();
std::string::const_iterator it = s.begin();
std::string::const_iterator end = s.end();
while (it != end && isspace(*it)) ++it;
while (it != end && *it != ';') value += *it++;
Poco::trimRightInPlace(value);
if (it != end) ++it;
splitParameters(it, end, parameters);
}
void MessageHeader::splitParameters(const std::string::const_iterator& begin, const std::string::const_iterator& end, NameValueCollection& parameters)
{
std::string::const_iterator it = begin;
while (it != end)
{
std::string pname;
std::string pvalue;
while (it != end && isspace(*it)) ++it;
while (it != end && *it != '=' && *it != ';') pname += *it++;
Poco::trimRightInPlace(pname);
if (it != end && *it != ';') ++it;
while (it != end && isspace(*it)) ++it;
while (it != end && *it != ';')
{
if (*it == '"')
{
++it;
while (it != end && *it != '"')
{
if (*it == '\\')
{
++it;
if (it != end) pvalue += *it++;
}
else pvalue += *it++;
}
if (it != end) ++it;
}
else if (*it == '\\')
{
++it;
if (it != end) pvalue += *it++;
}
else pvalue += *it++;
}
Poco::trimRightInPlace(pvalue);
if (!pname.empty()) parameters.add(pname, pvalue);
if (it != end) ++it;
}
}
void MessageHeader::quote(const std::string& value, std::string& result, bool allowSpace)
{
bool mustQuote = false;
for (std::string::const_iterator it = value.begin(); !mustQuote && it != value.end(); ++it)
{
if (!isalnum(*it) && *it != '.' && *it != '_' && *it != '-' && !(isspace(*it) && allowSpace))
mustQuote = true;
}
if (mustQuote) result += '"';
result.append(value);
if (mustQuote) result += '"';
}
} } // namespace Poco::Net
//
// MessageHeader.cpp
//
// $Id: //poco/1.2/Net/src/MessageHeader.cpp#2 $
//
// Library: Net
// Package: Messages
// Module: MessageHeader
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/NetException.h"
#include "Poco/String.h"
#include <ctype.h>
namespace Poco {
namespace Net {
MessageHeader::MessageHeader()
{
}
MessageHeader::MessageHeader(const MessageHeader& messageHeader):
NameValueCollection(messageHeader)
{
}
MessageHeader::~MessageHeader()
{
}
MessageHeader& MessageHeader::operator = (const MessageHeader& messageHeader)
{
NameValueCollection::operator = (messageHeader);
return *this;
}
void MessageHeader::write(std::ostream& ostr) const
{
NameValueCollection::ConstIterator it = begin();
while (it != end())
{
ostr << it->first << ": " << it->second << "\r\n";
++it;
}
}
void MessageHeader::read(std::istream& istr)
{
static const int eof = std::char_traits<char>::eof();
int ch = istr.get();
while (ch != eof && ch != '\r' && ch != '\n')
{
std::string name;
std::string value;
while (ch != eof && ch != ':' && ch != '\n' && name.length() < MAX_NAME_LENGTH) { name += ch; ch = istr.get(); }
if (ch == '\n') { ch = istr.get(); continue; } // ignore invalid header lines
if (ch != ':') throw MessageException("Field name too long/no colon found");
if (ch != eof) ch = istr.get(); // ':'
while (isspace(ch)) ch = istr.get();
while (ch != eof && ch != '\r' && ch != '\n' && value.length() < MAX_VALUE_LENGTH) { value += ch; ch = istr.get(); }
if (ch == '\r') ch = istr.get();
if (ch == '\n')
ch = istr.get();
else if (ch != eof)
throw MessageException("Field value too long/no CRLF found");
while (ch == ' ' || ch == '\t') // folding
{
while (ch != eof && ch != '\r' && ch != '\n' && value.length() < MAX_VALUE_LENGTH) { value += ch; ch = istr.get(); }
if (ch == '\r') ch = istr.get();
if (ch == '\n')
ch = istr.get();
else if (ch != eof)
throw MessageException("Folded field value too long/no CRLF found");
}
add(name, value);
}
istr.putback(ch);
}
void MessageHeader::splitElements(const std::string& s, std::vector<std::string>& elements, bool ignoreEmpty)
{
elements.clear();
std::string::const_iterator it = s.begin();
std::string::const_iterator end = s.end();
std::string elem;
while (it != end)
{
if (*it == '"')
{
elem += *it++;
while (it != end && *it != '"')
{
if (*it == '\\')
{
++it;
if (it != end) elem += *it++;
}
else elem += *it++;
}
if (it != end) elem += *it++;
}
else if (*it == '\\')
{
++it;
if (it != end) elem += *it++;
}
else if (*it == ',')
{
Poco::trimInPlace(elem);
if (!ignoreEmpty || !elem.empty())
elements.push_back(elem);
elem.clear();
++it;
}
else elem += *it++;
}
if (!elem.empty())
{
Poco::trimInPlace(elem);
if (!ignoreEmpty || !elem.empty())
elements.push_back(elem);
}
}
void MessageHeader::splitParameters(const std::string& s, std::string& value, NameValueCollection& parameters)
{
value.clear();
parameters.clear();
std::string::const_iterator it = s.begin();
std::string::const_iterator end = s.end();
while (it != end && isspace(*it)) ++it;
while (it != end && *it != ';') value += *it++;
Poco::trimRightInPlace(value);
if (it != end) ++it;
splitParameters(it, end, parameters);
}
void MessageHeader::splitParameters(const std::string::const_iterator& begin, const std::string::const_iterator& end, NameValueCollection& parameters)
{
std::string::const_iterator it = begin;
while (it != end)
{
std::string pname;
std::string pvalue;
while (it != end && isspace(*it)) ++it;
while (it != end && *it != '=' && *it != ';') pname += *it++;
Poco::trimRightInPlace(pname);
if (it != end && *it != ';') ++it;
while (it != end && isspace(*it)) ++it;
while (it != end && *it != ';')
{
if (*it == '"')
{
++it;
while (it != end && *it != '"')
{
if (*it == '\\')
{
++it;
if (it != end) pvalue += *it++;
}
else pvalue += *it++;
}
if (it != end) ++it;
}
else if (*it == '\\')
{
++it;
if (it != end) pvalue += *it++;
}
else pvalue += *it++;
}
Poco::trimRightInPlace(pvalue);
if (!pname.empty()) parameters.add(pname, pvalue);
if (it != end) ++it;
}
}
void MessageHeader::quote(const std::string& value, std::string& result, bool allowSpace)
{
bool mustQuote = false;
for (std::string::const_iterator it = value.begin(); !mustQuote && it != value.end(); ++it)
{
if (!isalnum(*it) && *it != '.' && *it != '_' && *it != '-' && !(isspace(*it) && allowSpace))
mustQuote = true;
}
if (mustQuote) result += '"';
result.append(value);
if (mustQuote) result += '"';
}
} } // namespace Poco::Net

View File

@@ -1,261 +1,261 @@
//
// MulticastSocket.cpp
//
// $Id: //poco/1.2/Net/src/MulticastSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: MulticastSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MulticastSocket.h"
#include "Poco/Net/NetException.h"
#include <string.h>
#if defined(hpux) && defined(_XOPEN_SOURCE_EXTENDED)
// netinet/in.h does not define struct ip_mreq if
// _XOPEN_SOURCE_EXTENDED is #define'd.
struct ip_mreq
{
struct in_addr imr_multiaddr;
struct in_addr imr_interface;
};
#endif
// some Unix variants don't have IPV6_ADD_MEMBERSHIP/IPV6_DROP_MEMBERSHIP
#if defined(IPV6_JOIN_GROUP) && !defined(IPV6_ADD_MEMBERSHIP)
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif
namespace Poco {
namespace Net {
MulticastSocket::MulticastSocket()
{
}
MulticastSocket::MulticastSocket(IPAddress::Family family): DatagramSocket(family)
{
}
MulticastSocket::MulticastSocket(const SocketAddress& address, bool reuseAddress): DatagramSocket(address, reuseAddress)
{
}
MulticastSocket::MulticastSocket(const Socket& socket): DatagramSocket(socket)
{
}
MulticastSocket::~MulticastSocket()
{
}
MulticastSocket& MulticastSocket::operator = (const Socket& socket)
{
DatagramSocket::operator = (socket);
return *this;
}
void MulticastSocket::setInterface(const NetworkInterface& interface)
{
if (!interface.supportsIPv6())
{
impl()->setOption(IPPROTO_IP, IP_MULTICAST_IF, interface.address());
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, interface.index());
#endif
}
}
NetworkInterface MulticastSocket::getInterface() const
{
try
{
IPAddress addr;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_IF, addr);
return NetworkInterface::forAddress(addr);
}
catch (Poco::Exception&)
{
#if defined(POCO_HAVE_IPv6)
int ix;
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, ix);
return NetworkInterface::forIndex(ix);
#else
throw;
#endif
}
}
void MulticastSocket::setLoopback(bool flag)
{
if (address().af() == AF_INET)
{
unsigned char uflag = flag ? 1 : 0;
impl()->setOption(IPPROTO_IP, IP_MULTICAST_LOOP, uflag);
}
else
{
#if defined(POCO_HAVE_IPv6)
unsigned uflag = flag ? 1 : 0;
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_LOOP, uflag);
#endif
}
}
bool MulticastSocket::getLoopback() const
{
bool flag = false;
if (address().af() == AF_INET)
{
unsigned char uflag;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_LOOP, uflag);
flag = uflag != 0;
}
else
{
#if defined(POCO_HAVE_IPv6)
unsigned uflag;
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_LOOP, uflag);
flag = uflag != 0;
#endif
}
return flag;
}
void MulticastSocket::setTimeToLive(unsigned value)
{
if (address().af() == AF_INET)
{
unsigned char ttl = (unsigned char) value;
impl()->setOption(IPPROTO_IP, IP_MULTICAST_TTL, ttl);
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_HOPS, value);
#endif
}
}
unsigned MulticastSocket::getTimeToLive() const
{
unsigned ttl;
if (address().af() == AF_INET)
{
unsigned char cttl;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_TTL, cttl);
ttl = cttl;
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_HOPS, ttl);
#endif
}
return ttl;
}
void MulticastSocket::joinGroup(const IPAddress& groupAddress)
{
NetworkInterface intf;
joinGroup(groupAddress, intf);
}
void MulticastSocket::joinGroup(const IPAddress& groupAddress, const NetworkInterface& interface)
{
if (groupAddress.af() == AF_INET)
{
struct ip_mreq mr;
memcpy(&mr.imr_multiaddr, groupAddress.addr(), groupAddress.length());
memcpy(&mr.imr_interface, interface.address().addr(), interface.address().length());
impl()->setRawOption(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mr, sizeof(mr));
}
else
{
#if defined(POCO_HAVE_IPv6)
struct ipv6_mreq mr;
memcpy(&mr.ipv6mr_multiaddr, groupAddress.addr(), groupAddress.length());
mr.ipv6mr_interface = interface.index();
impl()->setRawOption(IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mr, sizeof(mr));
#endif
}
}
void MulticastSocket::leaveGroup(const IPAddress& groupAddress)
{
NetworkInterface intf;
leaveGroup(groupAddress, intf);
}
void MulticastSocket::leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interface)
{
if (groupAddress.af() == AF_INET)
{
struct ip_mreq mr;
memcpy(&mr.imr_multiaddr, groupAddress.addr(), groupAddress.length());
memcpy(&mr.imr_interface, interface.address().addr(), interface.address().length());
impl()->setRawOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &mr, sizeof(mr));
}
else
{
#if defined(POCO_HAVE_IPv6)
struct ipv6_mreq mr;
memcpy(&mr.ipv6mr_multiaddr, groupAddress.addr(), groupAddress.length());
mr.ipv6mr_interface = interface.index();
impl()->setRawOption(IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mr, sizeof(mr));
#endif
}
}
} } // namespace Poco::Net
//
// MulticastSocket.cpp
//
// $Id: //poco/1.2/Net/src/MulticastSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: MulticastSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MulticastSocket.h"
#include "Poco/Net/NetException.h"
#include <string.h>
#if defined(hpux) && defined(_XOPEN_SOURCE_EXTENDED)
// netinet/in.h does not define struct ip_mreq if
// _XOPEN_SOURCE_EXTENDED is #define'd.
struct ip_mreq
{
struct in_addr imr_multiaddr;
struct in_addr imr_interface;
};
#endif
// some Unix variants don't have IPV6_ADD_MEMBERSHIP/IPV6_DROP_MEMBERSHIP
#if defined(IPV6_JOIN_GROUP) && !defined(IPV6_ADD_MEMBERSHIP)
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif
namespace Poco {
namespace Net {
MulticastSocket::MulticastSocket()
{
}
MulticastSocket::MulticastSocket(IPAddress::Family family): DatagramSocket(family)
{
}
MulticastSocket::MulticastSocket(const SocketAddress& address, bool reuseAddress): DatagramSocket(address, reuseAddress)
{
}
MulticastSocket::MulticastSocket(const Socket& socket): DatagramSocket(socket)
{
}
MulticastSocket::~MulticastSocket()
{
}
MulticastSocket& MulticastSocket::operator = (const Socket& socket)
{
DatagramSocket::operator = (socket);
return *this;
}
void MulticastSocket::setInterface(const NetworkInterface& interface)
{
if (!interface.supportsIPv6())
{
impl()->setOption(IPPROTO_IP, IP_MULTICAST_IF, interface.address());
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, interface.index());
#endif
}
}
NetworkInterface MulticastSocket::getInterface() const
{
try
{
IPAddress addr;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_IF, addr);
return NetworkInterface::forAddress(addr);
}
catch (Poco::Exception&)
{
#if defined(POCO_HAVE_IPv6)
int ix;
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, ix);
return NetworkInterface::forIndex(ix);
#else
throw;
#endif
}
}
void MulticastSocket::setLoopback(bool flag)
{
if (address().af() == AF_INET)
{
unsigned char uflag = flag ? 1 : 0;
impl()->setOption(IPPROTO_IP, IP_MULTICAST_LOOP, uflag);
}
else
{
#if defined(POCO_HAVE_IPv6)
unsigned uflag = flag ? 1 : 0;
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_LOOP, uflag);
#endif
}
}
bool MulticastSocket::getLoopback() const
{
bool flag = false;
if (address().af() == AF_INET)
{
unsigned char uflag;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_LOOP, uflag);
flag = uflag != 0;
}
else
{
#if defined(POCO_HAVE_IPv6)
unsigned uflag;
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_LOOP, uflag);
flag = uflag != 0;
#endif
}
return flag;
}
void MulticastSocket::setTimeToLive(unsigned value)
{
if (address().af() == AF_INET)
{
unsigned char ttl = (unsigned char) value;
impl()->setOption(IPPROTO_IP, IP_MULTICAST_TTL, ttl);
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_HOPS, value);
#endif
}
}
unsigned MulticastSocket::getTimeToLive() const
{
unsigned ttl;
if (address().af() == AF_INET)
{
unsigned char cttl;
impl()->getOption(IPPROTO_IP, IP_MULTICAST_TTL, cttl);
ttl = cttl;
}
else
{
#if defined(POCO_HAVE_IPv6)
impl()->getOption(IPPROTO_IPV6, IPV6_MULTICAST_HOPS, ttl);
#endif
}
return ttl;
}
void MulticastSocket::joinGroup(const IPAddress& groupAddress)
{
NetworkInterface intf;
joinGroup(groupAddress, intf);
}
void MulticastSocket::joinGroup(const IPAddress& groupAddress, const NetworkInterface& interface)
{
if (groupAddress.af() == AF_INET)
{
struct ip_mreq mr;
memcpy(&mr.imr_multiaddr, groupAddress.addr(), groupAddress.length());
memcpy(&mr.imr_interface, interface.address().addr(), interface.address().length());
impl()->setRawOption(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mr, sizeof(mr));
}
else
{
#if defined(POCO_HAVE_IPv6)
struct ipv6_mreq mr;
memcpy(&mr.ipv6mr_multiaddr, groupAddress.addr(), groupAddress.length());
mr.ipv6mr_interface = interface.index();
impl()->setRawOption(IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mr, sizeof(mr));
#endif
}
}
void MulticastSocket::leaveGroup(const IPAddress& groupAddress)
{
NetworkInterface intf;
leaveGroup(groupAddress, intf);
}
void MulticastSocket::leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interface)
{
if (groupAddress.af() == AF_INET)
{
struct ip_mreq mr;
memcpy(&mr.imr_multiaddr, groupAddress.addr(), groupAddress.length());
memcpy(&mr.imr_interface, interface.address().addr(), interface.address().length());
impl()->setRawOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &mr, sizeof(mr));
}
else
{
#if defined(POCO_HAVE_IPv6)
struct ipv6_mreq mr;
memcpy(&mr.ipv6mr_multiaddr, groupAddress.addr(), groupAddress.length());
mr.ipv6mr_interface = interface.index();
impl()->setRawOption(IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mr, sizeof(mr));
#endif
}
}
} } // namespace Poco::Net

View File

@@ -1,317 +1,317 @@
//
// MultipartReader.cpp
//
// $Id: //poco/1.2/Net/src/MultipartReader.cpp#2 $
//
// Library: Net
// Package: Messages
// Module: MultipartReader
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/NetException.h"
#include <ctype.h>
using Poco::BufferedStreamBuf;
namespace Poco {
namespace Net {
//
// MultipartStreamBuf
//
MultipartStreamBuf::MultipartStreamBuf(std::istream& istr, const std::string& boundary):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in),
_istr(istr),
_boundary(boundary),
_lastPart(false)
{
poco_assert (!boundary.empty() && boundary.length() < STREAM_BUFFER_SIZE - 6);
}
MultipartStreamBuf::~MultipartStreamBuf()
{
}
int MultipartStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
poco_assert_dbg (length >= _boundary.length() + 6);
static const int eof = std::char_traits<char>::eof();
int n = 0;
int ch = _istr.get();
*buffer++ = (char) ch; ++n;
if (ch == '\n' || ch == '\r' && _istr.peek() == '\n')
{
if (ch == '\r')
{
ch = _istr.get(); // '\n'
*buffer++ = (char) ch; ++n;
}
ch = _istr.peek();
if (ch == '\r' || ch == '\n') return n;
*buffer++ = (char) _istr.get(); ++n;
if (ch == '-' && _istr.peek() == '-')
{
ch = _istr.get(); // '-'
*buffer++ = (char) ch; ++n;
std::string::const_iterator it = _boundary.begin();
std::string::const_iterator end = _boundary.end();
ch = _istr.get();
*buffer++ = (char) ch; ++n;
while (it != end && ch == *it)
{
++it;
ch = _istr.get();
*buffer++ = (char) ch; ++n;
}
if (it == end)
{
if (ch == '\n' || ch == '\r' && _istr.peek() == '\n')
{
if (ch == '\r')
{
ch = _istr.get(); // '\n'
}
return 0;
}
else if (ch == '-' && _istr.peek() == '-')
{
ch = _istr.get(); // '-'
_lastPart = true;
return 0;
}
}
}
}
ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n' && n < length)
{
*buffer++ = (char) _istr.get(); ++n;
ch = _istr.peek();
}
return n;
}
bool MultipartStreamBuf::lastPart() const
{
return _lastPart;
}
//
// MultipartIOS
//
MultipartIOS::MultipartIOS(std::istream& istr, const std::string& boundary):
_buf(istr, boundary)
{
poco_ios_init(&_buf);
}
MultipartIOS::~MultipartIOS()
{
_buf.sync();
}
MultipartStreamBuf* MultipartIOS::rdbuf()
{
return &_buf;
}
bool MultipartIOS::lastPart() const
{
return _buf.lastPart();
}
//
// MultipartInputStream
//
MultipartInputStream::MultipartInputStream(std::istream& istr, const std::string& boundary):
MultipartIOS(istr, boundary),
std::istream(&_buf)
{
}
MultipartInputStream::~MultipartInputStream()
{
}
//
// MultipartReader
//
MultipartReader::MultipartReader(std::istream& istr):
_istr(istr),
_pMPI(0)
{
}
MultipartReader::MultipartReader(std::istream& istr, const std::string& boundary):
_istr(istr),
_boundary(boundary),
_pMPI(0)
{
}
MultipartReader::~MultipartReader()
{
delete _pMPI;
}
void MultipartReader::nextPart(MessageHeader& messageHeader)
{
if (!_pMPI)
{
if (_boundary.empty())
guessBoundary();
else
findFirstBoundary();
}
else if (_pMPI->lastPart())
{
throw MultipartException("No more parts available");
}
parseHeader(messageHeader);
delete _pMPI;
_pMPI = new MultipartInputStream(_istr, _boundary);
}
bool MultipartReader::hasNextPart()
{
return (!_pMPI || !_pMPI->lastPart()) && _istr.good();
}
std::istream& MultipartReader::stream() const
{
poco_check_ptr (_pMPI);
return *_pMPI;
}
const std::string& MultipartReader::boundary() const
{
return _boundary;
}
void MultipartReader::findFirstBoundary()
{
std::string expect("--");
expect.append(_boundary);
std::string line;
line.reserve(expect.length());
bool ok = true;
do
{
ok = readLine(line, expect.length());
}
while (ok && line != expect);
if (!ok) throw MultipartException("No boundary line found");
}
void MultipartReader::guessBoundary()
{
static const int eof = std::char_traits<char>::eof();
int ch = _istr.get();
while (isspace(ch))
ch = _istr.get();
if (ch == '-' && _istr.peek() == '-')
{
_istr.get();
ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n')
{
_boundary += (char) _istr.get();
ch = _istr.peek();
}
if (ch == '\r' || ch == '\n')
ch = _istr.get();
if (_istr.peek() == '\n')
_istr.get();
}
else throw MultipartException("No boundary line found");
}
void MultipartReader::parseHeader(MessageHeader& messageHeader)
{
messageHeader.clear();
messageHeader.read(_istr);
int ch = _istr.get();
if (ch == '\r' && _istr.peek() == '\n') ch = _istr.get();
}
bool MultipartReader::readLine(std::string& line, std::string::size_type n)
{
static const int eof = std::char_traits<char>::eof();
line.clear();
int ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n')
{
ch = (char) _istr.get();
if (line.length() < n) line += ch;
ch = _istr.peek();
}
if (ch != eof) _istr.get();
if (ch == '\r' && _istr.peek() == '\n') _istr.get();
return ch != eof;
}
} } // namespace Poco::Net
//
// MultipartReader.cpp
//
// $Id: //poco/1.2/Net/src/MultipartReader.cpp#2 $
//
// Library: Net
// Package: Messages
// Module: MultipartReader
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MultipartReader.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/NetException.h"
#include <ctype.h>
using Poco::BufferedStreamBuf;
namespace Poco {
namespace Net {
//
// MultipartStreamBuf
//
MultipartStreamBuf::MultipartStreamBuf(std::istream& istr, const std::string& boundary):
BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in),
_istr(istr),
_boundary(boundary),
_lastPart(false)
{
poco_assert (!boundary.empty() && boundary.length() < STREAM_BUFFER_SIZE - 6);
}
MultipartStreamBuf::~MultipartStreamBuf()
{
}
int MultipartStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
poco_assert_dbg (length >= _boundary.length() + 6);
static const int eof = std::char_traits<char>::eof();
int n = 0;
int ch = _istr.get();
*buffer++ = (char) ch; ++n;
if (ch == '\n' || ch == '\r' && _istr.peek() == '\n')
{
if (ch == '\r')
{
ch = _istr.get(); // '\n'
*buffer++ = (char) ch; ++n;
}
ch = _istr.peek();
if (ch == '\r' || ch == '\n') return n;
*buffer++ = (char) _istr.get(); ++n;
if (ch == '-' && _istr.peek() == '-')
{
ch = _istr.get(); // '-'
*buffer++ = (char) ch; ++n;
std::string::const_iterator it = _boundary.begin();
std::string::const_iterator end = _boundary.end();
ch = _istr.get();
*buffer++ = (char) ch; ++n;
while (it != end && ch == *it)
{
++it;
ch = _istr.get();
*buffer++ = (char) ch; ++n;
}
if (it == end)
{
if (ch == '\n' || ch == '\r' && _istr.peek() == '\n')
{
if (ch == '\r')
{
ch = _istr.get(); // '\n'
}
return 0;
}
else if (ch == '-' && _istr.peek() == '-')
{
ch = _istr.get(); // '-'
_lastPart = true;
return 0;
}
}
}
}
ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n' && n < length)
{
*buffer++ = (char) _istr.get(); ++n;
ch = _istr.peek();
}
return n;
}
bool MultipartStreamBuf::lastPart() const
{
return _lastPart;
}
//
// MultipartIOS
//
MultipartIOS::MultipartIOS(std::istream& istr, const std::string& boundary):
_buf(istr, boundary)
{
poco_ios_init(&_buf);
}
MultipartIOS::~MultipartIOS()
{
_buf.sync();
}
MultipartStreamBuf* MultipartIOS::rdbuf()
{
return &_buf;
}
bool MultipartIOS::lastPart() const
{
return _buf.lastPart();
}
//
// MultipartInputStream
//
MultipartInputStream::MultipartInputStream(std::istream& istr, const std::string& boundary):
MultipartIOS(istr, boundary),
std::istream(&_buf)
{
}
MultipartInputStream::~MultipartInputStream()
{
}
//
// MultipartReader
//
MultipartReader::MultipartReader(std::istream& istr):
_istr(istr),
_pMPI(0)
{
}
MultipartReader::MultipartReader(std::istream& istr, const std::string& boundary):
_istr(istr),
_boundary(boundary),
_pMPI(0)
{
}
MultipartReader::~MultipartReader()
{
delete _pMPI;
}
void MultipartReader::nextPart(MessageHeader& messageHeader)
{
if (!_pMPI)
{
if (_boundary.empty())
guessBoundary();
else
findFirstBoundary();
}
else if (_pMPI->lastPart())
{
throw MultipartException("No more parts available");
}
parseHeader(messageHeader);
delete _pMPI;
_pMPI = new MultipartInputStream(_istr, _boundary);
}
bool MultipartReader::hasNextPart()
{
return (!_pMPI || !_pMPI->lastPart()) && _istr.good();
}
std::istream& MultipartReader::stream() const
{
poco_check_ptr (_pMPI);
return *_pMPI;
}
const std::string& MultipartReader::boundary() const
{
return _boundary;
}
void MultipartReader::findFirstBoundary()
{
std::string expect("--");
expect.append(_boundary);
std::string line;
line.reserve(expect.length());
bool ok = true;
do
{
ok = readLine(line, expect.length());
}
while (ok && line != expect);
if (!ok) throw MultipartException("No boundary line found");
}
void MultipartReader::guessBoundary()
{
static const int eof = std::char_traits<char>::eof();
int ch = _istr.get();
while (isspace(ch))
ch = _istr.get();
if (ch == '-' && _istr.peek() == '-')
{
_istr.get();
ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n')
{
_boundary += (char) _istr.get();
ch = _istr.peek();
}
if (ch == '\r' || ch == '\n')
ch = _istr.get();
if (_istr.peek() == '\n')
_istr.get();
}
else throw MultipartException("No boundary line found");
}
void MultipartReader::parseHeader(MessageHeader& messageHeader)
{
messageHeader.clear();
messageHeader.read(_istr);
int ch = _istr.get();
if (ch == '\r' && _istr.peek() == '\n') ch = _istr.get();
}
bool MultipartReader::readLine(std::string& line, std::string::size_type n)
{
static const int eof = std::char_traits<char>::eof();
line.clear();
int ch = _istr.peek();
while (ch != eof && ch != '\r' && ch != '\n')
{
ch = (char) _istr.get();
if (line.length() < n) line += ch;
ch = _istr.peek();
}
if (ch != eof) _istr.get();
if (ch == '\r' && _istr.peek() == '\n') _istr.get();
return ch != eof;
}
} } // namespace Poco::Net

View File

@@ -1,102 +1,102 @@
//
// MultipartWriter.cpp
//
// $Id: //poco/1.2/Net/src/MultipartWriter.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: MultipartWriter
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MultipartWriter.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Random.h"
#include "Poco/NumberFormatter.h"
using Poco::Random;
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
MultipartWriter::MultipartWriter(std::ostream& ostr):
_ostr(ostr),
_boundary(createBoundary())
{
}
MultipartWriter::MultipartWriter(std::ostream& ostr, const std::string& boundary):
_ostr(ostr),
_boundary(boundary)
{
if (_boundary.empty())
_boundary = createBoundary();
}
MultipartWriter::~MultipartWriter()
{
}
void MultipartWriter::nextPart(const MessageHeader& header)
{
_ostr << "\r\n--" << _boundary << "\r\n";
header.write(_ostr);
_ostr << "\r\n";
}
void MultipartWriter::close()
{
_ostr << "\r\n--" << _boundary << "--\r\n";
}
const std::string& MultipartWriter::boundary() const
{
return _boundary;
}
std::string MultipartWriter::createBoundary()
{
std::string boundary("MIME_boundary_");
Random rnd;
boundary.append(NumberFormatter::formatHex(rnd.next(), 8));
boundary.append(NumberFormatter::formatHex(rnd.next(), 8));
return boundary;
}
} } // namespace Poco::Net
//
// MultipartWriter.cpp
//
// $Id: //poco/1.2/Net/src/MultipartWriter.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: MultipartWriter
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/MultipartWriter.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Random.h"
#include "Poco/NumberFormatter.h"
using Poco::Random;
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
MultipartWriter::MultipartWriter(std::ostream& ostr):
_ostr(ostr),
_boundary(createBoundary())
{
}
MultipartWriter::MultipartWriter(std::ostream& ostr, const std::string& boundary):
_ostr(ostr),
_boundary(boundary)
{
if (_boundary.empty())
_boundary = createBoundary();
}
MultipartWriter::~MultipartWriter()
{
}
void MultipartWriter::nextPart(const MessageHeader& header)
{
_ostr << "\r\n--" << _boundary << "\r\n";
header.write(_ostr);
_ostr << "\r\n";
}
void MultipartWriter::close()
{
_ostr << "\r\n--" << _boundary << "--\r\n";
}
const std::string& MultipartWriter::boundary() const
{
return _boundary;
}
std::string MultipartWriter::createBoundary()
{
std::string boundary("MIME_boundary_");
Random rnd;
boundary.append(NumberFormatter::formatHex(rnd.next(), 8));
boundary.append(NumberFormatter::formatHex(rnd.next(), 8));
return boundary;
}
} } // namespace Poco::Net

View File

@@ -1,174 +1,174 @@
//
// NameValueCollection.cpp
//
// $Id: //poco/1.2/Net/src/NameValueCollection.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: NameValueCollection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Exception.h"
#include <algorithm>
using Poco::NotFoundException;
namespace Poco {
namespace Net {
NameValueCollection::NameValueCollection()
{
}
NameValueCollection::NameValueCollection(const NameValueCollection& nvc):
_map(nvc._map)
{
}
NameValueCollection::~NameValueCollection()
{
}
NameValueCollection& NameValueCollection::operator = (const NameValueCollection& nvc)
{
if (&nvc != this)
{
_map = nvc._map;
}
return *this;
}
void NameValueCollection::swap(NameValueCollection& nvc)
{
std::swap(_map, nvc._map);
}
const std::string& NameValueCollection::operator [] (const std::string& name) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
throw NotFoundException(name);
}
void NameValueCollection::set(const std::string& name, const std::string& value)
{
Iterator it = _map.find(name);
if (it != _map.end())
_map.erase(it);
_map.insert(HeaderMap::value_type(name, value));
}
void NameValueCollection::add(const std::string& name, const std::string& value)
{
_map.insert(HeaderMap::value_type(name, value));
}
const std::string& NameValueCollection::get(const std::string& name) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
throw NotFoundException(name);
}
const std::string& NameValueCollection::get(const std::string& name, const std::string& defaultValue) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
return defaultValue;
}
bool NameValueCollection::has(const std::string& name) const
{
return _map.find(name) != _map.end();
}
NameValueCollection::ConstIterator NameValueCollection::find(const std::string& name) const
{
return _map.find(name);
}
NameValueCollection::ConstIterator NameValueCollection::begin() const
{
return _map.begin();
}
NameValueCollection::ConstIterator NameValueCollection::end() const
{
return _map.end();
}
bool NameValueCollection::empty() const
{
return _map.empty();
}
int NameValueCollection::size() const
{
return (int) _map.size();
}
void NameValueCollection::erase(const std::string& name)
{
_map.erase(name);
}
void NameValueCollection::clear()
{
_map.clear();
}
} } // namespace Poco::Net
//
// NameValueCollection.cpp
//
// $Id: //poco/1.2/Net/src/NameValueCollection.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: NameValueCollection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Exception.h"
#include <algorithm>
using Poco::NotFoundException;
namespace Poco {
namespace Net {
NameValueCollection::NameValueCollection()
{
}
NameValueCollection::NameValueCollection(const NameValueCollection& nvc):
_map(nvc._map)
{
}
NameValueCollection::~NameValueCollection()
{
}
NameValueCollection& NameValueCollection::operator = (const NameValueCollection& nvc)
{
if (&nvc != this)
{
_map = nvc._map;
}
return *this;
}
void NameValueCollection::swap(NameValueCollection& nvc)
{
std::swap(_map, nvc._map);
}
const std::string& NameValueCollection::operator [] (const std::string& name) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
throw NotFoundException(name);
}
void NameValueCollection::set(const std::string& name, const std::string& value)
{
Iterator it = _map.find(name);
if (it != _map.end())
_map.erase(it);
_map.insert(HeaderMap::value_type(name, value));
}
void NameValueCollection::add(const std::string& name, const std::string& value)
{
_map.insert(HeaderMap::value_type(name, value));
}
const std::string& NameValueCollection::get(const std::string& name) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
throw NotFoundException(name);
}
const std::string& NameValueCollection::get(const std::string& name, const std::string& defaultValue) const
{
ConstIterator it = _map.find(name);
if (it != _map.end())
return it->second;
else
return defaultValue;
}
bool NameValueCollection::has(const std::string& name) const
{
return _map.find(name) != _map.end();
}
NameValueCollection::ConstIterator NameValueCollection::find(const std::string& name) const
{
return _map.find(name);
}
NameValueCollection::ConstIterator NameValueCollection::begin() const
{
return _map.begin();
}
NameValueCollection::ConstIterator NameValueCollection::end() const
{
return _map.end();
}
bool NameValueCollection::empty() const
{
return _map.empty();
}
int NameValueCollection::size() const
{
return (int) _map.size();
}
void NameValueCollection::erase(const std::string& name)
{
_map.erase(name);
}
void NameValueCollection::clear()
{
_map.clear();
}
} } // namespace Poco::Net

View File

@@ -1,69 +1,69 @@
//
// NetException.cpp
//
// $Id: //poco/1.2/Net/src/NetException.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: NetException
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NetException.h"
#include <typeinfo>
using Poco::IOException;
namespace Poco {
namespace Net {
POCO_IMPLEMENT_EXCEPTION(NetException, IOException, "Net Exception")
POCO_IMPLEMENT_EXCEPTION(InvalidAddressException, NetException, "Invalid address")
POCO_IMPLEMENT_EXCEPTION(ServiceNotFoundException, NetException, "Service not found")
POCO_IMPLEMENT_EXCEPTION(ConnectionAbortedException, NetException, "Software caused connection abort")
POCO_IMPLEMENT_EXCEPTION(ConnectionResetException, NetException, "Connection reset by peer")
POCO_IMPLEMENT_EXCEPTION(ConnectionRefusedException, NetException, "Connection refused")
POCO_IMPLEMENT_EXCEPTION(DNSException, NetException, "DNS error")
POCO_IMPLEMENT_EXCEPTION(HostNotFoundException, DNSException, "Host not found")
POCO_IMPLEMENT_EXCEPTION(NoAddressFoundException, DNSException, "No address found")
POCO_IMPLEMENT_EXCEPTION(InterfaceNotFoundException, NetException, "Interface not found")
POCO_IMPLEMENT_EXCEPTION(MessageException, NetException, "Malformed message")
POCO_IMPLEMENT_EXCEPTION(MultipartException, MessageException, "Malformed multipart message")
POCO_IMPLEMENT_EXCEPTION(HTTPException, NetException, "HTTP Exception")
POCO_IMPLEMENT_EXCEPTION(NotAuthenticatedException, HTTPException, "No authentication information found")
POCO_IMPLEMENT_EXCEPTION(UnsupportedRedirectException, HTTPException, "Unsupported HTTP redirect (protocol change)")
POCO_IMPLEMENT_EXCEPTION(FTPException, NetException, "FTP Exception")
POCO_IMPLEMENT_EXCEPTION(SMTPException, NetException, "SMTP Exception")
POCO_IMPLEMENT_EXCEPTION(POP3Exception, NetException, "POP3 Exception")
POCO_IMPLEMENT_EXCEPTION(ICMPException, NetException, "ICMP Exception")
} } // namespace Poco::Net
//
// NetException.cpp
//
// $Id: //poco/1.2/Net/src/NetException.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: NetException
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NetException.h"
#include <typeinfo>
using Poco::IOException;
namespace Poco {
namespace Net {
POCO_IMPLEMENT_EXCEPTION(NetException, IOException, "Net Exception")
POCO_IMPLEMENT_EXCEPTION(InvalidAddressException, NetException, "Invalid address")
POCO_IMPLEMENT_EXCEPTION(ServiceNotFoundException, NetException, "Service not found")
POCO_IMPLEMENT_EXCEPTION(ConnectionAbortedException, NetException, "Software caused connection abort")
POCO_IMPLEMENT_EXCEPTION(ConnectionResetException, NetException, "Connection reset by peer")
POCO_IMPLEMENT_EXCEPTION(ConnectionRefusedException, NetException, "Connection refused")
POCO_IMPLEMENT_EXCEPTION(DNSException, NetException, "DNS error")
POCO_IMPLEMENT_EXCEPTION(HostNotFoundException, DNSException, "Host not found")
POCO_IMPLEMENT_EXCEPTION(NoAddressFoundException, DNSException, "No address found")
POCO_IMPLEMENT_EXCEPTION(InterfaceNotFoundException, NetException, "Interface not found")
POCO_IMPLEMENT_EXCEPTION(MessageException, NetException, "Malformed message")
POCO_IMPLEMENT_EXCEPTION(MultipartException, MessageException, "Malformed multipart message")
POCO_IMPLEMENT_EXCEPTION(HTTPException, NetException, "HTTP Exception")
POCO_IMPLEMENT_EXCEPTION(NotAuthenticatedException, HTTPException, "No authentication information found")
POCO_IMPLEMENT_EXCEPTION(UnsupportedRedirectException, HTTPException, "Unsupported HTTP redirect (protocol change)")
POCO_IMPLEMENT_EXCEPTION(FTPException, NetException, "FTP Exception")
POCO_IMPLEMENT_EXCEPTION(SMTPException, NetException, "SMTP Exception")
POCO_IMPLEMENT_EXCEPTION(POP3Exception, NetException, "POP3 Exception")
POCO_IMPLEMENT_EXCEPTION(ICMPException, NetException, "ICMP Exception")
} } // namespace Poco::Net

File diff suppressed because it is too large Load Diff

View File

@@ -1,68 +1,68 @@
//
// NullPartHandler.cpp
//
// $Id: //poco/1.2/Net/src/NullPartHandler.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: NullPartHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NullPartHandler.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
using Poco::NullOutputStream;
using Poco::StreamCopier;
namespace Poco {
namespace Net {
NullPartHandler::NullPartHandler()
{
}
NullPartHandler::~NullPartHandler()
{
}
void NullPartHandler::handlePart(const MessageHeader& header, std::istream& stream)
{
NullOutputStream ostr;
StreamCopier::copyStream(stream, ostr);
}
} } // namespace Poco::Net
//
// NullPartHandler.cpp
//
// $Id: //poco/1.2/Net/src/NullPartHandler.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: NullPartHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/NullPartHandler.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
using Poco::NullOutputStream;
using Poco::StreamCopier;
namespace Poco {
namespace Net {
NullPartHandler::NullPartHandler()
{
}
NullPartHandler::~NullPartHandler()
{
}
void NullPartHandler::handlePart(const MessageHeader& header, std::istream& stream)
{
NullOutputStream ostr;
StreamCopier::copyStream(stream, ostr);
}
} } // namespace Poco::Net

View File

@@ -1,300 +1,300 @@
//
// POP3ClientSession.cpp
//
// $Id: //poco/1.2/Net/src/POP3ClientSession.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: POP3ClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/POP3ClientSession.h"
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailStream.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/NetException.h"
#include "Poco/StreamCopier.h"
#include "Poco/NumberFormatter.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <istream>
#include <ctype.h>
using Poco::NumberFormatter;
using Poco::StreamCopier;
namespace Poco {
namespace Net {
class DialogStreamBuf: public Poco::UnbufferedStreamBuf
{
public:
DialogStreamBuf(DialogSocket& socket):
_socket(socket)
{
}
~DialogStreamBuf()
{
}
private:
int readFromDevice()
{
return _socket.get();
}
DialogSocket& _socket;
};
class DialogIOS: public virtual std::ios
{
public:
DialogIOS(DialogSocket& socket):
_buf(socket)
{
poco_ios_init(&_buf);
}
~DialogIOS()
{
}
DialogStreamBuf* rdbuf()
{
return &_buf;
}
protected:
DialogStreamBuf _buf;
};
class DialogInputStream: public DialogIOS, public std::istream
{
public:
DialogInputStream(DialogSocket& socket):
DialogIOS(socket),
std::istream(&_buf)
{
}
~DialogInputStream()
{
}
};
POP3ClientSession::POP3ClientSession(const StreamSocket& socket):
_socket(socket),
_isOpen(true)
{
}
POP3ClientSession::POP3ClientSession(const std::string& host, Poco::UInt16 port):
_socket(SocketAddress(host, port)),
_isOpen(true)
{
}
POP3ClientSession::~POP3ClientSession()
{
try
{
close();
}
catch (...)
{
}
}
void POP3ClientSession::setTimeout(const Poco::Timespan& timeout)
{
_socket.setReceiveTimeout(timeout);
}
Poco::Timespan POP3ClientSession::getTimeout() const
{
return _socket.getReceiveTimeout();
}
void POP3ClientSession::login(const std::string& username, const std::string& password)
{
std::string response;
_socket.receiveMessage(response);
if (!isPositive(response)) throw SMTPException("The POP3 service is unavailable", response);
sendCommand("USER", username, response);
if (!isPositive(response)) throw POP3Exception("Login rejected for user", response);
sendCommand("PASS", password, response);
if (!isPositive(response)) throw POP3Exception("Password rejected for user", response);
}
void POP3ClientSession::close()
{
if (_isOpen)
{
std::string response;
sendCommand("QUIT", response);
_socket.close();
_isOpen = false;
}
}
int POP3ClientSession::messageCount()
{
std::string response;
sendCommand("STAT", response);
if (!isPositive(response)) throw POP3Exception("Cannot determine message count", response);
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
int count = 0;
while (it != end && !isspace(*it)) ++it;
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) count = count*10 + *it++ - '0';
return count;
}
void POP3ClientSession::listMessages(MessageInfoVec& messages)
{
messages.clear();
std::string response;
sendCommand("LIST", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
_socket.receiveMessage(response);
while (response != ".")
{
MessageInfo info = {0, 0};
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
while (it != end && isdigit(*it)) info.id = info.id*10 + *it++ - '0';
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) info.size = info.size*10 + *it++ - '0';
messages.push_back(info);
_socket.receiveMessage(response);
}
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis);
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message, PartHandler& handler)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis, handler);
}
void POP3ClientSession::retrieveMessage(int id, std::ostream& ostr)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
StreamCopier::copyStream(mis, ostr);
}
void POP3ClientSession::retrieveHeader(int id, MessageHeader& header)
{
std::string response;
sendCommand("TOP", NumberFormatter::format(id), "0", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
header.read(mis);
// skip stuff following header
mis.get(); // \r
mis.get(); // \n
}
void POP3ClientSession::deleteMessage(int id)
{
std::string response;
sendCommand("DELE", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot mark message for deletion", response);
}
bool POP3ClientSession::sendCommand(const std::string& command, std::string& response)
{
_socket.sendMessage(command);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
_socket.sendMessage(command, arg);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response)
{
_socket.sendMessage(command, arg1, arg2);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::isPositive(const std::string& response)
{
return response.length() > 0 && response[0] == '+';
}
} } // namespace Poco::Net
//
// POP3ClientSession.cpp
//
// $Id: //poco/1.2/Net/src/POP3ClientSession.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: POP3ClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/POP3ClientSession.h"
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailStream.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/NetException.h"
#include "Poco/StreamCopier.h"
#include "Poco/NumberFormatter.h"
#include "Poco/UnbufferedStreamBuf.h"
#include <istream>
#include <ctype.h>
using Poco::NumberFormatter;
using Poco::StreamCopier;
namespace Poco {
namespace Net {
class DialogStreamBuf: public Poco::UnbufferedStreamBuf
{
public:
DialogStreamBuf(DialogSocket& socket):
_socket(socket)
{
}
~DialogStreamBuf()
{
}
private:
int readFromDevice()
{
return _socket.get();
}
DialogSocket& _socket;
};
class DialogIOS: public virtual std::ios
{
public:
DialogIOS(DialogSocket& socket):
_buf(socket)
{
poco_ios_init(&_buf);
}
~DialogIOS()
{
}
DialogStreamBuf* rdbuf()
{
return &_buf;
}
protected:
DialogStreamBuf _buf;
};
class DialogInputStream: public DialogIOS, public std::istream
{
public:
DialogInputStream(DialogSocket& socket):
DialogIOS(socket),
std::istream(&_buf)
{
}
~DialogInputStream()
{
}
};
POP3ClientSession::POP3ClientSession(const StreamSocket& socket):
_socket(socket),
_isOpen(true)
{
}
POP3ClientSession::POP3ClientSession(const std::string& host, Poco::UInt16 port):
_socket(SocketAddress(host, port)),
_isOpen(true)
{
}
POP3ClientSession::~POP3ClientSession()
{
try
{
close();
}
catch (...)
{
}
}
void POP3ClientSession::setTimeout(const Poco::Timespan& timeout)
{
_socket.setReceiveTimeout(timeout);
}
Poco::Timespan POP3ClientSession::getTimeout() const
{
return _socket.getReceiveTimeout();
}
void POP3ClientSession::login(const std::string& username, const std::string& password)
{
std::string response;
_socket.receiveMessage(response);
if (!isPositive(response)) throw SMTPException("The POP3 service is unavailable", response);
sendCommand("USER", username, response);
if (!isPositive(response)) throw POP3Exception("Login rejected for user", response);
sendCommand("PASS", password, response);
if (!isPositive(response)) throw POP3Exception("Password rejected for user", response);
}
void POP3ClientSession::close()
{
if (_isOpen)
{
std::string response;
sendCommand("QUIT", response);
_socket.close();
_isOpen = false;
}
}
int POP3ClientSession::messageCount()
{
std::string response;
sendCommand("STAT", response);
if (!isPositive(response)) throw POP3Exception("Cannot determine message count", response);
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
int count = 0;
while (it != end && !isspace(*it)) ++it;
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) count = count*10 + *it++ - '0';
return count;
}
void POP3ClientSession::listMessages(MessageInfoVec& messages)
{
messages.clear();
std::string response;
sendCommand("LIST", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
_socket.receiveMessage(response);
while (response != ".")
{
MessageInfo info = {0, 0};
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
while (it != end && isdigit(*it)) info.id = info.id*10 + *it++ - '0';
while (it != end && isspace(*it)) ++it;
while (it != end && isdigit(*it)) info.size = info.size*10 + *it++ - '0';
messages.push_back(info);
_socket.receiveMessage(response);
}
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis);
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message, PartHandler& handler)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis, handler);
}
void POP3ClientSession::retrieveMessage(int id, std::ostream& ostr)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
StreamCopier::copyStream(mis, ostr);
}
void POP3ClientSession::retrieveHeader(int id, MessageHeader& header)
{
std::string response;
sendCommand("TOP", NumberFormatter::format(id), "0", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
header.read(mis);
// skip stuff following header
mis.get(); // \r
mis.get(); // \n
}
void POP3ClientSession::deleteMessage(int id)
{
std::string response;
sendCommand("DELE", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot mark message for deletion", response);
}
bool POP3ClientSession::sendCommand(const std::string& command, std::string& response)
{
_socket.sendMessage(command);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
_socket.sendMessage(command, arg);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response)
{
_socket.sendMessage(command, arg1, arg2);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::isPositive(const std::string& response)
{
return response.length() > 0 && response[0] == '+';
}
} } // namespace Poco::Net

View File

@@ -1,54 +1,54 @@
//
// PartHandler.cpp
//
// $Id: //poco/1.2/Net/src/PartHandler.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: PartHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/PartHandler.h"
namespace Poco {
namespace Net {
PartHandler::PartHandler()
{
}
PartHandler::~PartHandler()
{
}
} } // namespace Poco::Net
//
// PartHandler.cpp
//
// $Id: //poco/1.2/Net/src/PartHandler.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: PartHandler
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/PartHandler.h"
namespace Poco {
namespace Net {
PartHandler::PartHandler()
{
}
PartHandler::~PartHandler()
{
}
} } // namespace Poco::Net

View File

@@ -1,68 +1,68 @@
//
// PartSource.cpp
//
// $Id: //poco/1.2/Net/src/PartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: PartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/PartSource.h"
namespace Poco {
namespace Net {
PartSource::PartSource():
_mediaType("application/octet-stream")
{
}
PartSource::PartSource(const std::string& mediaType):
_mediaType(mediaType)
{
}
PartSource::~PartSource()
{
}
const std::string& PartSource::filename()
{
static const std::string empty;
return empty;
}
} } // namespace Poco::Net
//
// PartSource.cpp
//
// $Id: //poco/1.2/Net/src/PartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: PartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/PartSource.h"
namespace Poco {
namespace Net {
PartSource::PartSource():
_mediaType("application/octet-stream")
{
}
PartSource::PartSource(const std::string& mediaType):
_mediaType(mediaType)
{
}
PartSource::~PartSource()
{
}
const std::string& PartSource::filename()
{
static const std::string empty;
return empty;
}
} } // namespace Poco::Net

View File

@@ -1,124 +1,124 @@
//
// QuotedPrintableDecoder.cpp
//
// $Id: //poco/1.2/Net/src/QuotedPrintableDecoder.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: QuotedPrintableDecoder
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/QuotedPrintableDecoder.h"
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
#include <ctype.h>
using Poco::UnbufferedStreamBuf;
using Poco::NumberParser;
using Poco::DataFormatException;
namespace Poco {
namespace Net {
QuotedPrintableDecoderBuf::QuotedPrintableDecoderBuf(std::istream& istr):
_istr(istr)
{
}
QuotedPrintableDecoderBuf::~QuotedPrintableDecoderBuf()
{
}
int QuotedPrintableDecoderBuf::readFromDevice()
{
int ch = _istr.get();
while (ch == '=')
{
ch = _istr.get();
if (ch == '\r')
{
ch = _istr.get(); // read \n
}
else if (isxdigit(ch))
{
std::string hex;
hex += (char) ch;
ch = _istr.get();
if (isxdigit(ch))
{
hex += (char) ch;
return NumberParser::parseHex(hex);
}
throw DataFormatException("Incomplete hex number in quoted-printable encoded stream");
}
else if (ch != '\n')
{
throw DataFormatException("Invalid occurrence of '=' in quoted-printable encoded stream");
}
ch = _istr.get();
}
return ch;
}
QuotedPrintableDecoderIOS::QuotedPrintableDecoderIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
QuotedPrintableDecoderIOS::~QuotedPrintableDecoderIOS()
{
}
QuotedPrintableDecoderBuf* QuotedPrintableDecoderIOS::rdbuf()
{
return &_buf;
}
QuotedPrintableDecoder::QuotedPrintableDecoder(std::istream& istr):
QuotedPrintableDecoderIOS(istr),
std::istream(&_buf)
{
}
QuotedPrintableDecoder::~QuotedPrintableDecoder()
{
}
} } // namespace Poco::Net
//
// QuotedPrintableDecoder.cpp
//
// $Id: //poco/1.2/Net/src/QuotedPrintableDecoder.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: QuotedPrintableDecoder
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/QuotedPrintableDecoder.h"
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
#include <ctype.h>
using Poco::UnbufferedStreamBuf;
using Poco::NumberParser;
using Poco::DataFormatException;
namespace Poco {
namespace Net {
QuotedPrintableDecoderBuf::QuotedPrintableDecoderBuf(std::istream& istr):
_istr(istr)
{
}
QuotedPrintableDecoderBuf::~QuotedPrintableDecoderBuf()
{
}
int QuotedPrintableDecoderBuf::readFromDevice()
{
int ch = _istr.get();
while (ch == '=')
{
ch = _istr.get();
if (ch == '\r')
{
ch = _istr.get(); // read \n
}
else if (isxdigit(ch))
{
std::string hex;
hex += (char) ch;
ch = _istr.get();
if (isxdigit(ch))
{
hex += (char) ch;
return NumberParser::parseHex(hex);
}
throw DataFormatException("Incomplete hex number in quoted-printable encoded stream");
}
else if (ch != '\n')
{
throw DataFormatException("Invalid occurrence of '=' in quoted-printable encoded stream");
}
ch = _istr.get();
}
return ch;
}
QuotedPrintableDecoderIOS::QuotedPrintableDecoderIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
QuotedPrintableDecoderIOS::~QuotedPrintableDecoderIOS()
{
}
QuotedPrintableDecoderBuf* QuotedPrintableDecoderIOS::rdbuf()
{
return &_buf;
}
QuotedPrintableDecoder::QuotedPrintableDecoder(std::istream& istr):
QuotedPrintableDecoderIOS(istr),
std::istream(&_buf)
{
}
QuotedPrintableDecoder::~QuotedPrintableDecoder()
{
}
} } // namespace Poco::Net

View File

@@ -1,172 +1,172 @@
//
// QuotedPrintableEncoder.cpp
//
// $Id: //poco/1.2/Net/src/QuotedPrintableEncoder.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: QuotedPrintableEncoder
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/QuotedPrintableEncoder.h"
#include "Poco/NumberFormatter.h"
using Poco::UnbufferedStreamBuf;
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
QuotedPrintableEncoderBuf::QuotedPrintableEncoderBuf(std::ostream& ostr):
_pending(-1),
_lineLength(0),
_ostr(ostr)
{
}
QuotedPrintableEncoderBuf::~QuotedPrintableEncoderBuf()
{
try
{
close();
}
catch (...)
{
}
}
int QuotedPrintableEncoderBuf::writeToDevice(char c)
{
if (_pending != -1)
{
if (_pending == '\r' && c == '\n')
writeRaw((char) _pending);
else if (c == '\r' || c == '\n')
writeEncoded((char) _pending);
else
writeRaw((char) _pending);
_pending = -1;
}
if (c == '\t' || c == ' ')
{
_pending = charToInt(c);
return _pending;
}
else if (c == '\r' || c == '\n' || c > 32 && c < 127 && c != '=')
{
writeRaw(c);
}
else
{
writeEncoded(c);
}
return charToInt(c);
}
void QuotedPrintableEncoderBuf::writeEncoded(char c)
{
if (_lineLength >= 73)
{
_ostr << "=\r\n";
_lineLength = 3;
}
else _lineLength += 3;
_ostr << '=' << NumberFormatter::formatHex((unsigned) charToInt(c), 2);
}
void QuotedPrintableEncoderBuf::writeRaw(char c)
{
if (c == '\r' || c == '\n')
{
_ostr.put(c);
_lineLength = 0;
}
else if (_lineLength < 75)
{
_ostr.put(c);
++_lineLength;
}
else
{
_ostr << "=\r\n" << c;
_lineLength = 1;
}
}
int QuotedPrintableEncoderBuf::close()
{
sync();
return _ostr ? 0 : -1;
}
QuotedPrintableEncoderIOS::QuotedPrintableEncoderIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
QuotedPrintableEncoderIOS::~QuotedPrintableEncoderIOS()
{
}
int QuotedPrintableEncoderIOS::close()
{
return _buf.close();
}
QuotedPrintableEncoderBuf* QuotedPrintableEncoderIOS::rdbuf()
{
return &_buf;
}
QuotedPrintableEncoder::QuotedPrintableEncoder(std::ostream& ostr):
QuotedPrintableEncoderIOS(ostr),
std::ostream(&_buf)
{
}
QuotedPrintableEncoder::~QuotedPrintableEncoder()
{
}
} } // namespace Poco::Net
//
// QuotedPrintableEncoder.cpp
//
// $Id: //poco/1.2/Net/src/QuotedPrintableEncoder.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: QuotedPrintableEncoder
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/QuotedPrintableEncoder.h"
#include "Poco/NumberFormatter.h"
using Poco::UnbufferedStreamBuf;
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
QuotedPrintableEncoderBuf::QuotedPrintableEncoderBuf(std::ostream& ostr):
_pending(-1),
_lineLength(0),
_ostr(ostr)
{
}
QuotedPrintableEncoderBuf::~QuotedPrintableEncoderBuf()
{
try
{
close();
}
catch (...)
{
}
}
int QuotedPrintableEncoderBuf::writeToDevice(char c)
{
if (_pending != -1)
{
if (_pending == '\r' && c == '\n')
writeRaw((char) _pending);
else if (c == '\r' || c == '\n')
writeEncoded((char) _pending);
else
writeRaw((char) _pending);
_pending = -1;
}
if (c == '\t' || c == ' ')
{
_pending = charToInt(c);
return _pending;
}
else if (c == '\r' || c == '\n' || c > 32 && c < 127 && c != '=')
{
writeRaw(c);
}
else
{
writeEncoded(c);
}
return charToInt(c);
}
void QuotedPrintableEncoderBuf::writeEncoded(char c)
{
if (_lineLength >= 73)
{
_ostr << "=\r\n";
_lineLength = 3;
}
else _lineLength += 3;
_ostr << '=' << NumberFormatter::formatHex((unsigned) charToInt(c), 2);
}
void QuotedPrintableEncoderBuf::writeRaw(char c)
{
if (c == '\r' || c == '\n')
{
_ostr.put(c);
_lineLength = 0;
}
else if (_lineLength < 75)
{
_ostr.put(c);
++_lineLength;
}
else
{
_ostr << "=\r\n" << c;
_lineLength = 1;
}
}
int QuotedPrintableEncoderBuf::close()
{
sync();
return _ostr ? 0 : -1;
}
QuotedPrintableEncoderIOS::QuotedPrintableEncoderIOS(std::ostream& ostr): _buf(ostr)
{
poco_ios_init(&_buf);
}
QuotedPrintableEncoderIOS::~QuotedPrintableEncoderIOS()
{
}
int QuotedPrintableEncoderIOS::close()
{
return _buf.close();
}
QuotedPrintableEncoderBuf* QuotedPrintableEncoderIOS::rdbuf()
{
return &_buf;
}
QuotedPrintableEncoder::QuotedPrintableEncoder(std::ostream& ostr):
QuotedPrintableEncoderIOS(ostr),
std::ostream(&_buf)
{
}
QuotedPrintableEncoder::~QuotedPrintableEncoder()
{
}
} } // namespace Poco::Net

View File

@@ -1,133 +1,133 @@
//
// RawSocket.cpp
//
// $Id: //poco/1.2/Net/src/RawSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: RawSocket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/RawSocket.h"
#include "Poco/Net/RawSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
RawSocket::RawSocket():
Socket(new RawSocketImpl)
{
}
RawSocket::RawSocket(IPAddress::Family family, int proto):
Socket(new RawSocketImpl(family, proto))
{
}
RawSocket::RawSocket(const SocketAddress& address, bool reuseAddress):
Socket(new RawSocketImpl)
{
bind(address, reuseAddress);
}
RawSocket::RawSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<RawSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
RawSocket::RawSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<RawSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
RawSocket::~RawSocket()
{
}
RawSocket& RawSocket::operator = (const Socket& socket)
{
if (dynamic_cast<RawSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void RawSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void RawSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
int RawSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int RawSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
int RawSocket::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{
return impl()->sendTo(buffer, length, address, flags);
}
int RawSocket::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
return impl()->receiveFrom(buffer, length, address, flags);
}
} } // namespace Poco::Net
//
// RawSocket.cpp
//
// $Id: //poco/1.2/Net/src/RawSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: RawSocket
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/RawSocket.h"
#include "Poco/Net/RawSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
RawSocket::RawSocket():
Socket(new RawSocketImpl)
{
}
RawSocket::RawSocket(IPAddress::Family family, int proto):
Socket(new RawSocketImpl(family, proto))
{
}
RawSocket::RawSocket(const SocketAddress& address, bool reuseAddress):
Socket(new RawSocketImpl)
{
bind(address, reuseAddress);
}
RawSocket::RawSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<RawSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
RawSocket::RawSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<RawSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
RawSocket::~RawSocket()
{
}
RawSocket& RawSocket::operator = (const Socket& socket)
{
if (dynamic_cast<RawSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void RawSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void RawSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
int RawSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int RawSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
int RawSocket::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{
return impl()->sendTo(buffer, length, address, flags);
}
int RawSocket::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
return impl()->receiveFrom(buffer, length, address, flags);
}
} } // namespace Poco::Net

View File

@@ -1,91 +1,91 @@
//
// RawSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/RawSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: RawSocketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/RawSocketImpl.h"
#include "Poco/Net/NetException.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
RawSocketImpl::RawSocketImpl()
{
init(AF_INET);
}
RawSocketImpl::RawSocketImpl(IPAddress::Family family, int proto)
{
if (family == IPAddress::IPv4)
init2(AF_INET, proto);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
init2(AF_INET6, proto);
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to RawSocketImpl");
}
RawSocketImpl::RawSocketImpl(poco_socket_t sockfd):
SocketImpl(sockfd)
{
}
RawSocketImpl::~RawSocketImpl()
{
}
void RawSocketImpl::init(int af)
{
init2(af, IPPROTO_RAW);
}
void RawSocketImpl::init2(int af, int proto)
{
initSocket(af, SOCK_RAW, proto);
setOption(IPPROTO_IP, IP_HDRINCL, 0);
}
} } // namespace Poco::Net
//
// RawSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/RawSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: RawSocketImpl
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/RawSocketImpl.h"
#include "Poco/Net/NetException.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
RawSocketImpl::RawSocketImpl()
{
init(AF_INET);
}
RawSocketImpl::RawSocketImpl(IPAddress::Family family, int proto)
{
if (family == IPAddress::IPv4)
init2(AF_INET, proto);
#if POCO_HAVE_IPv6
else if (family == IPAddress::IPv6)
init2(AF_INET6, proto);
#endif
else throw InvalidArgumentException("Invalid or unsupported address family passed to RawSocketImpl");
}
RawSocketImpl::RawSocketImpl(poco_socket_t sockfd):
SocketImpl(sockfd)
{
}
RawSocketImpl::~RawSocketImpl()
{
}
void RawSocketImpl::init(int af)
{
init2(af, IPPROTO_RAW);
}
void RawSocketImpl::init2(int af, int proto)
{
initSocket(af, SOCK_RAW, proto);
setOption(IPPROTO_IP, IP_HDRINCL, 0);
}
} } // namespace Poco::Net

View File

@@ -1,164 +1,164 @@
//
// SMTPClientSession.cpp
//
// $Id: //poco/1.2/Net/src/SMTPClientSession.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: SMTPClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SMTPClientSession.h"
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailRecipient.h"
#include "Poco/Net/MailStream.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/NetException.h"
#include "Poco/Environment.h"
using Poco::Environment;
namespace Poco {
namespace Net {
SMTPClientSession::SMTPClientSession(const StreamSocket& socket):
_socket(socket),
_isOpen(true)
{
}
SMTPClientSession::SMTPClientSession(const std::string& host, Poco::UInt16 port):
_socket(SocketAddress(host, port)),
_isOpen(true)
{
}
SMTPClientSession::~SMTPClientSession()
{
try
{
close();
}
catch (...)
{
}
}
void SMTPClientSession::setTimeout(const Poco::Timespan& timeout)
{
_socket.setReceiveTimeout(timeout);
}
Poco::Timespan SMTPClientSession::getTimeout() const
{
return _socket.getReceiveTimeout();
}
void SMTPClientSession::login(const std::string& hostname)
{
std::string response;
int status = _socket.receiveStatusMessage(response);
if (!isPositiveCompletion(status)) throw SMTPException("The mail service is unavailable", response);
status = sendCommand("EHLO", hostname, response);
if (isPermanentNegative(status))
status = sendCommand("HELO", hostname, response);
if (!isPositiveCompletion(status)) throw SMTPException("Login failed", response);
}
void SMTPClientSession::login()
{
login(Environment::nodeName());
}
void SMTPClientSession::close()
{
if (_isOpen)
{
std::string response;
sendCommand("QUIT", response);
_socket.close();
_isOpen = false;
}
}
void SMTPClientSession::sendMessage(const MailMessage& message)
{
std::string response;
std::string sender("<");
sender.append(message.getSender());
sender.append(">");
int status = sendCommand("MAIL FROM:", sender, response);
if (!isPositiveCompletion(status)) throw SMTPException("Cannot send message", response);
for (MailMessage::Recipients::const_iterator it = message.recipients().begin(); it != message.recipients().end(); ++it)
{
std::string recipient("<");
recipient.append(it->getAddress());
recipient.append(">");
int status = sendCommand("RCPT TO:", recipient, response);
if (!isPositiveCompletion(status)) throw SMTPException(std::string("Recipient rejected: ") + recipient, response);
}
status = sendCommand("DATA", response);
if (!isPositiveIntermediate(status)) throw SMTPException("Cannot send message data", response);
SocketOutputStream socketStream(_socket);
MailOutputStream mailStream(socketStream);
message.write(mailStream);
mailStream.close();
socketStream.flush();
status = _socket.receiveStatusMessage(response);
if (!isPositiveCompletion(status)) throw SMTPException("The server rejected the message", response);
}
int SMTPClientSession::sendCommand(const std::string& command, std::string& response)
{
_socket.sendMessage(command);
return _socket.receiveStatusMessage(response);
}
int SMTPClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
_socket.sendMessage(command, arg);
return _socket.receiveStatusMessage(response);
}
} } // namespace Poco::Net
//
// SMTPClientSession.cpp
//
// $Id: //poco/1.2/Net/src/SMTPClientSession.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: SMTPClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SMTPClientSession.h"
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailRecipient.h"
#include "Poco/Net/MailStream.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/NetException.h"
#include "Poco/Environment.h"
using Poco::Environment;
namespace Poco {
namespace Net {
SMTPClientSession::SMTPClientSession(const StreamSocket& socket):
_socket(socket),
_isOpen(true)
{
}
SMTPClientSession::SMTPClientSession(const std::string& host, Poco::UInt16 port):
_socket(SocketAddress(host, port)),
_isOpen(true)
{
}
SMTPClientSession::~SMTPClientSession()
{
try
{
close();
}
catch (...)
{
}
}
void SMTPClientSession::setTimeout(const Poco::Timespan& timeout)
{
_socket.setReceiveTimeout(timeout);
}
Poco::Timespan SMTPClientSession::getTimeout() const
{
return _socket.getReceiveTimeout();
}
void SMTPClientSession::login(const std::string& hostname)
{
std::string response;
int status = _socket.receiveStatusMessage(response);
if (!isPositiveCompletion(status)) throw SMTPException("The mail service is unavailable", response);
status = sendCommand("EHLO", hostname, response);
if (isPermanentNegative(status))
status = sendCommand("HELO", hostname, response);
if (!isPositiveCompletion(status)) throw SMTPException("Login failed", response);
}
void SMTPClientSession::login()
{
login(Environment::nodeName());
}
void SMTPClientSession::close()
{
if (_isOpen)
{
std::string response;
sendCommand("QUIT", response);
_socket.close();
_isOpen = false;
}
}
void SMTPClientSession::sendMessage(const MailMessage& message)
{
std::string response;
std::string sender("<");
sender.append(message.getSender());
sender.append(">");
int status = sendCommand("MAIL FROM:", sender, response);
if (!isPositiveCompletion(status)) throw SMTPException("Cannot send message", response);
for (MailMessage::Recipients::const_iterator it = message.recipients().begin(); it != message.recipients().end(); ++it)
{
std::string recipient("<");
recipient.append(it->getAddress());
recipient.append(">");
int status = sendCommand("RCPT TO:", recipient, response);
if (!isPositiveCompletion(status)) throw SMTPException(std::string("Recipient rejected: ") + recipient, response);
}
status = sendCommand("DATA", response);
if (!isPositiveIntermediate(status)) throw SMTPException("Cannot send message data", response);
SocketOutputStream socketStream(_socket);
MailOutputStream mailStream(socketStream);
message.write(mailStream);
mailStream.close();
socketStream.flush();
status = _socket.receiveStatusMessage(response);
if (!isPositiveCompletion(status)) throw SMTPException("The server rejected the message", response);
}
int SMTPClientSession::sendCommand(const std::string& command, std::string& response)
{
_socket.sendMessage(command);
return _socket.receiveStatusMessage(response);
}
int SMTPClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
_socket.sendMessage(command, arg);
return _socket.receiveStatusMessage(response);
}
} } // namespace Poco::Net

View File

@@ -1,130 +1,130 @@
//
// ServerSocket.cpp
//
// $Id: //poco/1.2/Net/src/ServerSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: ServerSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/ServerSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ServerSocket::ServerSocket(): Socket(new ServerSocketImpl)
{
}
ServerSocket::ServerSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<ServerSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ServerSocket::ServerSocket(const SocketAddress& address, int backlog): Socket(new ServerSocketImpl)
{
impl()->bind(address, true);
impl()->listen(backlog);
}
ServerSocket::ServerSocket(Poco::UInt16 port, int backlog): Socket(new ServerSocketImpl)
{
IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port);
impl()->bind(address, true);
impl()->listen(backlog);
}
ServerSocket::ServerSocket(SocketImpl* pImpl, bool ignore): Socket(pImpl)
{
}
ServerSocket::~ServerSocket()
{
}
ServerSocket& ServerSocket::operator = (const Socket& socket)
{
if (dynamic_cast<ServerSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void ServerSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
void ServerSocket::bind(Poco::UInt16 port, bool reuseAddress)
{
IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port);
impl()->bind(address, reuseAddress);
}
void ServerSocket::listen(int backlog)
{
impl()->listen(backlog);
}
StreamSocket ServerSocket::acceptConnection(SocketAddress& clientAddr)
{
return StreamSocket(impl()->acceptConnection(clientAddr));
}
StreamSocket ServerSocket::acceptConnection()
{
SocketAddress clientAddr;
return StreamSocket(impl()->acceptConnection(clientAddr));
}
} } // namespace Poco::Net
//
// ServerSocket.cpp
//
// $Id: //poco/1.2/Net/src/ServerSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: ServerSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/ServerSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
ServerSocket::ServerSocket(): Socket(new ServerSocketImpl)
{
}
ServerSocket::ServerSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<ServerSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
ServerSocket::ServerSocket(const SocketAddress& address, int backlog): Socket(new ServerSocketImpl)
{
impl()->bind(address, true);
impl()->listen(backlog);
}
ServerSocket::ServerSocket(Poco::UInt16 port, int backlog): Socket(new ServerSocketImpl)
{
IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port);
impl()->bind(address, true);
impl()->listen(backlog);
}
ServerSocket::ServerSocket(SocketImpl* pImpl, bool ignore): Socket(pImpl)
{
}
ServerSocket::~ServerSocket()
{
}
ServerSocket& ServerSocket::operator = (const Socket& socket)
{
if (dynamic_cast<ServerSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void ServerSocket::bind(const SocketAddress& address, bool reuseAddress)
{
impl()->bind(address, reuseAddress);
}
void ServerSocket::bind(Poco::UInt16 port, bool reuseAddress)
{
IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port);
impl()->bind(address, reuseAddress);
}
void ServerSocket::listen(int backlog)
{
impl()->listen(backlog);
}
StreamSocket ServerSocket::acceptConnection(SocketAddress& clientAddr)
{
return StreamSocket(impl()->acceptConnection(clientAddr));
}
StreamSocket ServerSocket::acceptConnection()
{
SocketAddress clientAddr;
return StreamSocket(impl()->acceptConnection(clientAddr));
}
} } // namespace Poco::Net

View File

@@ -1,54 +1,54 @@
//
// ServerSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ServerSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: ServerSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ServerSocketImpl.h"
namespace Poco {
namespace Net {
ServerSocketImpl::ServerSocketImpl()
{
}
ServerSocketImpl::~ServerSocketImpl()
{
}
} } // namespace Poco::Net
//
// ServerSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/ServerSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: ServerSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/ServerSocketImpl.h"
namespace Poco {
namespace Net {
ServerSocketImpl::ServerSocketImpl()
{
}
ServerSocketImpl::~ServerSocketImpl()
{
}
} } // namespace Poco::Net

View File

@@ -1,162 +1,162 @@
//
// Socket.cpp
//
// $Id: //poco/1.2/Net/src/Socket.cpp#2 $
//
// Library: Net
// Package: Sockets
// Module: Socket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/Socket.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Timestamp.h"
#include <algorithm>
#include <string.h>
namespace Poco {
namespace Net {
Socket::Socket():
_pImpl(new StreamSocketImpl)
{
}
Socket::Socket(SocketImpl* pImpl):
_pImpl(pImpl)
{
poco_check_ptr (_pImpl);
}
Socket::Socket(const Socket& socket):
_pImpl(socket._pImpl)
{
poco_check_ptr (_pImpl);
_pImpl->duplicate();
}
Socket& Socket::operator = (const Socket& socket)
{
if (&socket != this)
{
if (_pImpl) _pImpl->release();
_pImpl = socket._pImpl;
if (_pImpl) _pImpl->duplicate();
}
return *this;
}
Socket::~Socket()
{
_pImpl->release();
}
int Socket::select(SocketList& readList, SocketList& writeList, SocketList& exceptList, const Poco::Timespan& timeout)
{
fd_set fdRead;
fd_set fdWrite;
fd_set fdExcept;
int nfd = 0;
FD_ZERO(&fdRead);
for (SocketList::const_iterator it = readList.begin(); it != readList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdRead);
}
FD_ZERO(&fdWrite);
for (SocketList::const_iterator it = writeList.begin(); it != writeList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdWrite);
}
FD_ZERO(&fdExcept);
for (SocketList::const_iterator it = exceptList.begin(); it != exceptList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdExcept);
}
Poco::Timespan remainingTime(timeout);
int rc;
do
{
struct timeval tv;
tv.tv_sec = (long) remainingTime.totalSeconds();
tv.tv_usec = (long) remainingTime.useconds();
Poco::Timestamp start;
rc = ::select(nfd + 1, &fdRead, &fdWrite, &fdExcept, &tv);
if (rc < 0 && SocketImpl::lastError() == POCO_EINTR)
{
Poco::Timestamp end;
Poco::Timespan waited = end - start;
if (waited > remainingTime)
remainingTime -= waited;
else
remainingTime = 0;
}
}
while (rc < 0 && SocketImpl::lastError() == POCO_EINTR);
if (rc < 0) SocketImpl::error();
SocketList readyReadList;
for (SocketList::const_iterator it = readList.begin(); it != readList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdRead))
readyReadList.push_back(*it);
}
std::swap(readList, readyReadList);
SocketList readyWriteList;
for (SocketList::const_iterator it = writeList.begin(); it != writeList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdWrite))
readyWriteList.push_back(*it);
}
std::swap(writeList, readyWriteList);
SocketList readyExceptList;
for (SocketList::const_iterator it = exceptList.begin(); it != exceptList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdExcept))
readyExceptList.push_back(*it);
}
std::swap(exceptList, readyExceptList);
return rc;
}
} } // namespace Poco::Net
//
// Socket.cpp
//
// $Id: //poco/1.2/Net/src/Socket.cpp#2 $
//
// Library: Net
// Package: Sockets
// Module: Socket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/Socket.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Timestamp.h"
#include <algorithm>
#include <string.h>
namespace Poco {
namespace Net {
Socket::Socket():
_pImpl(new StreamSocketImpl)
{
}
Socket::Socket(SocketImpl* pImpl):
_pImpl(pImpl)
{
poco_check_ptr (_pImpl);
}
Socket::Socket(const Socket& socket):
_pImpl(socket._pImpl)
{
poco_check_ptr (_pImpl);
_pImpl->duplicate();
}
Socket& Socket::operator = (const Socket& socket)
{
if (&socket != this)
{
if (_pImpl) _pImpl->release();
_pImpl = socket._pImpl;
if (_pImpl) _pImpl->duplicate();
}
return *this;
}
Socket::~Socket()
{
_pImpl->release();
}
int Socket::select(SocketList& readList, SocketList& writeList, SocketList& exceptList, const Poco::Timespan& timeout)
{
fd_set fdRead;
fd_set fdWrite;
fd_set fdExcept;
int nfd = 0;
FD_ZERO(&fdRead);
for (SocketList::const_iterator it = readList.begin(); it != readList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdRead);
}
FD_ZERO(&fdWrite);
for (SocketList::const_iterator it = writeList.begin(); it != writeList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdWrite);
}
FD_ZERO(&fdExcept);
for (SocketList::const_iterator it = exceptList.begin(); it != exceptList.end(); ++it)
{
if (int(it->sockfd()) > nfd)
nfd = int(it->sockfd());
FD_SET(it->sockfd(), &fdExcept);
}
Poco::Timespan remainingTime(timeout);
int rc;
do
{
struct timeval tv;
tv.tv_sec = (long) remainingTime.totalSeconds();
tv.tv_usec = (long) remainingTime.useconds();
Poco::Timestamp start;
rc = ::select(nfd + 1, &fdRead, &fdWrite, &fdExcept, &tv);
if (rc < 0 && SocketImpl::lastError() == POCO_EINTR)
{
Poco::Timestamp end;
Poco::Timespan waited = end - start;
if (waited > remainingTime)
remainingTime -= waited;
else
remainingTime = 0;
}
}
while (rc < 0 && SocketImpl::lastError() == POCO_EINTR);
if (rc < 0) SocketImpl::error();
SocketList readyReadList;
for (SocketList::const_iterator it = readList.begin(); it != readList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdRead))
readyReadList.push_back(*it);
}
std::swap(readList, readyReadList);
SocketList readyWriteList;
for (SocketList::const_iterator it = writeList.begin(); it != writeList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdWrite))
readyWriteList.push_back(*it);
}
std::swap(writeList, readyWriteList);
SocketList readyExceptList;
for (SocketList::const_iterator it = exceptList.begin(); it != exceptList.end(); ++it)
{
if (FD_ISSET(it->sockfd(), &fdExcept))
readyExceptList.push_back(*it);
}
std::swap(exceptList, readyExceptList);
return rc;
}
} } // namespace Poco::Net

View File

@@ -1,386 +1,386 @@
//
// SocketAddress.cpp
//
// $Id: //poco/1.2/Net/src/SocketAddress.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: SocketAddress
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/IPAddress.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/DNS.h"
#include "Poco/RefCountedObject.h"
#include "Poco/NumberParser.h"
#include "Poco/NumberFormatter.h"
#include <algorithm>
#include <string.h>
using Poco::RefCountedObject;
using Poco::NumberParser;
using Poco::NumberFormatter;
using Poco::UInt16;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
//
// SocketAddressImpl
//
class SocketAddressImpl: public RefCountedObject
{
public:
virtual IPAddress host() const = 0;
virtual UInt16 port() const = 0;
virtual poco_socklen_t length() const = 0;
virtual const struct sockaddr* addr() const = 0;
virtual int af() const = 0;
protected:
SocketAddressImpl()
{
}
virtual ~SocketAddressImpl()
{
}
private:
SocketAddressImpl(const SocketAddressImpl&);
SocketAddressImpl& operator = (const SocketAddressImpl&);
};
class IPv4SocketAddressImpl: public SocketAddressImpl
{
public:
IPv4SocketAddressImpl()
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin_family = AF_INET;
poco_set_sin_len(&_addr);
}
IPv4SocketAddressImpl(const struct sockaddr_in* addr)
{
memcpy(&_addr, addr, sizeof(_addr));
}
IPv4SocketAddressImpl(const void* addr, UInt16 port)
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin_family = AF_INET;
memcpy(&_addr.sin_addr, addr, sizeof(_addr.sin_addr));
_addr.sin_port = port;
}
IPAddress host() const
{
return IPAddress(&_addr.sin_addr, sizeof(_addr.sin_addr));
}
UInt16 port() const
{
return _addr.sin_port;
}
poco_socklen_t length() const
{
return sizeof(_addr);
}
const struct sockaddr* addr() const
{
return reinterpret_cast<const struct sockaddr*>(&_addr);
}
int af() const
{
return _addr.sin_family;
}
private:
struct sockaddr_in _addr;
};
#if defined(POCO_HAVE_IPv6)
class IPv6SocketAddressImpl: public SocketAddressImpl
{
public:
IPv6SocketAddressImpl(const struct sockaddr_in6* addr)
{
memcpy(&_addr, addr, sizeof(_addr));
}
IPv6SocketAddressImpl(const void* addr, UInt16 port)
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin6_family = AF_INET6;
poco_set_sin6_len(&_addr);
memcpy(&_addr.sin6_addr, addr, sizeof(_addr.sin6_addr));
_addr.sin6_port = port;
}
IPAddress host() const
{
return IPAddress(&_addr.sin6_addr, sizeof(_addr.sin6_addr));
}
UInt16 port() const
{
return _addr.sin6_port;
}
poco_socklen_t length() const
{
return sizeof(_addr);
}
const struct sockaddr* addr() const
{
return reinterpret_cast<const struct sockaddr*>(&_addr);
}
int af() const
{
return _addr.sin6_family;
}
private:
struct sockaddr_in6 _addr;
};
#endif // POCO_HAVE_IPv6
//
// SocketAddress
//
SocketAddress::SocketAddress()
{
_pImpl = new IPv4SocketAddressImpl;
}
SocketAddress::SocketAddress(const IPAddress& addr, Poco::UInt16 port)
{
init(addr, port);
}
SocketAddress::SocketAddress(const std::string& addr, Poco::UInt16 port)
{
init(addr, port);
}
SocketAddress::SocketAddress(const std::string& addr, const std::string& port)
{
init(addr, resolveService(port));
}
SocketAddress::SocketAddress(const std::string& hostAndPort)
{
poco_assert (!hostAndPort.empty());
std::string host;
std::string port;
std::string::const_iterator it = hostAndPort.begin();
std::string::const_iterator end = hostAndPort.end();
if (*it == '[')
{
++it;
while (it != end && *it != ']') host += *it++;
if (it == end) throw InvalidArgumentException("Malformed IPv6 address");
++it;
}
else
{
while (it != end && *it != ':') host += *it++;
}
if (it != end && *it == ':')
{
++it;
while (it != end) port += *it++;
}
else throw InvalidArgumentException("Missing port number");
init(host, resolveService(port));
}
SocketAddress::SocketAddress(const SocketAddress& addr)
{
_pImpl = addr._pImpl;
_pImpl->duplicate();
}
SocketAddress::SocketAddress(const struct sockaddr* addr, poco_socklen_t length)
{
if (length == sizeof(struct sockaddr_in))
_pImpl = new IPv4SocketAddressImpl(reinterpret_cast<const struct sockaddr_in*>(addr));
#if defined(POCO_HAVE_IPv6)
else if (length == sizeof(struct sockaddr_in6))
_pImpl = new IPv6SocketAddressImpl(reinterpret_cast<const struct sockaddr_in6*>(addr));
#endif
else throw Poco::InvalidArgumentException("Invalid address length passed to SocketAddress()");
}
SocketAddress::~SocketAddress()
{
_pImpl->release();
}
SocketAddress& SocketAddress::operator = (const SocketAddress& addr)
{
if (&addr != this)
{
_pImpl->release();
_pImpl = addr._pImpl;
_pImpl->duplicate();
}
return *this;
}
void SocketAddress::swap(SocketAddress& addr)
{
std::swap(_pImpl, addr._pImpl);
}
IPAddress SocketAddress::host() const
{
return _pImpl->host();
}
Poco::UInt16 SocketAddress::port() const
{
return ntohs(_pImpl->port());
}
poco_socklen_t SocketAddress::length() const
{
return _pImpl->length();
}
const struct sockaddr* SocketAddress::addr() const
{
return _pImpl->addr();
}
int SocketAddress::af() const
{
return _pImpl->af();
}
std::string SocketAddress::toString() const
{
std::string result;
if (host().family() == IPAddress::IPv6)
result.append("[");
result.append(host().toString());
if (host().family() == IPAddress::IPv6)
result.append("]");
result.append(":");
result.append(NumberFormatter::format(port()));
return result;
}
void SocketAddress::init(const IPAddress& host, Poco::UInt16 port)
{
if (host.family() == IPAddress::IPv4)
_pImpl = new IPv4SocketAddressImpl(host.addr(), htons(port));
#if defined(POCO_HAVE_IPv6)
else if (host.family() == IPAddress::IPv6)
_pImpl = new IPv6SocketAddressImpl(host.addr(), htons(port));
#endif
else throw Poco::NotImplementedException("unsupported IP address family");
}
void SocketAddress::init(const std::string& host, Poco::UInt16 port)
{
IPAddress ip;
if (IPAddress::tryParse(host, ip))
{
init(ip, port);
}
else
{
HostEntry he = DNS::hostByName(host);
if (he.addresses().size() > 0)
init(he.addresses()[0], port);
else throw HostNotFoundException("No address found for host", host);
}
}
Poco::UInt16 SocketAddress::resolveService(const std::string& service)
{
unsigned port;
if (NumberParser::tryParseUnsigned(service, port) && port <= 0xFFFF)
{
return (UInt16) port;
}
else
{
struct servent* se = getservbyname(service.c_str(), NULL);
if (se)
return ntohs(se->s_port);
else
throw ServiceNotFoundException(service);
}
}
} } // namespace Poco::Net
//
// SocketAddress.cpp
//
// $Id: //poco/1.2/Net/src/SocketAddress.cpp#1 $
//
// Library: Net
// Package: NetCore
// Module: SocketAddress
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/IPAddress.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/DNS.h"
#include "Poco/RefCountedObject.h"
#include "Poco/NumberParser.h"
#include "Poco/NumberFormatter.h"
#include <algorithm>
#include <string.h>
using Poco::RefCountedObject;
using Poco::NumberParser;
using Poco::NumberFormatter;
using Poco::UInt16;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
//
// SocketAddressImpl
//
class SocketAddressImpl: public RefCountedObject
{
public:
virtual IPAddress host() const = 0;
virtual UInt16 port() const = 0;
virtual poco_socklen_t length() const = 0;
virtual const struct sockaddr* addr() const = 0;
virtual int af() const = 0;
protected:
SocketAddressImpl()
{
}
virtual ~SocketAddressImpl()
{
}
private:
SocketAddressImpl(const SocketAddressImpl&);
SocketAddressImpl& operator = (const SocketAddressImpl&);
};
class IPv4SocketAddressImpl: public SocketAddressImpl
{
public:
IPv4SocketAddressImpl()
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin_family = AF_INET;
poco_set_sin_len(&_addr);
}
IPv4SocketAddressImpl(const struct sockaddr_in* addr)
{
memcpy(&_addr, addr, sizeof(_addr));
}
IPv4SocketAddressImpl(const void* addr, UInt16 port)
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin_family = AF_INET;
memcpy(&_addr.sin_addr, addr, sizeof(_addr.sin_addr));
_addr.sin_port = port;
}
IPAddress host() const
{
return IPAddress(&_addr.sin_addr, sizeof(_addr.sin_addr));
}
UInt16 port() const
{
return _addr.sin_port;
}
poco_socklen_t length() const
{
return sizeof(_addr);
}
const struct sockaddr* addr() const
{
return reinterpret_cast<const struct sockaddr*>(&_addr);
}
int af() const
{
return _addr.sin_family;
}
private:
struct sockaddr_in _addr;
};
#if defined(POCO_HAVE_IPv6)
class IPv6SocketAddressImpl: public SocketAddressImpl
{
public:
IPv6SocketAddressImpl(const struct sockaddr_in6* addr)
{
memcpy(&_addr, addr, sizeof(_addr));
}
IPv6SocketAddressImpl(const void* addr, UInt16 port)
{
memset(&_addr, 0, sizeof(_addr));
_addr.sin6_family = AF_INET6;
poco_set_sin6_len(&_addr);
memcpy(&_addr.sin6_addr, addr, sizeof(_addr.sin6_addr));
_addr.sin6_port = port;
}
IPAddress host() const
{
return IPAddress(&_addr.sin6_addr, sizeof(_addr.sin6_addr));
}
UInt16 port() const
{
return _addr.sin6_port;
}
poco_socklen_t length() const
{
return sizeof(_addr);
}
const struct sockaddr* addr() const
{
return reinterpret_cast<const struct sockaddr*>(&_addr);
}
int af() const
{
return _addr.sin6_family;
}
private:
struct sockaddr_in6 _addr;
};
#endif // POCO_HAVE_IPv6
//
// SocketAddress
//
SocketAddress::SocketAddress()
{
_pImpl = new IPv4SocketAddressImpl;
}
SocketAddress::SocketAddress(const IPAddress& addr, Poco::UInt16 port)
{
init(addr, port);
}
SocketAddress::SocketAddress(const std::string& addr, Poco::UInt16 port)
{
init(addr, port);
}
SocketAddress::SocketAddress(const std::string& addr, const std::string& port)
{
init(addr, resolveService(port));
}
SocketAddress::SocketAddress(const std::string& hostAndPort)
{
poco_assert (!hostAndPort.empty());
std::string host;
std::string port;
std::string::const_iterator it = hostAndPort.begin();
std::string::const_iterator end = hostAndPort.end();
if (*it == '[')
{
++it;
while (it != end && *it != ']') host += *it++;
if (it == end) throw InvalidArgumentException("Malformed IPv6 address");
++it;
}
else
{
while (it != end && *it != ':') host += *it++;
}
if (it != end && *it == ':')
{
++it;
while (it != end) port += *it++;
}
else throw InvalidArgumentException("Missing port number");
init(host, resolveService(port));
}
SocketAddress::SocketAddress(const SocketAddress& addr)
{
_pImpl = addr._pImpl;
_pImpl->duplicate();
}
SocketAddress::SocketAddress(const struct sockaddr* addr, poco_socklen_t length)
{
if (length == sizeof(struct sockaddr_in))
_pImpl = new IPv4SocketAddressImpl(reinterpret_cast<const struct sockaddr_in*>(addr));
#if defined(POCO_HAVE_IPv6)
else if (length == sizeof(struct sockaddr_in6))
_pImpl = new IPv6SocketAddressImpl(reinterpret_cast<const struct sockaddr_in6*>(addr));
#endif
else throw Poco::InvalidArgumentException("Invalid address length passed to SocketAddress()");
}
SocketAddress::~SocketAddress()
{
_pImpl->release();
}
SocketAddress& SocketAddress::operator = (const SocketAddress& addr)
{
if (&addr != this)
{
_pImpl->release();
_pImpl = addr._pImpl;
_pImpl->duplicate();
}
return *this;
}
void SocketAddress::swap(SocketAddress& addr)
{
std::swap(_pImpl, addr._pImpl);
}
IPAddress SocketAddress::host() const
{
return _pImpl->host();
}
Poco::UInt16 SocketAddress::port() const
{
return ntohs(_pImpl->port());
}
poco_socklen_t SocketAddress::length() const
{
return _pImpl->length();
}
const struct sockaddr* SocketAddress::addr() const
{
return _pImpl->addr();
}
int SocketAddress::af() const
{
return _pImpl->af();
}
std::string SocketAddress::toString() const
{
std::string result;
if (host().family() == IPAddress::IPv6)
result.append("[");
result.append(host().toString());
if (host().family() == IPAddress::IPv6)
result.append("]");
result.append(":");
result.append(NumberFormatter::format(port()));
return result;
}
void SocketAddress::init(const IPAddress& host, Poco::UInt16 port)
{
if (host.family() == IPAddress::IPv4)
_pImpl = new IPv4SocketAddressImpl(host.addr(), htons(port));
#if defined(POCO_HAVE_IPv6)
else if (host.family() == IPAddress::IPv6)
_pImpl = new IPv6SocketAddressImpl(host.addr(), htons(port));
#endif
else throw Poco::NotImplementedException("unsupported IP address family");
}
void SocketAddress::init(const std::string& host, Poco::UInt16 port)
{
IPAddress ip;
if (IPAddress::tryParse(host, ip))
{
init(ip, port);
}
else
{
HostEntry he = DNS::hostByName(host);
if (he.addresses().size() > 0)
init(he.addresses()[0], port);
else throw HostNotFoundException("No address found for host", host);
}
}
Poco::UInt16 SocketAddress::resolveService(const std::string& service)
{
unsigned port;
if (NumberParser::tryParseUnsigned(service, port) && port <= 0xFFFF)
{
return (UInt16) port;
}
else
{
struct servent* se = getservbyname(service.c_str(), NULL);
if (se)
return ntohs(se->s_port);
else
throw ServiceNotFoundException(service);
}
}
} } // namespace Poco::Net

File diff suppressed because it is too large Load Diff

View File

@@ -1,116 +1,116 @@
//
// SocketNotification.cpp
//
// $Id: //poco/1.2/Net/src/SocketNotification.cpp#1 $
//
// Library: Net
// Package: Reactor
// Module: SocketNotification
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketNotification.h"
namespace Poco {
namespace Net {
SocketNotification::SocketNotification(SocketReactor* pReactor):
_pReactor(pReactor)
{
}
SocketNotification::~SocketNotification()
{
}
void SocketNotification::setSocket(const Socket& socket)
{
_socket = socket;
}
ReadableNotification::ReadableNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ReadableNotification::~ReadableNotification()
{
}
WritableNotification::WritableNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
WritableNotification::~WritableNotification()
{
}
ErrorNotification::ErrorNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ErrorNotification::~ErrorNotification()
{
}
TimeoutNotification::TimeoutNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
TimeoutNotification::~TimeoutNotification()
{
}
ShutdownNotification::ShutdownNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ShutdownNotification::~ShutdownNotification()
{
}
} } // namespace Poco::Net
//
// SocketNotification.cpp
//
// $Id: //poco/1.2/Net/src/SocketNotification.cpp#1 $
//
// Library: Net
// Package: Reactor
// Module: SocketNotification
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketNotification.h"
namespace Poco {
namespace Net {
SocketNotification::SocketNotification(SocketReactor* pReactor):
_pReactor(pReactor)
{
}
SocketNotification::~SocketNotification()
{
}
void SocketNotification::setSocket(const Socket& socket)
{
_socket = socket;
}
ReadableNotification::ReadableNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ReadableNotification::~ReadableNotification()
{
}
WritableNotification::WritableNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
WritableNotification::~WritableNotification()
{
}
ErrorNotification::ErrorNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ErrorNotification::~ErrorNotification()
{
}
TimeoutNotification::TimeoutNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
TimeoutNotification::~TimeoutNotification()
{
}
ShutdownNotification::ShutdownNotification(SocketReactor* pReactor):
SocketNotification(pReactor)
{
}
ShutdownNotification::~ShutdownNotification()
{
}
} } // namespace Poco::Net

View File

@@ -1,96 +1,96 @@
//
// SocketNotifier.cpp
//
// $Id: //poco/1.2/Net/src/SocketNotifier.cpp#2 $
//
// Library: Net
// Package: Reactor
// Module: SocketNotifier
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketNotifier.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketNotification.h"
namespace Poco {
namespace Net {
SocketNotifier::SocketNotifier(const Socket& socket):
_socket(socket)
{
}
SocketNotifier::~SocketNotifier()
{
}
void SocketNotifier::addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer)
{
_nc.addObserver(observer);
if (observer.accepts(pReactor->_pReadableNotification))
_events.insert(pReactor->_pReadableNotification.get());
else if (observer.accepts(pReactor->_pWritableNotification))
_events.insert(pReactor->_pWritableNotification.get());
else if (observer.accepts(pReactor->_pErrorNotification))
_events.insert(pReactor->_pErrorNotification.get());
else if (observer.accepts(pReactor->_pTimeoutNotification))
_events.insert(pReactor->_pTimeoutNotification.get());
}
void SocketNotifier::removeObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer)
{
_nc.removeObserver(observer);
EventSet::iterator it = _events.end();
if (observer.accepts(pReactor->_pReadableNotification))
it = _events.find(pReactor->_pReadableNotification.get());
else if (observer.accepts(pReactor->_pWritableNotification))
it = _events.find(pReactor->_pWritableNotification.get());
else if (observer.accepts(pReactor->_pErrorNotification))
it = _events.find(pReactor->_pErrorNotification.get());
else if (observer.accepts(pReactor->_pTimeoutNotification))
it = _events.find(pReactor->_pTimeoutNotification.get());
if (it != _events.end())
_events.erase(it);
}
void SocketNotifier::dispatch(SocketNotification* pNotification)
{
pNotification->setSocket(_socket);
pNotification->duplicate();
_nc.postNotification(pNotification);
}
} } // namespace Poco::Net
//
// SocketNotifier.cpp
//
// $Id: //poco/1.2/Net/src/SocketNotifier.cpp#2 $
//
// Library: Net
// Package: Reactor
// Module: SocketNotifier
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketNotifier.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketNotification.h"
namespace Poco {
namespace Net {
SocketNotifier::SocketNotifier(const Socket& socket):
_socket(socket)
{
}
SocketNotifier::~SocketNotifier()
{
}
void SocketNotifier::addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer)
{
_nc.addObserver(observer);
if (observer.accepts(pReactor->_pReadableNotification))
_events.insert(pReactor->_pReadableNotification.get());
else if (observer.accepts(pReactor->_pWritableNotification))
_events.insert(pReactor->_pWritableNotification.get());
else if (observer.accepts(pReactor->_pErrorNotification))
_events.insert(pReactor->_pErrorNotification.get());
else if (observer.accepts(pReactor->_pTimeoutNotification))
_events.insert(pReactor->_pTimeoutNotification.get());
}
void SocketNotifier::removeObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer)
{
_nc.removeObserver(observer);
EventSet::iterator it = _events.end();
if (observer.accepts(pReactor->_pReadableNotification))
it = _events.find(pReactor->_pReadableNotification.get());
else if (observer.accepts(pReactor->_pWritableNotification))
it = _events.find(pReactor->_pWritableNotification.get());
else if (observer.accepts(pReactor->_pErrorNotification))
it = _events.find(pReactor->_pErrorNotification.get());
else if (observer.accepts(pReactor->_pTimeoutNotification))
it = _events.find(pReactor->_pTimeoutNotification.get());
if (it != _events.end())
_events.erase(it);
}
void SocketNotifier::dispatch(SocketNotification* pNotification)
{
pNotification->setSocket(_socket);
pNotification->duplicate();
_nc.postNotification(pNotification);
}
} } // namespace Poco::Net

View File

@@ -1,233 +1,233 @@
//
// SocketReactor.cpp
//
// $Id: //poco/1.2/Net/src/SocketReactor.cpp#1 $
//
// Library: Net
// Package: Reactor
// Module: SocketReactor
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketNotification.h"
#include "Poco/Net/SocketNotifier.h"
#include "Poco/ErrorHandler.h"
#include "Poco/Exception.h"
using Poco::FastMutex;
using Poco::Exception;
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
SocketReactor::SocketReactor():
_stop(false),
_timeout(DEFAULT_TIMEOUT),
_pReadableNotification(new ReadableNotification(this)),
_pWritableNotification(new WritableNotification(this)),
_pErrorNotification(new ErrorNotification(this)),
_pTimeoutNotification(new TimeoutNotification(this)),
_pShutdownNotification(new ShutdownNotification(this))
{
}
SocketReactor::SocketReactor(const Poco::Timespan& timeout):
_stop(false),
_timeout(timeout),
_pReadableNotification(new ReadableNotification(this)),
_pWritableNotification(new WritableNotification(this)),
_pErrorNotification(new ErrorNotification(this)),
_pTimeoutNotification(new TimeoutNotification(this)),
_pShutdownNotification(new ShutdownNotification(this))
{
}
SocketReactor::~SocketReactor()
{
}
void SocketReactor::run()
{
Socket::SocketList readable;
Socket::SocketList writable;
Socket::SocketList except;
while (!_stop)
{
readable.clear();
writable.clear();
except.clear();
{
FastMutex::ScopedLock lock(_mutex);
for (EventHandlerMap::iterator it = _handlers.begin(); it != _handlers.end(); ++it)
{
if (it->second->accepts(_pReadableNotification))
readable.push_back(it->first);
if (it->second->accepts(_pWritableNotification))
writable.push_back(it->first);
if (it->second->accepts(_pErrorNotification))
except.push_back(it->first);
}
}
if (Socket::select(readable, writable, except, _timeout))
{
for (Socket::SocketList::iterator it = readable.begin(); it != readable.end(); ++it)
dispatch(*it, _pReadableNotification);
for (Socket::SocketList::iterator it = writable.begin(); it != writable.end(); ++it)
dispatch(*it, _pWritableNotification);
for (Socket::SocketList::iterator it = except.begin(); it != except.end(); ++it)
dispatch(*it, _pErrorNotification);
}
else onTimeout();
}
onShutdown();
}
void SocketReactor::stop()
{
_stop = true;
}
void SocketReactor::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
const Poco::Timespan& SocketReactor::getTimeout() const
{
return _timeout;
}
void SocketReactor::addEventHandler(const Socket& socket, const Poco::AbstractObserver& observer)
{
FastMutex::ScopedLock lock(_mutex);
NotifierPtr pNotifier;
EventHandlerMap::iterator it = _handlers.find(socket);
if (it == _handlers.end())
{
pNotifier = new SocketNotifier(socket);
_handlers[socket] = pNotifier;
}
else pNotifier = it->second;
pNotifier->addObserver(this, observer);
}
void SocketReactor::removeEventHandler(const Socket& socket, const Poco::AbstractObserver& observer)
{
FastMutex::ScopedLock lock(_mutex);
EventHandlerMap::iterator it = _handlers.find(socket);
if (it != _handlers.end())
{
NotifierPtr pNotifier = it->second;
pNotifier->removeObserver(this, observer);
if (!pNotifier->hasObservers())
_handlers.erase(it);
}
}
void SocketReactor::onTimeout()
{
dispatch(_pTimeoutNotification);
}
void SocketReactor::onShutdown()
{
dispatch(_pShutdownNotification);
}
void SocketReactor::dispatch(const Socket& socket, SocketNotification* pNotification)
{
NotifierPtr pNotifier;
{
FastMutex::ScopedLock lock(_mutex);
EventHandlerMap::iterator it = _handlers.find(socket);
if (it != _handlers.end())
pNotifier = it->second;
else
return;
}
dispatch(pNotifier, pNotification);
}
void SocketReactor::dispatch(SocketNotification* pNotification)
{
std::vector<NotifierPtr> delegates;
delegates.reserve(_handlers.size());
{
FastMutex::ScopedLock lock(_mutex);
for (EventHandlerMap::iterator it = _handlers.begin(); it != _handlers.end(); ++it)
delegates.push_back(it->second);
}
for (std::vector<NotifierPtr>::iterator it = delegates.begin(); it != delegates.end(); ++it)
{
dispatch(*it, pNotification);
}
}
void SocketReactor::dispatch(NotifierPtr& pNotifier, SocketNotification* pNotification)
{
try
{
pNotifier->dispatch(pNotification);
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
} } // namespace Poco::Net
//
// SocketReactor.cpp
//
// $Id: //poco/1.2/Net/src/SocketReactor.cpp#1 $
//
// Library: Net
// Package: Reactor
// Module: SocketReactor
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketNotification.h"
#include "Poco/Net/SocketNotifier.h"
#include "Poco/ErrorHandler.h"
#include "Poco/Exception.h"
using Poco::FastMutex;
using Poco::Exception;
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
SocketReactor::SocketReactor():
_stop(false),
_timeout(DEFAULT_TIMEOUT),
_pReadableNotification(new ReadableNotification(this)),
_pWritableNotification(new WritableNotification(this)),
_pErrorNotification(new ErrorNotification(this)),
_pTimeoutNotification(new TimeoutNotification(this)),
_pShutdownNotification(new ShutdownNotification(this))
{
}
SocketReactor::SocketReactor(const Poco::Timespan& timeout):
_stop(false),
_timeout(timeout),
_pReadableNotification(new ReadableNotification(this)),
_pWritableNotification(new WritableNotification(this)),
_pErrorNotification(new ErrorNotification(this)),
_pTimeoutNotification(new TimeoutNotification(this)),
_pShutdownNotification(new ShutdownNotification(this))
{
}
SocketReactor::~SocketReactor()
{
}
void SocketReactor::run()
{
Socket::SocketList readable;
Socket::SocketList writable;
Socket::SocketList except;
while (!_stop)
{
readable.clear();
writable.clear();
except.clear();
{
FastMutex::ScopedLock lock(_mutex);
for (EventHandlerMap::iterator it = _handlers.begin(); it != _handlers.end(); ++it)
{
if (it->second->accepts(_pReadableNotification))
readable.push_back(it->first);
if (it->second->accepts(_pWritableNotification))
writable.push_back(it->first);
if (it->second->accepts(_pErrorNotification))
except.push_back(it->first);
}
}
if (Socket::select(readable, writable, except, _timeout))
{
for (Socket::SocketList::iterator it = readable.begin(); it != readable.end(); ++it)
dispatch(*it, _pReadableNotification);
for (Socket::SocketList::iterator it = writable.begin(); it != writable.end(); ++it)
dispatch(*it, _pWritableNotification);
for (Socket::SocketList::iterator it = except.begin(); it != except.end(); ++it)
dispatch(*it, _pErrorNotification);
}
else onTimeout();
}
onShutdown();
}
void SocketReactor::stop()
{
_stop = true;
}
void SocketReactor::setTimeout(const Poco::Timespan& timeout)
{
_timeout = timeout;
}
const Poco::Timespan& SocketReactor::getTimeout() const
{
return _timeout;
}
void SocketReactor::addEventHandler(const Socket& socket, const Poco::AbstractObserver& observer)
{
FastMutex::ScopedLock lock(_mutex);
NotifierPtr pNotifier;
EventHandlerMap::iterator it = _handlers.find(socket);
if (it == _handlers.end())
{
pNotifier = new SocketNotifier(socket);
_handlers[socket] = pNotifier;
}
else pNotifier = it->second;
pNotifier->addObserver(this, observer);
}
void SocketReactor::removeEventHandler(const Socket& socket, const Poco::AbstractObserver& observer)
{
FastMutex::ScopedLock lock(_mutex);
EventHandlerMap::iterator it = _handlers.find(socket);
if (it != _handlers.end())
{
NotifierPtr pNotifier = it->second;
pNotifier->removeObserver(this, observer);
if (!pNotifier->hasObservers())
_handlers.erase(it);
}
}
void SocketReactor::onTimeout()
{
dispatch(_pTimeoutNotification);
}
void SocketReactor::onShutdown()
{
dispatch(_pShutdownNotification);
}
void SocketReactor::dispatch(const Socket& socket, SocketNotification* pNotification)
{
NotifierPtr pNotifier;
{
FastMutex::ScopedLock lock(_mutex);
EventHandlerMap::iterator it = _handlers.find(socket);
if (it != _handlers.end())
pNotifier = it->second;
else
return;
}
dispatch(pNotifier, pNotification);
}
void SocketReactor::dispatch(SocketNotification* pNotification)
{
std::vector<NotifierPtr> delegates;
delegates.reserve(_handlers.size());
{
FastMutex::ScopedLock lock(_mutex);
for (EventHandlerMap::iterator it = _handlers.begin(); it != _handlers.end(); ++it)
delegates.push_back(it->second);
}
for (std::vector<NotifierPtr>::iterator it = delegates.begin(); it != delegates.end(); ++it)
{
dispatch(*it, pNotification);
}
}
void SocketReactor::dispatch(NotifierPtr& pNotifier, SocketNotification* pNotification)
{
try
{
pNotifier->dispatch(pNotification);
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
} } // namespace Poco::Net

View File

@@ -1,178 +1,178 @@
//
// SocketStream.cpp
//
// $Id: //poco/1.2/Net/src/SocketStream.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: SocketStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Exception.h"
using Poco::BufferedBidirectionalStreamBuf;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
//
// SocketStreamBuf
//
SocketStreamBuf::SocketStreamBuf(const Socket& socket):
BufferedBidirectionalStreamBuf(STREAM_BUFFER_SIZE, std::ios::in | std::ios::out),
_pImpl(dynamic_cast<StreamSocketImpl*>(socket.impl()))
{
if (_pImpl)
_pImpl->duplicate();
else
throw InvalidArgumentException("Invalid or null SocketImpl passed to SocketStreamBuf");
}
SocketStreamBuf::~SocketStreamBuf()
{
_pImpl->release();
}
int SocketStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
return _pImpl->receiveBytes(buffer, (int) length);
}
int SocketStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _pImpl->sendBytes(buffer, (int) length);
}
//
// SocketIOS
//
SocketIOS::SocketIOS(const Socket& socket):
_buf(socket)
{
poco_ios_init(&_buf);
}
SocketIOS::~SocketIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
SocketStreamBuf* SocketIOS::rdbuf()
{
return &_buf;
}
void SocketIOS::close()
{
_buf.sync();
_buf.socketImpl()->close();
}
StreamSocket SocketIOS::socket() const
{
return StreamSocket(_buf.socketImpl());
}
//
// SocketOutputStream
//
SocketOutputStream::SocketOutputStream(const Socket& socket):
SocketIOS(socket),
std::ostream(&_buf)
{
}
SocketOutputStream::~SocketOutputStream()
{
}
//
// SocketInputStream
//
SocketInputStream::SocketInputStream(const Socket& socket):
SocketIOS(socket),
std::istream(&_buf)
{
}
SocketInputStream::~SocketInputStream()
{
}
//
// SocketStream
//
SocketStream::SocketStream(const Socket& socket):
SocketIOS(socket),
std::iostream(&_buf)
{
}
SocketStream::~SocketStream()
{
}
} } // namespace Poco::Net
//
// SocketStream.cpp
//
// $Id: //poco/1.2/Net/src/SocketStream.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: SocketStream
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Exception.h"
using Poco::BufferedBidirectionalStreamBuf;
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
//
// SocketStreamBuf
//
SocketStreamBuf::SocketStreamBuf(const Socket& socket):
BufferedBidirectionalStreamBuf(STREAM_BUFFER_SIZE, std::ios::in | std::ios::out),
_pImpl(dynamic_cast<StreamSocketImpl*>(socket.impl()))
{
if (_pImpl)
_pImpl->duplicate();
else
throw InvalidArgumentException("Invalid or null SocketImpl passed to SocketStreamBuf");
}
SocketStreamBuf::~SocketStreamBuf()
{
_pImpl->release();
}
int SocketStreamBuf::readFromDevice(char* buffer, std::streamsize length)
{
return _pImpl->receiveBytes(buffer, (int) length);
}
int SocketStreamBuf::writeToDevice(const char* buffer, std::streamsize length)
{
return _pImpl->sendBytes(buffer, (int) length);
}
//
// SocketIOS
//
SocketIOS::SocketIOS(const Socket& socket):
_buf(socket)
{
poco_ios_init(&_buf);
}
SocketIOS::~SocketIOS()
{
try
{
_buf.sync();
}
catch (...)
{
}
}
SocketStreamBuf* SocketIOS::rdbuf()
{
return &_buf;
}
void SocketIOS::close()
{
_buf.sync();
_buf.socketImpl()->close();
}
StreamSocket SocketIOS::socket() const
{
return StreamSocket(_buf.socketImpl());
}
//
// SocketOutputStream
//
SocketOutputStream::SocketOutputStream(const Socket& socket):
SocketIOS(socket),
std::ostream(&_buf)
{
}
SocketOutputStream::~SocketOutputStream()
{
}
//
// SocketInputStream
//
SocketInputStream::SocketInputStream(const Socket& socket):
SocketIOS(socket),
std::istream(&_buf)
{
}
SocketInputStream::~SocketInputStream()
{
}
//
// SocketStream
//
SocketStream::SocketStream(const Socket& socket):
SocketIOS(socket),
std::iostream(&_buf)
{
}
SocketStream::~SocketStream()
{
}
} } // namespace Poco::Net

View File

@@ -1,143 +1,143 @@
//
// StreamSocket.cpp
//
// $Id: //poco/1.2/Net/src/StreamSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: StreamSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
StreamSocket::StreamSocket(): Socket(new StreamSocketImpl)
{
}
StreamSocket::StreamSocket(const SocketAddress& address): Socket(new StreamSocketImpl)
{
connect(address);
}
StreamSocket::StreamSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<StreamSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
StreamSocket::StreamSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<StreamSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
StreamSocket::~StreamSocket()
{
}
StreamSocket& StreamSocket::operator = (const Socket& socket)
{
if (dynamic_cast<StreamSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void StreamSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void StreamSocket::connect(const SocketAddress& address, const Poco::Timespan& timeout)
{
impl()->connect(address, timeout);
}
void StreamSocket::connectNB(const SocketAddress& address)
{
impl()->connectNB(address);
}
void StreamSocket::shutdownReceive()
{
impl()->shutdownReceive();
}
void StreamSocket::shutdownSend()
{
impl()->shutdownSend();
}
void StreamSocket::shutdown()
{
impl()->shutdown();
}
int StreamSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int StreamSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
void StreamSocket::sendUrgent(unsigned char data)
{
impl()->sendUrgent(data);
}
} } // namespace Poco::Net
//
// StreamSocket.cpp
//
// $Id: //poco/1.2/Net/src/StreamSocket.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: StreamSocket
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Exception.h"
using Poco::InvalidArgumentException;
namespace Poco {
namespace Net {
StreamSocket::StreamSocket(): Socket(new StreamSocketImpl)
{
}
StreamSocket::StreamSocket(const SocketAddress& address): Socket(new StreamSocketImpl)
{
connect(address);
}
StreamSocket::StreamSocket(const Socket& socket): Socket(socket)
{
if (!dynamic_cast<StreamSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
StreamSocket::StreamSocket(SocketImpl* pImpl): Socket(pImpl)
{
if (!dynamic_cast<StreamSocketImpl*>(impl()))
throw InvalidArgumentException("Cannot assign incompatible socket");
}
StreamSocket::~StreamSocket()
{
}
StreamSocket& StreamSocket::operator = (const Socket& socket)
{
if (dynamic_cast<StreamSocketImpl*>(socket.impl()))
Socket::operator = (socket);
else
throw InvalidArgumentException("Cannot assign incompatible socket");
return *this;
}
void StreamSocket::connect(const SocketAddress& address)
{
impl()->connect(address);
}
void StreamSocket::connect(const SocketAddress& address, const Poco::Timespan& timeout)
{
impl()->connect(address, timeout);
}
void StreamSocket::connectNB(const SocketAddress& address)
{
impl()->connectNB(address);
}
void StreamSocket::shutdownReceive()
{
impl()->shutdownReceive();
}
void StreamSocket::shutdownSend()
{
impl()->shutdownSend();
}
void StreamSocket::shutdown()
{
impl()->shutdown();
}
int StreamSocket::sendBytes(const void* buffer, int length, int flags)
{
return impl()->sendBytes(buffer, length, flags);
}
int StreamSocket::receiveBytes(void* buffer, int length, int flags)
{
return impl()->receiveBytes(buffer, length, flags);
}
void StreamSocket::sendUrgent(unsigned char data)
{
impl()->sendUrgent(data);
}
} } // namespace Poco::Net

View File

@@ -1,73 +1,73 @@
//
// StreamSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/StreamSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: StreamSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StreamSocketImpl.h"
namespace Poco {
namespace Net {
StreamSocketImpl::StreamSocketImpl()
{
}
StreamSocketImpl::StreamSocketImpl(poco_socket_t sockfd): SocketImpl(sockfd)
{
}
StreamSocketImpl::~StreamSocketImpl()
{
}
int StreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
{
const char* p = reinterpret_cast<const char*>(buffer);
int remaining = length;
while (remaining > 0)
{
int n = SocketImpl::sendBytes(p, length, flags);
p += n;
remaining -= n;
}
return length;
}
} } // namespace Poco::Net
//
// StreamSocketImpl.cpp
//
// $Id: //poco/1.2/Net/src/StreamSocketImpl.cpp#1 $
//
// Library: Net
// Package: Sockets
// Module: StreamSocketImpl
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StreamSocketImpl.h"
namespace Poco {
namespace Net {
StreamSocketImpl::StreamSocketImpl()
{
}
StreamSocketImpl::StreamSocketImpl(poco_socket_t sockfd): SocketImpl(sockfd)
{
}
StreamSocketImpl::~StreamSocketImpl()
{
}
int StreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
{
const char* p = reinterpret_cast<const char*>(buffer);
int remaining = length;
while (remaining > 0)
{
int n = SocketImpl::sendBytes(p, length, flags);
p += n;
remaining -= n;
}
return length;
}
} } // namespace Poco::Net

View File

@@ -1,83 +1,83 @@
//
// StringPartSource.cpp
//
// $Id: //poco/1.2/Net/src/StringPartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: StringPartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StringPartSource.h"
namespace Poco {
namespace Net {
StringPartSource::StringPartSource(const std::string& str):
PartSource("text/plain"),
_istr(str)
{
}
StringPartSource::StringPartSource(const std::string& str, const std::string& mediaType):
PartSource(mediaType),
_istr(str)
{
}
StringPartSource::StringPartSource(const std::string& str, const std::string& mediaType, const std::string& filename):
PartSource(mediaType),
_istr(str),
_filename(filename)
{
}
StringPartSource::~StringPartSource()
{
}
std::istream& StringPartSource::stream()
{
return _istr;
}
const std::string& StringPartSource::filename()
{
return _filename;
}
} } // namespace Poco::Net
//
// StringPartSource.cpp
//
// $Id: //poco/1.2/Net/src/StringPartSource.cpp#1 $
//
// Library: Net
// Package: Messages
// Module: StringPartSource
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/StringPartSource.h"
namespace Poco {
namespace Net {
StringPartSource::StringPartSource(const std::string& str):
PartSource("text/plain"),
_istr(str)
{
}
StringPartSource::StringPartSource(const std::string& str, const std::string& mediaType):
PartSource(mediaType),
_istr(str)
{
}
StringPartSource::StringPartSource(const std::string& str, const std::string& mediaType, const std::string& filename):
PartSource(mediaType),
_istr(str),
_filename(filename)
{
}
StringPartSource::~StringPartSource()
{
}
std::istream& StringPartSource::stream()
{
return _istr;
}
const std::string& StringPartSource::filename()
{
return _filename;
}
} } // namespace Poco::Net

View File

@@ -1,176 +1,176 @@
//
// TCPServer.cpp
//
// $Id: //poco/1.2/Net/src/TCPServer.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServer
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerDispatcher.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
#include "Poco/ErrorHandler.h"
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
TCPServer::TCPServer(TCPServerConnectionFactory* pFactory, const ServerSocket& socket, TCPServerParams* pParams):
_socket(socket),
_pDispatcher(new TCPServerDispatcher(pFactory, Poco::ThreadPool::defaultPool(), pParams)),
_thread(threadName(socket)),
_stopped(false)
{
}
TCPServer::TCPServer(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams* pParams):
_socket(socket),
_pDispatcher(new TCPServerDispatcher(pFactory, threadPool, pParams)),
_thread(threadName(socket)),
_stopped(false)
{
}
TCPServer::~TCPServer()
{
stop();
_pDispatcher->release();
}
const TCPServerParams& TCPServer::params() const
{
return _pDispatcher->params();
}
void TCPServer::start()
{
poco_assert (!_stopped);
_thread.start(*this);
}
void TCPServer::stop()
{
if (!_stopped)
{
_stopped = true;
_thread.join();
_pDispatcher->stop();
}
}
void TCPServer::run()
{
while (!_stopped)
{
Poco::Timespan timeout(250000);
if (_socket.poll(timeout, Socket::SELECT_READ))
{
try
{
StreamSocket ss = _socket.acceptConnection();
_pDispatcher->enqueue(ss);
}
catch (Poco::Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
}
}
int TCPServer::currentThreads() const
{
return _pDispatcher->currentThreads();
}
int TCPServer::totalConnections() const
{
return _pDispatcher->totalConnections();
}
int TCPServer::currentConnections() const
{
return _pDispatcher->currentConnections();
}
int TCPServer::maxConcurrentConnections() const
{
return _pDispatcher->maxConcurrentConnections();
}
int TCPServer::queuedConnections() const
{
return _pDispatcher->queuedConnections();
}
int TCPServer::refusedConnections() const
{
return _pDispatcher->refusedConnections();
}
std::string TCPServer::threadName(const ServerSocket& socket)
{
std::string name("TCPServer: ");
name.append(socket.address().toString());
return name;
}
} } // namespace Poco::Net
//
// TCPServer.cpp
//
// $Id: //poco/1.2/Net/src/TCPServer.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServer
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerDispatcher.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
#include "Poco/ErrorHandler.h"
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
TCPServer::TCPServer(TCPServerConnectionFactory* pFactory, const ServerSocket& socket, TCPServerParams* pParams):
_socket(socket),
_pDispatcher(new TCPServerDispatcher(pFactory, Poco::ThreadPool::defaultPool(), pParams)),
_thread(threadName(socket)),
_stopped(false)
{
}
TCPServer::TCPServer(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams* pParams):
_socket(socket),
_pDispatcher(new TCPServerDispatcher(pFactory, threadPool, pParams)),
_thread(threadName(socket)),
_stopped(false)
{
}
TCPServer::~TCPServer()
{
stop();
_pDispatcher->release();
}
const TCPServerParams& TCPServer::params() const
{
return _pDispatcher->params();
}
void TCPServer::start()
{
poco_assert (!_stopped);
_thread.start(*this);
}
void TCPServer::stop()
{
if (!_stopped)
{
_stopped = true;
_thread.join();
_pDispatcher->stop();
}
}
void TCPServer::run()
{
while (!_stopped)
{
Poco::Timespan timeout(250000);
if (_socket.poll(timeout, Socket::SELECT_READ))
{
try
{
StreamSocket ss = _socket.acceptConnection();
_pDispatcher->enqueue(ss);
}
catch (Poco::Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
}
}
int TCPServer::currentThreads() const
{
return _pDispatcher->currentThreads();
}
int TCPServer::totalConnections() const
{
return _pDispatcher->totalConnections();
}
int TCPServer::currentConnections() const
{
return _pDispatcher->currentConnections();
}
int TCPServer::maxConcurrentConnections() const
{
return _pDispatcher->maxConcurrentConnections();
}
int TCPServer::queuedConnections() const
{
return _pDispatcher->queuedConnections();
}
int TCPServer::refusedConnections() const
{
return _pDispatcher->refusedConnections();
}
std::string TCPServer::threadName(const ServerSocket& socket)
{
std::string name("TCPServer: ");
name.append(socket.address().toString());
return name;
}
} } // namespace Poco::Net

View File

@@ -1,82 +1,82 @@
//
// TCPServerConnection.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerConnection.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerConnection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Exception.h"
#include "Poco/ErrorHandler.h"
using Poco::Exception;
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
TCPServerConnection::TCPServerConnection(const StreamSocket& socket):
_socket(socket)
{
}
TCPServerConnection::~TCPServerConnection()
{
}
void TCPServerConnection::start()
{
try
{
run();
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
} } // namespace Poco::Net
//
// TCPServerConnection.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerConnection.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerConnection
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Exception.h"
#include "Poco/ErrorHandler.h"
using Poco::Exception;
using Poco::ErrorHandler;
namespace Poco {
namespace Net {
TCPServerConnection::TCPServerConnection(const StreamSocket& socket):
_socket(socket)
{
}
TCPServerConnection::~TCPServerConnection()
{
}
void TCPServerConnection::start()
{
try
{
run();
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
}
} } // namespace Poco::Net

View File

@@ -1,54 +1,54 @@
//
// TCPServerConnectionFactory.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerConnectionFactory.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerConnectionFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerConnectionFactory.h"
namespace Poco {
namespace Net {
TCPServerConnectionFactory::TCPServerConnectionFactory()
{
}
TCPServerConnectionFactory::~TCPServerConnectionFactory()
{
}
} } // namespace Poco::Net
//
// TCPServerConnectionFactory.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerConnectionFactory.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerConnectionFactory
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerConnectionFactory.h"
namespace Poco {
namespace Net {
TCPServerConnectionFactory::TCPServerConnectionFactory()
{
}
TCPServerConnectionFactory::~TCPServerConnectionFactory()
{
}
} } // namespace Poco::Net

View File

@@ -1,256 +1,256 @@
//
// TCPServerDispatcher.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerDispatcher.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerDispatcher
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerDispatcher.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/TCPServerParams.h"
#include "Poco/Notification.h"
#include "Poco/AutoPtr.h"
#include <memory>
using Poco::Notification;
using Poco::FastMutex;
using Poco::AutoPtr;
namespace Poco {
namespace Net {
class TCPConnectionNotification: public Notification
{
public:
TCPConnectionNotification(const StreamSocket& socket):
_socket(socket)
{
}
~TCPConnectionNotification()
{
}
const StreamSocket& socket() const
{
return _socket;
}
private:
StreamSocket _socket;
};
TCPServerDispatcher::TCPServerDispatcher(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, TCPServerParams* pParams):
_rc(1),
_pParams(pParams),
_currentThreads(0),
_totalConnections(0),
_currentConnections(0),
_maxConcurrentConnections(0),
_refusedConnections(0),
_stopped(false),
_pConnectionFactory(pFactory),
_threadPool(threadPool)
{
poco_check_ptr (pFactory);
if (!_pParams)
_pParams = new TCPServerParams;
if (_pParams->getMaxThreads() == 0)
_pParams->setMaxThreads(threadPool.capacity());
}
TCPServerDispatcher::~TCPServerDispatcher()
{
_pParams->release();
delete _pConnectionFactory;
}
void TCPServerDispatcher::duplicate()
{
_mutex.lock();
++_rc;
_mutex.unlock();
}
void TCPServerDispatcher::release()
{
_mutex.lock();
int rc = --_rc;
_mutex.unlock();
if (rc == 0) delete this;
}
void TCPServerDispatcher::run()
{
AutoPtr<TCPServerDispatcher> guard(this, true); // ensure object stays alive
int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds();
for (;;)
{
AutoPtr<Notification> pNf = _queue.waitDequeueNotification(idleTime);
if (pNf)
{
TCPConnectionNotification* pCNf = dynamic_cast<TCPConnectionNotification*>(pNf.get());
if (pCNf)
{
std::auto_ptr<TCPServerConnection> pConnection(_pConnectionFactory->createConnection(pCNf->socket()));
poco_check_ptr(pConnection.get());
beginConnection();
pConnection->start();
endConnection();
}
}
FastMutex::ScopedLock lock(_mutex);
if (_stopped || _currentThreads > 1 && _queue.empty())
{
--_currentThreads;
break;
}
}
}
void TCPServerDispatcher::enqueue(const StreamSocket& socket)
{
FastMutex::ScopedLock lock(_mutex);
if (_queue.size() < _pParams->getMaxQueued())
{
_queue.enqueueNotification(new TCPConnectionNotification(socket));
if (!_queue.hasIdleThreads() && _currentThreads < _pParams->getMaxThreads())
{
try
{
static const std::string threadName("TCPServerConnection");
_threadPool.start(*this, threadName);
++_currentThreads;
}
catch (Poco::Exception&)
{
// no problem here, connection is already queued
// and a new thread might be available later.
}
}
}
else
{
++_refusedConnections;
}
}
void TCPServerDispatcher::stop()
{
_stopped = true;
_queue.clear();
_queue.wakeUpAll();
}
int TCPServerDispatcher::currentThreads() const
{
FastMutex::ScopedLock lock(_mutex);
return _currentThreads;
}
int TCPServerDispatcher::totalConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _totalConnections;
}
int TCPServerDispatcher::currentConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _currentConnections;
}
int TCPServerDispatcher::maxConcurrentConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _maxConcurrentConnections;
}
int TCPServerDispatcher::queuedConnections() const
{
return _queue.size();
}
int TCPServerDispatcher::refusedConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _refusedConnections;
}
void TCPServerDispatcher::beginConnection()
{
FastMutex::ScopedLock lock(_mutex);
++_totalConnections;
++_currentConnections;
if (_currentConnections > _maxConcurrentConnections)
_maxConcurrentConnections = _currentConnections;
}
void TCPServerDispatcher::endConnection()
{
FastMutex::ScopedLock lock(_mutex);
--_currentConnections;
}
} } // namespace Poco::Net
//
// TCPServerDispatcher.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerDispatcher.cpp#1 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerDispatcher
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerDispatcher.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/TCPServerParams.h"
#include "Poco/Notification.h"
#include "Poco/AutoPtr.h"
#include <memory>
using Poco::Notification;
using Poco::FastMutex;
using Poco::AutoPtr;
namespace Poco {
namespace Net {
class TCPConnectionNotification: public Notification
{
public:
TCPConnectionNotification(const StreamSocket& socket):
_socket(socket)
{
}
~TCPConnectionNotification()
{
}
const StreamSocket& socket() const
{
return _socket;
}
private:
StreamSocket _socket;
};
TCPServerDispatcher::TCPServerDispatcher(TCPServerConnectionFactory* pFactory, Poco::ThreadPool& threadPool, TCPServerParams* pParams):
_rc(1),
_pParams(pParams),
_currentThreads(0),
_totalConnections(0),
_currentConnections(0),
_maxConcurrentConnections(0),
_refusedConnections(0),
_stopped(false),
_pConnectionFactory(pFactory),
_threadPool(threadPool)
{
poco_check_ptr (pFactory);
if (!_pParams)
_pParams = new TCPServerParams;
if (_pParams->getMaxThreads() == 0)
_pParams->setMaxThreads(threadPool.capacity());
}
TCPServerDispatcher::~TCPServerDispatcher()
{
_pParams->release();
delete _pConnectionFactory;
}
void TCPServerDispatcher::duplicate()
{
_mutex.lock();
++_rc;
_mutex.unlock();
}
void TCPServerDispatcher::release()
{
_mutex.lock();
int rc = --_rc;
_mutex.unlock();
if (rc == 0) delete this;
}
void TCPServerDispatcher::run()
{
AutoPtr<TCPServerDispatcher> guard(this, true); // ensure object stays alive
int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds();
for (;;)
{
AutoPtr<Notification> pNf = _queue.waitDequeueNotification(idleTime);
if (pNf)
{
TCPConnectionNotification* pCNf = dynamic_cast<TCPConnectionNotification*>(pNf.get());
if (pCNf)
{
std::auto_ptr<TCPServerConnection> pConnection(_pConnectionFactory->createConnection(pCNf->socket()));
poco_check_ptr(pConnection.get());
beginConnection();
pConnection->start();
endConnection();
}
}
FastMutex::ScopedLock lock(_mutex);
if (_stopped || _currentThreads > 1 && _queue.empty())
{
--_currentThreads;
break;
}
}
}
void TCPServerDispatcher::enqueue(const StreamSocket& socket)
{
FastMutex::ScopedLock lock(_mutex);
if (_queue.size() < _pParams->getMaxQueued())
{
_queue.enqueueNotification(new TCPConnectionNotification(socket));
if (!_queue.hasIdleThreads() && _currentThreads < _pParams->getMaxThreads())
{
try
{
static const std::string threadName("TCPServerConnection");
_threadPool.start(*this, threadName);
++_currentThreads;
}
catch (Poco::Exception&)
{
// no problem here, connection is already queued
// and a new thread might be available later.
}
}
}
else
{
++_refusedConnections;
}
}
void TCPServerDispatcher::stop()
{
_stopped = true;
_queue.clear();
_queue.wakeUpAll();
}
int TCPServerDispatcher::currentThreads() const
{
FastMutex::ScopedLock lock(_mutex);
return _currentThreads;
}
int TCPServerDispatcher::totalConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _totalConnections;
}
int TCPServerDispatcher::currentConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _currentConnections;
}
int TCPServerDispatcher::maxConcurrentConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _maxConcurrentConnections;
}
int TCPServerDispatcher::queuedConnections() const
{
return _queue.size();
}
int TCPServerDispatcher::refusedConnections() const
{
FastMutex::ScopedLock lock(_mutex);
return _refusedConnections;
}
void TCPServerDispatcher::beginConnection()
{
FastMutex::ScopedLock lock(_mutex);
++_totalConnections;
++_currentConnections;
if (_currentConnections > _maxConcurrentConnections)
_maxConcurrentConnections = _currentConnections;
}
void TCPServerDispatcher::endConnection()
{
FastMutex::ScopedLock lock(_mutex);
--_currentConnections;
}
} } // namespace Poco::Net

View File

@@ -1,79 +1,79 @@
//
// TCPServerParams.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerParams.cpp#2 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerParams
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerParams.h"
namespace Poco {
namespace Net {
TCPServerParams::TCPServerParams():
_threadIdleTime(10000000),
_maxThreads(0),
_maxQueued(64)
{
}
TCPServerParams::~TCPServerParams()
{
}
void TCPServerParams::setThreadIdleTime(const Poco::Timespan& milliseconds)
{
_threadIdleTime = milliseconds;
}
void TCPServerParams::setMaxThreads(int count)
{
poco_assert (count > 0);
_maxThreads = count;
}
void TCPServerParams::setMaxQueued(int count)
{
poco_assert (count > 0);
_maxQueued = count;
}
} } // namespace Poco::Net
//
// TCPServerParams.cpp
//
// $Id: //poco/1.2/Net/src/TCPServerParams.cpp#2 $
//
// Library: Net
// Package: TCPServer
// Module: TCPServerParams
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/TCPServerParams.h"
namespace Poco {
namespace Net {
TCPServerParams::TCPServerParams():
_threadIdleTime(10000000),
_maxThreads(0),
_maxQueued(64)
{
}
TCPServerParams::~TCPServerParams()
{
}
void TCPServerParams::setThreadIdleTime(const Poco::Timespan& milliseconds)
{
_threadIdleTime = milliseconds;
}
void TCPServerParams::setMaxThreads(int count)
{
poco_assert (count > 0);
_maxThreads = count;
}
void TCPServerParams::setMaxQueued(int count)
{
poco_assert (count > 0);
_maxQueued = count;
}
} } // namespace Poco::Net