committed latest 1.3 snapshot

This commit is contained in:
Guenter Obiltschnig
2007-04-18 16:25:02 +00:00
parent 965b9458d5
commit 6b529b6061
35 changed files with 2017 additions and 282 deletions

View File

@@ -1,7 +1,7 @@
#
# Makefile
#
# $Id: //poco/Main/Net/Makefile#34 $
# $Id: //poco/Main/Net/Makefile#36 $
#
# Makefile for Poco Net
#
@@ -17,19 +17,19 @@ objects = \
DatagramSocketImpl FilePartSource HTTPServerConnection MessageHeader \
HTTPChunkedStream HTTPServerConnectionFactory MulticastSocket SocketStream \
HTTPClientSession HTTPServerParams MultipartReader StreamSocket SocketImpl \
HTTPFixedLengthStream HTTPServerRequest MultipartWriter StreamSocketImpl \
HTTPHeaderStream HTTPServerResponse NameValueCollection TCPServer \
HTTPFixedLengthStream HTTPServerRequest HTTPServerRequestImpl MultipartWriter StreamSocketImpl \
HTTPHeaderStream HTTPServerResponse HTTPServerResponseImpl NameValueCollection TCPServer \
HTTPMessage HTTPServerSession NetException TCPServerConnection HTTPBufferAllocator \
HTTPRequest HTTPSession HTTPSessionInstantiator HTTPSessionFactory NetworkInterface TCPServerConnectionFactory \
HTTPRequestHandler HTTPStream HTTPIOStream ServerSocket TCPServerDispatcher \
HTTPRequestHandlerFactory HTTPStreamFactory ServerSocketImpl TCPServerParams \
QuotedPrintableEncoder QuotedPrintableDecoder StringPartSource \
FTPClientSession FTPStreamFactory PartHandler PartSource NullPartHandler \
SocketReactor SocketNotifier SocketNotification \
SocketReactor SocketNotifier SocketNotification AbstractHTTPRequestHandler \
MailRecipient MailMessage MailStream SMTPClientSession POP3ClientSession \
RawSocket RawSocketImpl ICMPClient ICMPEventArgs ICMPPacket ICMPPacketImpl \
ICMPSocket ICMPSocketImpl ICMPv4PacketImpl \
RemoteSyslogChannel
RemoteSyslogChannel RemoteSyslogListener
target = PocoNet
target_version = $(LIBVERSION)

View File

@@ -600,6 +600,9 @@
<Filter
Name="Header Files"
Filter="">
<File
RelativePath=".\include\Poco\Net\AbstractHTTPRequestHandler.h">
</File>
<File
RelativePath=".\include\Poco\Net\HTTPRequestHandler.h">
</File>
@@ -621,9 +624,15 @@
<File
RelativePath=".\include\Poco\Net\HTTPServerRequest.h">
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerRequestImpl.h">
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerResponse.h">
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerResponseImpl.h">
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerSession.h">
</File>
@@ -631,6 +640,9 @@
<Filter
Name="Source Files"
Filter="">
<File
RelativePath=".\src\AbstractHTTPRequestHandler.cpp">
</File>
<File
RelativePath=".\src\HTTPRequestHandler.cpp">
</File>
@@ -652,9 +664,15 @@
<File
RelativePath=".\src\HTTPServerRequest.cpp">
</File>
<File
RelativePath=".\src\HTTPServerRequestImpl.cpp">
</File>
<File
RelativePath=".\src\HTTPServerResponse.cpp">
</File>
<File
RelativePath=".\src\HTTPServerResponseImpl.cpp">
</File>
<File
RelativePath=".\src\HTTPServerSession.cpp">
</File>
@@ -885,6 +903,9 @@
<File
RelativePath=".\include\Poco\Net\RemoteSyslogChannel.h">
</File>
<File
RelativePath=".\include\Poco\Net\RemoteSyslogListener.h">
</File>
</Filter>
<Filter
Name="Source Files"
@@ -892,6 +913,9 @@
<File
RelativePath=".\src\RemoteSyslogChannel.cpp">
</File>
<File
RelativePath=".\src\RemoteSyslogListener.cpp">
</File>
</Filter>
</Filter>
</Files>

View File

@@ -805,6 +805,10 @@
<Filter
Name="Header Files"
>
<File
RelativePath=".\include\Poco\Net\AbstractHTTPRequestHandler.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\HTTPRequestHandler.h"
>
@@ -833,10 +837,18 @@
RelativePath=".\include\Poco\Net\HTTPServerRequest.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerRequestImpl.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerResponse.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerResponseImpl.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\HTTPServerSession.h"
>
@@ -845,6 +857,10 @@
<Filter
Name="Source Files"
>
<File
RelativePath=".\src\AbstractHTTPRequestHandler.cpp"
>
</File>
<File
RelativePath=".\src\HTTPRequestHandler.cpp"
>
@@ -873,10 +889,18 @@
RelativePath=".\src\HTTPServerRequest.cpp"
>
</File>
<File
RelativePath=".\src\HTTPServerRequestImpl.cpp"
>
</File>
<File
RelativePath=".\src\HTTPServerResponse.cpp"
>
</File>
<File
RelativePath=".\src\HTTPServerResponseImpl.cpp"
>
</File>
<File
RelativePath=".\src\HTTPServerSession.cpp"
>
@@ -1157,6 +1181,10 @@
RelativePath=".\include\Poco\Net\RemoteSyslogChannel.h"
>
</File>
<File
RelativePath=".\include\Poco\Net\RemoteSyslogListener.h"
>
</File>
</Filter>
<Filter
Name="Source Files"
@@ -1165,6 +1193,10 @@
RelativePath=".\src\RemoteSyslogChannel.cpp"
>
</File>
<File
RelativePath=".\src\RemoteSyslogListener.cpp"
>
</File>
</Filter>
</Filter>
</Files>

View File

@@ -0,0 +1,154 @@
//
// AbstractHTTPRequestHandler.h
//
// $Id: //poco/Main/Net/include/Poco/Net/AbstractHTTPRequestHandler.h#2 $
//
// Library: Net
// Package: HTTPServer
// Module: AbstractHTTPRequestHandler
//
// Definition of the AbstractHTTPRequestHandler class.
//
// Copyright (c) 2007, 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.
//
#ifndef Net_AbstractHTTPRequestHandler_INCLUDED
#define Net_AbstractHTTPRequestHandler_INCLUDED
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPResponse.h"
namespace Poco {
namespace Net {
class HTMLForm;
class Net_API AbstractHTTPRequestHandler: public HTTPRequestHandler
/// The abstract base class for AbstractHTTPRequestHandlers
/// created by HTTPServer.
///
/// Derived classes must override the run() method.
/// Contrary to a HTTPRequestHandler, an AbstractHTTPRequestHandler
/// stores request and response as member variables to avoid having
/// to pass them around as method parameters. Additionally, a
/// HTMLForm object is created for use by subclasses.
///
/// The run() method must perform the complete handling
/// of the HTTP request connection. As soon as the run()
/// method returns, the request handler object is destroyed.
///
/// A new AbstractHTTPRequestHandler object will be created for
/// each new HTTP request that is received by the HTTPServer.
{
public:
AbstractHTTPRequestHandler();
/// Creates the AbstractHTTPRequestHandler.
virtual ~AbstractHTTPRequestHandler();
/// Destroys the AbstractHTTPRequestHandler.
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response);
/// This class implements some common behavior,
/// before calling run() to actually handle the request:
/// - save request and response objects;
/// - call authorize();
/// - if authorize() returns true call run(),
/// else send 401 (Unauthorized) response.
HTTPServerRequest& request();
/// Returns the request.
HTTPServerResponse& response();
/// Returns the response.
HTMLForm& form();
/// Returns a HTMLForm for the given request.
/// The HTMLForm object is created when this
/// member function is executed the first time.
void sendErrorResponse(HTTPResponse::HTTPStatus status, const std::string& message);
/// Sends a HTML error page for the given status code.
/// The given message is added to the page:
/// <HTML>
/// <HEAD>
/// <TITLE>status - reason</TITLE>
/// </HEAD>
/// <BODY>
/// <H1>status - reason</H1>
/// <P>message</P>
/// </BODY>
/// </HTML>
protected:
virtual void run() = 0;
/// Must be overridden by subclasses.
///
/// Handles the given request.
virtual bool authenticate();
/// Check authentication; returns true if okay, false if failed to authenticate.
/// The default implementation always returns true.
///
/// Subclasses can override this member function to perform
/// some form of client or request authentication before
/// the request is actually handled.
private:
HTTPServerRequest* _pRequest;
HTTPServerResponse* _pResponse;
HTMLForm* _pForm;
};
//
// inlines
//
inline HTTPServerRequest& AbstractHTTPRequestHandler::request()
{
poco_check_ptr (_pRequest);
return *_pRequest;
}
inline HTTPServerResponse& AbstractHTTPRequestHandler::response()
{
poco_check_ptr (_pResponse);
return *_pResponse;
}
} } // namespace Poco::Net
#endif // Net_AbstractHTTPRequestHandler_INCLUDED

View File

@@ -1,7 +1,7 @@
//
// FilePartSource.h
//
// $Id: //poco/Main/Net/include/Poco/Net/FilePartSource.h#2 $
// $Id: //poco/Main/Net/include/Poco/Net/FilePartSource.h#3 $
//
// Library: Net
// Package: Messages
@@ -42,7 +42,7 @@
#include "Poco/Net/Net.h"
#include "Poco/Net/PartSource.h"
#include <fstream>
#include "Poco/FileStream.h"
namespace Poco {
@@ -77,8 +77,8 @@ public:
/// Returns the filename portion of the path.
private:
std::ifstream _istr;
std::string _filename;
Poco::FileInputStream _istr;
};

View File

@@ -1,7 +1,7 @@
//
// HTTPClientSession.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPClientSession.h#3 $
// $Id: //poco/Main/Net/include/Poco/Net/HTTPClientSession.h#5 $
//
// Library: Net
// Package: HTTPClient
@@ -130,6 +130,12 @@ public:
Poco::UInt16 getProxyPort() const;
/// Returns the proxy port number.
void setKeepAliveTimeout(const Poco::Timespan& timeout);
/// Sets the connection timeout for HTTP connections.
const Poco::Timespan& getKeepAliveTimeout() const;
/// Returns the connection timeout for HTTP connections.
virtual std::ostream& sendRequest(HTTPRequest& request);
/// Sends the header for the given HTTP request to
/// the server.
@@ -152,6 +158,11 @@ public:
/// destroyed.
protected:
enum
{
DEFAULT_KEEP_ALIVE_TIMEOUT = 8
};
void reconnect();
/// Connects the underlying socket to the HTTP server.
@@ -188,11 +199,16 @@ protected:
bool getExpectResponseBody() const;
/// Returns _expectResponseBody.
bool mustReconnect() const;
/// Checks if we can reuse a persistent connection.
private:
std::string _host;
Poco::UInt16 _port;
std::string _proxyHost;
Poco::UInt16 _proxyPort;
Poco::Timespan _keepAliveTimeout;
Poco::Timestamp _lastRequest;
bool _reconnect;
bool _mustReconnect;
bool _expectResponseBody;
@@ -258,6 +274,12 @@ inline bool HTTPClientSession::getExpectResponseBody() const
}
inline const Poco::Timespan& HTTPClientSession::getKeepAliveTimeout() const
{
return _keepAliveTimeout;
}
} } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
//
// HTTPRequestHandlerFactory.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPRequestHandlerFactory.h#2 $
// $Id: //poco/Main/Net/include/Poco/Net/HTTPRequestHandlerFactory.h#3 $
//
// Library: Net
// Package: HTTPServer
@@ -48,12 +48,13 @@ namespace Net {
class HTTPServerRequest;
class HTTPServerResponse;
class HTTPRequestHandler;
class Net_API HTTPRequestHandlerFactory
/// A factory for HTTPRequestHandler objects.
/// Subclasses must override the createRequstHandler()
/// Subclasses must override the createRequestHandler()
/// method.
{
public:

View File

@@ -1,7 +1,7 @@
//
// HTTPServerRequest.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerRequest.h#2 $
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerRequest.h#5 $
//
// Library: Net
// Package: HTTPServer
@@ -51,81 +51,49 @@ namespace Net {
class HTTPServerSession;
class HTTPServerResponse;
class HTTPServerParams;
class Net_API HTTPServerRequest: public HTTPRequest
/// This subclass of HTTPRequest is used for
/// This abstract HTTPServerRequest of HTTPRequest is used for
/// representing server-side HTTP requests.
///
/// A HTTPServerRequest is passed to the
/// handleRequest() method of HTTPRequestHandler.
{
public:
HTTPServerRequest(HTTPServerSession& session, HTTPServerParams* pParams);
/// Creates the HTTPServerRequest, using the
/// given HTTPServerSession.
HTTPServerRequest();
/// Creates the HTTPServerRequest
~HTTPServerRequest();
/// Destroys the HTTPServerRequest.
std::istream& stream();
virtual std::istream& stream() = 0;
/// Returns the input stream for reading
/// the request body.
///
/// The stream is valid until the HTTPServerRequest
/// The stream must be valid until the HTTPServerRequest
/// object is destroyed.
bool expectContinue() const;
virtual bool expectContinue() const = 0;
/// Returns true if the client expects a
/// 100 Continue response.
const SocketAddress& clientAddress() const;
virtual const SocketAddress& clientAddress() const = 0;
/// Returns the client's address.
const SocketAddress& serverAddress() const;
virtual const SocketAddress& serverAddress() const = 0;
/// Returns the server's address.
const HTTPServerParams& serverParams() const;
virtual const HTTPServerParams& serverParams() const = 0;
/// Returns a reference to the server parameters.
private:
std::istream* _pStream;
HTTPServerParams* _pParams;
SocketAddress _clientAddress;
SocketAddress _serverAddress;
virtual HTTPServerResponse& response() const = 0;
/// Returns a reference to the associated response.
};
//
// inlines
//
inline std::istream& HTTPServerRequest::stream()
{
poco_check_ptr (_pStream);
return *_pStream;
}
inline const SocketAddress& HTTPServerRequest::clientAddress() const
{
return _clientAddress;
}
inline const SocketAddress& HTTPServerRequest::serverAddress() const
{
return _serverAddress;
}
inline const HTTPServerParams& HTTPServerRequest::serverParams() const
{
return *_pParams;
}
} } // namespace Poco::Net

View File

@@ -0,0 +1,142 @@
//
// HTTPServerRequestImpl.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerRequestImpl.h#3 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerRequestImpl
//
// Definition of the HTTPServerRequestImpl class.
//
// 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.
//
#ifndef Net_HTTPServerRequestImpl_INCLUDED
#define Net_HTTPServerRequestImpl_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/SocketAddress.h"
#include <istream>
namespace Poco {
namespace Net {
class HTTPServerSession;
class HTTPServerParams;
class Net_API HTTPServerRequestImpl: public HTTPServerRequest
/// This subclass of HTTPServerRequest is used for
/// representing server-side HTTP requests.
///
/// A HTTPServerRequest is passed to the
/// handleRequest() method of HTTPRequestHandler.
{
public:
HTTPServerRequestImpl(HTTPServerResponse& response, HTTPServerSession& session, HTTPServerParams* pParams);
/// Creates the HTTPServerRequestImpl, using the
/// given HTTPServerSession.
~HTTPServerRequestImpl();
/// Destroys the HTTPServerRequestImpl.
std::istream& stream();
/// Returns the input stream for reading
/// the request body.
///
/// The stream is valid until the HTTPServerRequestImpl
/// object is destroyed.
bool expectContinue() const;
/// Returns true if the client expects a
/// 100 Continue response.
const SocketAddress& clientAddress() const;
/// Returns the client's address.
const SocketAddress& serverAddress() const;
/// Returns the server's address.
const HTTPServerParams& serverParams() const;
/// Returns a reference to the server parameters.
HTTPServerResponse& response() const;
/// Returns a reference to the associated response.
private:
HTTPServerResponse& _response;
std::istream* _pStream;
HTTPServerParams* _pParams;
SocketAddress _clientAddress;
SocketAddress _serverAddress;
};
//
// inlines
//
inline std::istream& HTTPServerRequestImpl::stream()
{
poco_check_ptr (_pStream);
return *_pStream;
}
inline const SocketAddress& HTTPServerRequestImpl::clientAddress() const
{
return _clientAddress;
}
inline const SocketAddress& HTTPServerRequestImpl::serverAddress() const
{
return _serverAddress;
}
inline const HTTPServerParams& HTTPServerRequestImpl::serverParams() const
{
return *_pParams;
}
inline HTTPServerResponse& HTTPServerRequestImpl::response() const
{
return _response;
}
} } // namespace Poco::Net
#endif // Net_HTTPServerRequestImpl_INCLUDED

View File

@@ -1,7 +1,7 @@
//
// HTTPServerResponse.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerResponse.h#3 $
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerResponse.h#5 $
//
// Library: Net
// Package: HTTPServer
@@ -65,17 +65,17 @@ class Net_API HTTPServerResponse: public HTTPResponse
/// as necessary, and provide a message body.
{
public:
HTTPServerResponse(HTTPServerSession& session);
HTTPServerResponse();
/// Creates the HTTPServerResponse.
~HTTPServerResponse();
/// Destroys the HTTPServerResponse.
void sendContinue();
virtual void sendContinue() = 0;
/// Sends a 100 Continue response to the
/// client.
std::ostream& send();
virtual std::ostream& send() = 0;
/// Sends the response header to the client and
/// returns an output stream for sending the
/// response body.
@@ -86,7 +86,7 @@ public:
/// Must not be called after sendFile(), sendBuffer()
/// or redirect() has been called.
void sendFile(const std::string& path, const std::string& mediaType);
virtual void sendFile(const std::string& path, const std::string& mediaType) = 0;
/// Sends the response header to the client, followed
/// by the content of the given file.
///
@@ -97,7 +97,7 @@ public:
/// cannot be found, or an OpenFileException if
/// the file cannot be opened.
void sendBuffer(const void* pBuffer, std::size_t length);
virtual void sendBuffer(const void* pBuffer, std::size_t length) = 0;
/// Sends the response header to the client, followed
/// by the contents of the given buffer.
///
@@ -111,7 +111,7 @@ public:
/// Must not be called after send(), sendFile()
/// or redirect() has been called.
void redirect(const std::string& uri);
virtual void redirect(const std::string& uri) = 0;
/// Sets the status code to 302 (Found)
/// and sets the "Location" header field
/// to the given URI, which according to
@@ -119,29 +119,16 @@ public:
///
/// Must not be called after send() has been called.
void requireAuthentication(const std::string& realm);
virtual void requireAuthentication(const std::string& realm) = 0;
/// Sets the status code to 401 (Unauthorized)
/// and sets the "WWW-Authenticate" header field
/// according to the given realm.
bool sent() const;
virtual bool sent() const = 0;
/// Returns true if the response (header) has been sent.
private:
HTTPServerSession& _session;
std::ostream* _pStream;
};
//
// inlines
//
inline bool HTTPServerResponse::sent() const
{
return _pStream != 0;
}
} } // namespace Poco::Net

View File

@@ -0,0 +1,148 @@
//
// HTTPServerResponseImpl.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPServerResponseImpl.h#2 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerResponseImpl
//
// Definition of the HTTPServerResponseImpl class.
//
// 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.
//
#ifndef Net_HTTPServerResponseImpl_INCLUDED
#define Net_HTTPServerResponseImpl_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Net/HTTPServerResponse.h"
#include <ostream>
namespace Poco {
namespace Net {
class HTTPServerSession;
class HTTPCookie;
class Net_API HTTPServerResponseImpl: public HTTPServerResponse
/// This subclass of HTTPServerResponse is used for
/// representing server-side HTTP responses.
///
/// A HTTPServerResponse is passed to the
/// handleRequest() method of HTTPRequestHandler.
///
/// handleRequest() must set a status code
/// and optional reason phrase, set headers
/// as necessary, and provide a message body.
{
public:
HTTPServerResponseImpl(HTTPServerSession& session);
/// Creates the HTTPServerResponseImpl.
~HTTPServerResponseImpl();
/// Destroys the HTTPServerResponseImpl.
void sendContinue();
/// Sends a 100 Continue response to the
/// client.
std::ostream& send();
/// Sends the response header to the client and
/// returns an output stream for sending the
/// response body.
///
/// The returned stream is valid until the response
/// object is destroyed.
///
/// Must not be called after sendFile(), sendBuffer()
/// or redirect() has been called.
void sendFile(const std::string& path, const std::string& mediaType);
/// Sends the response header to the client, followed
/// by the content of the given file.
///
/// Must not be called after send(), sendBuffer()
/// or redirect() has been called.
///
/// Throws a FileNotFoundException if the file
/// cannot be found, or an OpenFileException if
/// the file cannot be opened.
void sendBuffer(const void* pBuffer, std::size_t length);
/// Sends the response header to the client, followed
/// by the contents of the given buffer.
///
/// The Content-Length header of the response is set
/// to length and chunked transfer encoding is disabled.
///
/// If both the HTTP message header and body (from the
/// given buffer) fit into one single network packet, the
/// complete response can be sent in one network packet.
///
/// Must not be called after send(), sendFile()
/// or redirect() has been called.
void redirect(const std::string& uri);
/// Sets the status code to 302 (Found)
/// and sets the "Location" header field
/// to the given URI, which according to
/// the HTTP specification, must be absolute.
///
/// Must not be called after send() has been called.
void requireAuthentication(const std::string& realm);
/// Sets the status code to 401 (Unauthorized)
/// and sets the "WWW-Authenticate" header field
/// according to the given realm.
bool sent() const;
/// Returns true if the response (header) has been sent.
private:
HTTPServerSession& _session;
std::ostream* _pStream;
};
//
// inlines
//
inline bool HTTPServerResponseImpl::sent() const
{
return _pStream != 0;
}
} } // namespace Poco::Net
#endif // Net_HTTPServerResponseImpl_INCLUDED

View File

@@ -1,7 +1,7 @@
//
// HTTPSession.h
//
// $Id: //poco/Main/Net/include/Poco/Net/HTTPSession.h#2 $
// $Id: //poco/Main/Net/include/Poco/Net/HTTPSession.h#4 $
//
// Library: Net
// Package: HTTP

View File

@@ -1,7 +1,7 @@
//
// RemoteSyslogChannel.h
//
// $Id: //poco/Main/Net/include/Poco/Net/RemoteSyslogChannel.h#2 $
// $Id: //poco/Main/Net/include/Poco/Net/RemoteSyslogChannel.h#4 $
//
// Library: Net
// Package: Logging
@@ -59,6 +59,9 @@ class Net_API RemoteSyslogChannel: public Poco::Channel
/// protocol, as described in RFC 3164.
{
public:
static const std::string BSD_TIMEFORMAT;
static const std::string SYSLOG_TIMEFORMAT;
enum Severity
{
SYSLOG_EMERGENCY = 0, /// Emergency: system is unusable
@@ -118,7 +121,7 @@ public:
/// Closes the RemoteSyslogChannel.
void log(const Message& msg);
/// Sens the message's text to the syslog service.
/// Sends the message's text to the syslog service.
void setProperty(const std::string& name, const std::string& value);
/// Sets the property with the given value.

View File

@@ -0,0 +1,114 @@
//
// RemoteSyslogListener.h
//
// $Id: //poco/Main/Net/include/Poco/Net/RemoteSyslogListener.h#4 $
//
// Library: Net
// Package: Logging
// Module: RemoteSyslogListener
//
// Definition of the RemoteSyslogListener class.
//
// Copyright (c) 2007, 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.
//
#ifndef Net_RemoteSyslogListener_INCLUDED
#define Net_RemoteSyslogListener_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Thread.h"
#include "Poco/SplitterChannel.h"
#include "Poco/NotificationQueue.h"
namespace Poco {
namespace Net {
class RemoteUDPListener;
class SyslogParser;
class Net_API RemoteSyslogListener: public Poco::SplitterChannel
/// RemoteSyslogListener implents listening for syslog messages
/// sent over UDP, according to the syslog Working Group Internet Draft:
/// "The syslog Protocol" <http://www.ietf.org/internet-drafts/draft-ietf-syslog-protocol-17.txt>,
/// and "Transmission of syslog messages over UDP" <http://www.ietf.org/internet-drafts/draft-ietf-syslog-transport-udp-07.txt>.
///
/// In addition, RemoteSyslogListener also supports the "old" BSD syslog
/// protocol, as described in RFC 3164.
///
/// The RemoteSyslogListener is a subclass of Poco::SplitterChannel.
/// Every received log message is sent to the channels registered
/// with addChannel() or the "channel" property.
{
public:
RemoteSyslogListener();
/// Creates the RemoteSyslogListener.
RemoteSyslogListener(Poco::UInt16 port);
/// Creates the RemoteSyslogListener.
void setProperty(const std::string& name, const std::string& value);
/// Sets the property with the given value.
///
/// The following properties are supported:
/// * port: The UDP port number where to listen for UDP.
std::string getProperty(const std::string& name) const;
/// Returns the value of the property with the given name.
void open();
/// Starts the listener.
void close();
/// Stops the listener.
static void registerChannel();
/// Registers the channel with the global LoggingFactory.
static const std::string PROP_PORT;
protected:
~RemoteSyslogListener();
/// Destroys the RemoteSyslogListener.
private:
RemoteUDPListener* _pListener;
SyslogParser* _pParser;
Poco::Thread _listener;
Poco::Thread _parser;
Poco::NotificationQueue _queue;
Poco::UInt16 _port;
};
} } // namespace Poco::Net
#endif // Net_RemoteSyslogListener_INCLUDED

View File

@@ -0,0 +1,113 @@
//
// AbstractHTTPRequestHandler.cpp
//
// $Id: //poco/Main/Net/src/AbstractHTTPRequestHandler.cpp#3 $
//
// Library: Net
// Package: HTTPServer
// Module: AbstractHTTPRequestHandler
//
// Copyright (c) 2007, 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/AbstractHTTPRequestHandler.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTMLForm.h"
#include "Poco/NumberFormatter.h"
using Poco::NumberFormatter;
namespace Poco {
namespace Net {
AbstractHTTPRequestHandler::AbstractHTTPRequestHandler():
_pRequest(0),
_pResponse(0),
_pForm(0)
{
}
AbstractHTTPRequestHandler::~AbstractHTTPRequestHandler()
{
delete _pForm;
}
void AbstractHTTPRequestHandler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
_pRequest = &request;
_pResponse = &response;
if (authenticate())
{
run();
}
else
{
sendErrorResponse(HTTPResponse::HTTP_UNAUTHORIZED, "");
}
}
bool AbstractHTTPRequestHandler::authenticate()
{
return true;
}
HTMLForm& AbstractHTTPRequestHandler::form()
{
if (!_pForm)
_pForm = new HTMLForm(request(), request().stream());
return *_pForm;
}
void AbstractHTTPRequestHandler::sendErrorResponse(HTTPResponse::HTTPStatus status, const std::string& message)
{
response().setStatusAndReason(status);
std::string statusAndReason(NumberFormatter::format(static_cast<int>(response().getStatus())));
statusAndReason += " - ";
statusAndReason += response().getReason();
std::string page("<HTML><HEAD><TITLE>");
page += statusAndReason;
page += "</TITLE></HEAD><BODY><H1>";
page += statusAndReason;
page += "</H1>";
page += "<P>";
page += message;
page += "</P></BODY></HTML>";
response().sendBuffer(page.data(), page.size());
}
} } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
//
// FilePartSource.cpp
//
// $Id: //poco/Main/Net/src/FilePartSource.cpp#7 $
// $Id: //poco/Main/Net/src/FilePartSource.cpp#8 $
//
// Library: Net
// Package: Messages
@@ -48,7 +48,7 @@ namespace Net {
FilePartSource::FilePartSource(const std::string& path):
_istr(path.c_str(), std::ios::in | std::ios::binary)
_istr(path)
{
Path p(path);
_filename = p.getFileName();
@@ -59,7 +59,7 @@ FilePartSource::FilePartSource(const std::string& path):
FilePartSource::FilePartSource(const std::string& path, const std::string& mediaType):
PartSource(mediaType),
_istr(path.c_str(), std::ios::in | std::ios::binary)
_istr(path)
{
Path p(path);
_filename = p.getFileName();

View File

@@ -1,7 +1,7 @@
//
// HTTPClientSession.cpp
//
// $Id: //poco/Main/Net/src/HTTPClientSession.cpp#16 $
// $Id: //poco/Main/Net/src/HTTPClientSession.cpp#18 $
//
// Library: Net
// Package: HTTPClient
@@ -57,6 +57,7 @@ namespace Net {
HTTPClientSession::HTTPClientSession():
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
_reconnect(false),
_mustReconnect(false),
_expectResponseBody(false),
@@ -70,6 +71,7 @@ HTTPClientSession::HTTPClientSession(const StreamSocket& socket):
HTTPSession(socket),
_port(HTTPSession::HTTP_PORT),
_proxyPort(HTTPSession::HTTP_PORT),
_keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
_reconnect(false),
_mustReconnect(false),
_expectResponseBody(false),
@@ -83,6 +85,7 @@ HTTPClientSession::HTTPClientSession(const SocketAddress& address):
_host(address.host().toString()),
_port(address.port()),
_proxyPort(HTTPSession::HTTP_PORT),
_keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
_reconnect(false),
_mustReconnect(false),
_expectResponseBody(false),
@@ -96,6 +99,7 @@ HTTPClientSession::HTTPClientSession(const std::string& host, Poco::UInt16 port)
_host(host),
_port(port),
_proxyPort(HTTPSession::HTTP_PORT),
_keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
_reconnect(false),
_mustReconnect(false),
_expectResponseBody(false),
@@ -159,13 +163,19 @@ void HTTPClientSession::setProxyPort(Poco::UInt16 port)
}
void HTTPClientSession::setKeepAliveTimeout(const Poco::Timespan& timeout)
{
_keepAliveTimeout = timeout;
}
std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
{
delete _pResponseStream;
_pResponseStream = 0;
bool keepAlive = getKeepAlive();
if (connected() && !keepAlive || _mustReconnect)
if (connected() && !keepAlive || mustReconnect())
{
close();
_mustReconnect = false;
@@ -204,6 +214,7 @@ std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
_pRequestStream = new HTTPOutputStream(*this);
request.write(*_pRequestStream);
}
_lastRequest.update();
return *_pRequestStream;
}
@@ -250,7 +261,9 @@ int HTTPClientSession::write(const char* buffer, std::streamsize length)
{
try
{
return HTTPSession::write(buffer, length);
int rc = HTTPSession::write(buffer, length);
_reconnect = false;
return rc;
}
catch (NetException&)
{
@@ -258,11 +271,12 @@ int HTTPClientSession::write(const char* buffer, std::streamsize length)
{
close();
reconnect();
return HTTPSession::write(buffer, length);
int rc = HTTPSession::write(buffer, length);
_reconnect = false;
return rc;
}
else throw;
}
_reconnect = false;
}
@@ -319,4 +333,15 @@ void HTTPClientSession::setRequestStream(std::ostream* pRequestStream)
}
bool HTTPClientSession::mustReconnect() const
{
if (!_mustReconnect)
{
Poco::Timestamp now;
return _keepAliveTimeout <= now - _lastRequest;
}
else return true;
}
} } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
//
// HTTPServerConnection.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerConnection.cpp#9 $
// $Id: //poco/Main/Net/src/HTTPServerConnection.cpp#10 $
//
// Library: Net
// Package: HTTPServer
@@ -36,8 +36,8 @@
#include "Poco/Net/HTTPServerConnection.h"
#include "Poco/Net/HTTPServerSession.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerRequestImpl.h"
#include "Poco/Net/HTTPServerResponseImpl.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
@@ -76,8 +76,9 @@ void HTTPServerConnection::run()
{
try
{
HTTPServerRequest request(session, _pParams);
HTTPServerResponse response(session);
HTTPServerResponseImpl response(session);
HTTPServerRequestImpl request(response, session, _pParams);
response.setVersion(request.getVersion());
response.setKeepAlive(_pParams->getKeepAlive() && request.getKeepAlive() && session.canKeepAlive());
if (!server.empty())
@@ -116,7 +117,7 @@ void HTTPServerConnection::run()
void HTTPServerConnection::sendErrorResponse(HTTPServerSession& session, HTTPResponse::HTTPStatus status)
{
HTTPServerResponse response(session);
HTTPServerResponseImpl response(session);
response.setVersion(HTTPMessage::HTTP_1_1);
response.setStatusAndReason(status);
response.setKeepAlive(false);

View File

@@ -1,7 +1,7 @@
//
// HTTPServerRequest.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerRequest.cpp#6 $
// $Id: //poco/Main/Net/src/HTTPServerRequest.cpp#8 $
//
// Library: Net
// Package: HTTPServer
@@ -35,56 +35,19 @@
#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())
HTTPServerRequest::HTTPServerRequest()
{
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;
}

View File

@@ -0,0 +1,92 @@
//
// HTTPServerRequestImpl.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerRequestImpl.cpp#2 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerRequestImpl
//
// 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/HTTPServerRequestImpl.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 {
HTTPServerRequestImpl::HTTPServerRequestImpl(HTTPServerResponse& response, HTTPServerSession& session, HTTPServerParams* pParams):
_response(response),
_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);
}
HTTPServerRequestImpl::~HTTPServerRequestImpl()
{
_pParams->release();
delete _pStream;
}
bool HTTPServerRequestImpl::expectContinue() const
{
return has("Expect") && icompare(get("Expect"), "100-continue") == 0;
}
} } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
//
// HTTPServerResponse.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerResponse.cpp#10 $
// $Id: //poco/Main/Net/src/HTTPServerResponse.cpp#12 $
//
// Library: Net
// Package: HTTPServer
@@ -35,135 +35,19 @@
#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/CountingStream.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()
{
}
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())
{
HTTPHeaderOutputStream hs(_session);
write(hs);
_pStream = new HTTPChunkedOutputStream(_session);
}
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
{
Poco::CountingOutputStream cs;
write(cs);
_pStream = new HTTPFixedLengthOutputStream(_session, getContentLength() + cs.chars());
write(*_pStream);
}
else
{
_pStream = new HTTPOutputStream(_session);
setKeepAlive(false);
write(*_pStream);
}
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(static_cast<int>(length));
setContentType(mediaType);
setChunkedTransferEncoding(false);
std::ifstream istr(path.c_str(), std::ios::binary | std::ios::in);
if (istr.good())
{
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
StreamCopier::copyStream(istr, *_pStream);
}
else throw OpenFileException(path);
}
void HTTPServerResponse::sendBuffer(const void* pBuffer, std::size_t length)
{
poco_assert (!_pStream);
setContentLength(static_cast<int>(length));
setChunkedTransferEncoding(false);
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
_pStream->write(static_cast<const char*>(pBuffer), static_cast<std::streamsize>(length));
}
void HTTPServerResponse::redirect(const std::string& uri)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_FOUND);
set("Location", uri);
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
}
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);
}

View File

@@ -0,0 +1,170 @@
//
// HTTPServerResponseImpl.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerResponseImpl.cpp#3 $
//
// Library: Net
// Package: HTTPServer
// Module: HTTPServerResponseImpl
//
// 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/HTTPServerResponseImpl.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/CountingStream.h"
#include "Poco/Exception.h"
#include "Poco/FileStream.h"
using Poco::File;
using Poco::Timestamp;
using Poco::NumberFormatter;
using Poco::StreamCopier;
using Poco::OpenFileException;
namespace Poco {
namespace Net {
HTTPServerResponseImpl::HTTPServerResponseImpl(HTTPServerSession& session):
_session(session),
_pStream(0)
{
}
HTTPServerResponseImpl::~HTTPServerResponseImpl()
{
delete _pStream;
}
void HTTPServerResponseImpl::sendContinue()
{
HTTPHeaderOutputStream hs(_session);
hs << getVersion() << " 100 Continue\r\n\r\n";
}
std::ostream& HTTPServerResponseImpl::send()
{
poco_assert (!_pStream);
if (getChunkedTransferEncoding())
{
HTTPHeaderOutputStream hs(_session);
write(hs);
_pStream = new HTTPChunkedOutputStream(_session);
}
else if (getContentLength() != HTTPMessage::UNKNOWN_CONTENT_LENGTH)
{
Poco::CountingOutputStream cs;
write(cs);
_pStream = new HTTPFixedLengthOutputStream(_session, getContentLength() + cs.chars());
write(*_pStream);
}
else
{
_pStream = new HTTPOutputStream(_session);
setKeepAlive(false);
write(*_pStream);
}
return *_pStream;
}
void HTTPServerResponseImpl::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(static_cast<int>(length));
setContentType(mediaType);
setChunkedTransferEncoding(false);
Poco::FileInputStream istr(path);
if (istr.good())
{
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
StreamCopier::copyStream(istr, *_pStream);
}
else throw OpenFileException(path);
}
void HTTPServerResponseImpl::sendBuffer(const void* pBuffer, std::size_t length)
{
poco_assert (!_pStream);
setContentLength(static_cast<int>(length));
setChunkedTransferEncoding(false);
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
_pStream->write(static_cast<const char*>(pBuffer), static_cast<std::streamsize>(length));
}
void HTTPServerResponseImpl::redirect(const std::string& uri)
{
poco_assert (!_pStream);
setStatusAndReason(HTTPResponse::HTTP_FOUND);
set("Location", uri);
_pStream = new HTTPOutputStream(_session);
write(*_pStream);
}
void HTTPServerResponseImpl::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,7 +1,7 @@
//
// HTTPServerSession.cpp
//
// $Id: //poco/Main/Net/src/HTTPServerSession.cpp#7 $
// $Id: //poco/Main/Net/src/HTTPServerSession.cpp#8 $
//
// Library: Net
// Package: HTTPServer
@@ -48,6 +48,8 @@ HTTPServerSession::HTTPServerSession(const StreamSocket& socket, HTTPServerParam
_keepAliveTimeout(pParams->getKeepAliveTimeout()),
_maxKeepAliveRequests(pParams->getMaxKeepAliveRequests())
{
setTimeout(pParams->getTimeout());
this->socket().setReceiveTimeout(pParams->getTimeout());
}

View File

@@ -1,7 +1,7 @@
//
// HTTPSession.cpp
//
// $Id: //poco/Main/Net/src/HTTPSession.cpp#10 $
// $Id: //poco/Main/Net/src/HTTPSession.cpp#12 $
//
// Library: Net
// Package: HTTP
@@ -158,10 +158,7 @@ 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)
{
@@ -192,6 +189,7 @@ bool HTTPSession::connected() const
void HTTPSession::connect(const SocketAddress& address)
{
_socket.connect(address, _timeout);
_socket.setReceiveTimeout(_timeout);
_socket.setNoDelay(true);
}

View File

@@ -1,7 +1,7 @@
//
// RemoteSyslogChannel.cpp
//
// $Id: //poco/Main/Net/src/RemoteSyslogChannel.cpp#2 $
// $Id: //poco/Main/Net/src/RemoteSyslogChannel.cpp#3 $
//
// Library: Net
// Package: Logging
@@ -49,6 +49,8 @@ namespace Poco {
namespace Net {
const std::string RemoteSyslogChannel::BSD_TIMEFORMAT("%b %f %H:%M:%S");
const std::string RemoteSyslogChannel::SYSLOG_TIMEFORMAT("%Y-%m-%dT%H:%M:%S.%i%z");
const std::string RemoteSyslogChannel::PROP_NAME("name");
const std::string RemoteSyslogChannel::PROP_FACILITY("facility");
const std::string RemoteSyslogChannel::PROP_FORMAT("format");
@@ -129,14 +131,14 @@ void RemoteSyslogChannel::log(const Message& msg)
m += '>';
if (_bsdFormat)
{
m += Poco::DateTimeFormatter::format(msg.getTime(), "%w %f %H:%M:%S");
m += Poco::DateTimeFormatter::format(msg.getTime(), BSD_TIMEFORMAT);
m += ' ';
m += _host;
}
else
{
m += "1 "; // version
m += Poco::DateTimeFormatter::format(msg.getTime(), "%Y-%m-%dT%H:%M:%S.%i%z");
m += Poco::DateTimeFormatter::format(msg.getTime(), SYSLOG_TIMEFORMAT);
m += ' ';
m += _host;
m += ' ';

View File

@@ -0,0 +1,524 @@
//
// RemoteSyslogListener.cpp
//
// $Id: //poco/Main/Net/src/RemoteSyslogListener.cpp#6 $
//
// Library: Net
// Package: Logging
// Module: RemoteSyslogListener
//
// Copyright (c) 2007, 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/RemoteSyslogListener.h"
#include "Poco/Net/RemoteSyslogChannel.h"
#include "Poco/Net/DatagramSocket.h"
#include "Poco/Runnable.h"
#include "Poco/Notification.h"
#include "Poco/AutoPtr.h"
#include "Poco/NumberParser.h"
#include "Poco/NumberFormatter.h"
#include "Poco/DateTimeParser.h"
#include "Poco/Message.h"
#include "Poco/LoggingFactory.h"
#include "Poco/Buffer.h"
#include <cctype>
namespace Poco {
namespace Net {
//
// MessageNotification
//
class MessageNotification: public Poco::Notification
{
public:
MessageNotification(const std::string& msg)
{
_msg = msg;
}
~MessageNotification()
{
}
const std::string& message() const
{
return _msg;
}
private:
std::string _msg;
};
//
// RemoteUDPListener
//
class RemoteUDPListener: public Poco::Runnable
{
public:
enum
{
WAITTIME_MILLISEC = 1000,
BUFFER_SIZE = 65536
};
RemoteUDPListener(Poco::NotificationQueue& queue, Poco::UInt16 port);
~RemoteUDPListener();
void run();
void safeStop();
private:
Poco::NotificationQueue& _queue;
DatagramSocket _socket;
bool _stopped;
};
RemoteUDPListener::RemoteUDPListener(Poco::NotificationQueue& queue, Poco::UInt16 port):
_queue(queue),
_socket(Poco::Net::SocketAddress(Poco::Net::IPAddress(), port)),
_stopped(true)
{
}
RemoteUDPListener::~RemoteUDPListener()
{
}
void RemoteUDPListener::run()
{
poco_assert (_stopped);
Poco::Buffer<char> buffer(BUFFER_SIZE);
_stopped = false;
Poco::Timespan waitTime(WAITTIME_MILLISEC* 1000);
while (!_stopped)
{
try
{
if (_socket.poll(waitTime, Socket::SELECT_READ))
{
int byteCnt = _socket.receiveBytes(buffer.begin(), BUFFER_SIZE);
if (byteCnt > 0)
{
_queue.enqueueNotification(new MessageNotification(std::string(buffer.begin(), byteCnt)));
}
}
}
catch (...)
{
// lazy exception catching
}
}
}
void RemoteUDPListener::safeStop()
{
_stopped = true;
}
//
// SyslogParser
//
class SyslogParser: public Poco::Runnable
{
public:
static const std::string NILVALUE;
enum
{
WAITTIME_MILLISEC = 1000
};
SyslogParser(Poco::NotificationQueue& queue, RemoteSyslogListener* pListener);
~SyslogParser();
void run();
void safeStop();
static Poco::Message::Priority convert(RemoteSyslogChannel::Severity severity);
private:
void parse(const std::string& msg);
void parsePrio(const std::string& msg, std::size_t& pos, RemoteSyslogChannel::Severity& severity, RemoteSyslogChannel::Facility& fac);
void parseNew(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos);
void parseBSD(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos);
static std::string parseUntilSpace(const std::string& msg, std::size_t& pos);
/// Parses until it encounters the next space char, returns the string from pos, excluding space
/// pos will point past the space char
private:
Poco::NotificationQueue& _queue;
bool _stopped;
RemoteSyslogListener* _pListener;
};
const std::string SyslogParser::NILVALUE("-");
SyslogParser::SyslogParser(Poco::NotificationQueue& queue, RemoteSyslogListener* pListener):
_queue(queue),
_stopped(true),
_pListener(pListener)
{
poco_check_ptr (_pListener);
}
SyslogParser::~SyslogParser()
{
}
void SyslogParser::run()
{
poco_assert (_stopped);
_stopped = false;
while (!_stopped)
{
try
{
Poco::AutoPtr<Poco::Notification> pNf(_queue.waitDequeueNotification(WAITTIME_MILLISEC));
if (pNf)
{
Poco::AutoPtr<MessageNotification> pMsgNf = pNf.cast<MessageNotification>();
parse(pMsgNf->message());
}
}
catch (Poco::Exception&)
{
// parsing exception, what should we do?
}
catch (...)
{
}
}
}
void SyslogParser::safeStop()
{
_stopped = true;
}
void SyslogParser::parse(const std::string& msg)
{
// <int> -> int: lower 3 bits severity, upper bits: facility
std::size_t pos = 0;
RemoteSyslogChannel::Severity severity;
RemoteSyslogChannel::Facility fac;
parsePrio(msg, pos, severity, fac);
// the next field decide if we parse an old BSD message or a new syslog message
// BSD: expects a month value in string form: Jan, Feb...
// SYSLOG expects a version number: 1
if (std::isdigit(msg[pos]))
{
parseNew(msg, severity, fac, pos);
}
else
{
parseBSD(msg, severity, fac, pos);
}
poco_assert (pos == msg.size());
}
void SyslogParser::parsePrio(const std::string& msg, std::size_t& pos, RemoteSyslogChannel::Severity& severity, RemoteSyslogChannel::Facility& fac)
{
poco_assert (pos < msg.size());
poco_assert (msg[pos] == '<');
++pos;
std::size_t start = pos;
while (pos < msg.size() && std::isdigit(msg[pos]))
++pos;
poco_assert (msg[pos] == '>');
poco_assert (pos - start > 0);
std::string valStr = msg.substr(start, pos - start);
++pos; // skip the >
int val = Poco::NumberParser::parse(valStr);
poco_assert (val >= 0 && val <= (RemoteSyslogChannel::SYSLOG_LOCAL7 + RemoteSyslogChannel::SYSLOG_DEBUG));
Poco::UInt16 pri = static_cast<Poco::UInt16>(val);
// now get the lowest 3 bits
severity = static_cast<RemoteSyslogChannel::Severity>(pri & 0x0007u);
fac = static_cast<RemoteSyslogChannel::Facility>(pri & 0xfff8u);
}
void SyslogParser::parseNew(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos)
{
Poco::Message::Priority prio = convert(severity);
// rest of the unparsed header is:
// VERSION SP TIMESTAMP SP HOSTNAME SP APP-NAME SP PROCID SP MSGID
std::string versionStr(parseUntilSpace(msg, pos));
std::string timeStr(parseUntilSpace(msg, pos)); // can be the nilvalue!
std::string hostName(parseUntilSpace(msg, pos));
std::string appName(parseUntilSpace(msg, pos));
std::string procId(parseUntilSpace(msg, pos));
std::string msgId(parseUntilSpace(msg, pos));
std::string message(msg.substr(pos));
pos = msg.size();
Poco::DateTime date;
int tzd = 0;
bool hasDate = Poco::DateTimeParser::tryParse(RemoteSyslogChannel::SYSLOG_TIMEFORMAT, timeStr, date, tzd);
Poco::Message logEntry(msgId, message, prio);
logEntry["host"] = hostName;
logEntry["app"] = appName;
if (hasDate)
logEntry.setTime(date.timestamp());
int lval(0);
Poco::NumberParser::tryParse(procId, lval);
logEntry.setPid(lval);
_pListener->log(logEntry);
}
void SyslogParser::parseBSD(const std::string& msg, RemoteSyslogChannel::Severity severity, RemoteSyslogChannel::Facility fac, std::size_t& pos)
{
Poco::Message::Priority prio = convert(severity);
// rest of the unparsed header is:
// "%b %f %H:%M:%S" SP hostname|ipaddress
// detect three spaces
int spaceCnt = 0;
std::size_t start = pos;
while (spaceCnt < 3 && pos < msg.size())
{
if (msg[pos] == ' ')
{
spaceCnt++;
if (spaceCnt == 1)
{
// size must be 3 chars for month
if (pos - start != 3)
{
// probably a shortened time value, or the hostname
// assume hostName
Poco::Message logEntry(msg.substr(start, pos-start), msg.substr(pos+1), prio);
_pListener->log(logEntry);
return;
}
}
else if (spaceCnt == 2)
{
// a day value!
if (!(std::isdigit(msg[pos-1]) && (std::isdigit(msg[pos-2]) || std::isspace(msg[pos-2]))))
{
// assume the next field is a hostname
spaceCnt = 3;
}
}
if (pos + 1 < msg.size() && msg[pos+1] == ' ')
{
// we have two spaces when the day value is smaller than 10!
++pos; // skip one
}
}
++pos;
}
std::string timeStr(msg.substr(start, pos-start-1));
int tzd(0);
Poco::DateTime date;
int year = date.year(); // year is not included, use the current one
bool hasDate = Poco::DateTimeParser::tryParse(RemoteSyslogChannel::BSD_TIMEFORMAT, timeStr, date, tzd);
if (hasDate)
{
int m = date.month();
int d = date.day();
int h = date.hour();
int min = date.minute();
int sec = date.second();
date = Poco::DateTime(year, m, d, h, min, sec);
}
// next entry is host SP
std::string hostName(parseUntilSpace(msg, pos));
// TAG: at most 32 alphanumeric chars, ANY non alphannumeric indicates start of message content
// ignore: treat everything as content
std::string message(msg.substr(pos));
pos = msg.size();
Poco::Message logEntry(hostName, message, prio);
logEntry.setTime(date.timestamp());
_pListener->log(logEntry);
}
std::string SyslogParser::parseUntilSpace(const std::string& msg, std::size_t& pos)
{
std::size_t start = pos;
while (pos < msg.size() && !std::isspace(msg[pos]))
++pos;
// skip space
++pos;
return msg.substr(start, pos-start-1);
}
Poco::Message::Priority SyslogParser::convert(RemoteSyslogChannel::Severity severity)
{
switch (severity)
{
case RemoteSyslogChannel::SYSLOG_EMERGENCY:
return Poco::Message::PRIO_FATAL;
case RemoteSyslogChannel::SYSLOG_ALERT:
return Poco::Message::PRIO_FATAL;
case RemoteSyslogChannel::SYSLOG_CRITICAL:
return Poco::Message::PRIO_CRITICAL;
case RemoteSyslogChannel::SYSLOG_ERROR:
return Poco::Message::PRIO_ERROR;
case RemoteSyslogChannel::SYSLOG_WARNING:
return Poco::Message::PRIO_WARNING;
case RemoteSyslogChannel::SYSLOG_NOTICE:
return Poco::Message::PRIO_NOTICE;
case RemoteSyslogChannel::SYSLOG_INFORMATIONAL:
return Poco::Message::PRIO_INFORMATION;
case RemoteSyslogChannel::SYSLOG_DEBUG:
return Poco::Message::PRIO_DEBUG;
}
throw Poco::LogicException("Illegal severity value in message");
}
//
// RemoteSyslogListener
//
const std::string RemoteSyslogListener::PROP_PORT("port");
RemoteSyslogListener::RemoteSyslogListener():
_pListener(0),
_pParser(0),
_listener(),
_parser(),
_queue(),
_port(RemoteSyslogChannel::SYSLOG_PORT)
{
}
RemoteSyslogListener::RemoteSyslogListener(Poco::UInt16 port):
_pListener(0),
_pParser(0),
_listener(),
_parser(),
_queue(),
_port(port)
{
}
RemoteSyslogListener::~RemoteSyslogListener()
{
}
void RemoteSyslogListener::setProperty(const std::string& name, const std::string& value)
{
if (name == PROP_PORT)
{
int val = Poco::NumberParser::parse(value);
if (val > 0 && val < 65536)
_port = static_cast<Poco::UInt16>(val);
else
throw Poco::InvalidArgumentException("Not a valid port number", value);
}
else
{
SplitterChannel::setProperty(name, value);
}
}
std::string RemoteSyslogListener::getProperty(const std::string& name) const
{
if (name == PROP_PORT)
return Poco::NumberFormatter::format(_port);
else
return SplitterChannel::getProperty(name);
}
void RemoteSyslogListener::open()
{
SplitterChannel::open();
_pParser = new SyslogParser(_queue, this);
_pListener = new RemoteUDPListener(_queue, _port);
_parser.start(*_pParser);
_listener.start(*_pListener);
}
void RemoteSyslogListener::close()
{
if (_pListener && _pParser)
{
_pListener->safeStop();
_pParser->safeStop();
_queue.clear();
_listener.join();
_parser.join();
delete _pListener;
delete _pParser;
_pListener = 0;
_pParser = 0;
}
SplitterChannel::close();
}
void RemoteSyslogListener::registerChannel()
{
Poco::LoggingFactory::defaultFactory().registerChannelClass("RemoteSyslogListener", new Poco::Instantiator<RemoteSyslogListener, Poco::Channel>);
}
} } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
//
// SocketImpl.cpp
//
// $Id: //poco/Main/Net/src/SocketImpl.cpp#17 $
// $Id: //poco/Main/Net/src/SocketImpl.cpp#19 $
//
// Library: Net
// Package: Sockets

View File

@@ -1,7 +1,7 @@
#
# Makefile
#
# $Id: //poco/Main/Net/testsuite/Makefile#20 $
# $Id: //poco/Main/Net/testsuite/Makefile#21 $
#
# Makefile for Poco Net testsuite
#
@@ -24,7 +24,8 @@ objects = \
SocketReactorTest ReactorTestSuite \
MailTestSuite MailMessageTest MailStreamTest \
SMTPClientSessionTest POP3ClientSessionTest \
RawSocketTest ICMPClientTest ICMPSocketTest ICMPClientTestSuite
RawSocketTest ICMPClientTest ICMPSocketTest ICMPClientTestSuite \
SyslogTest
target = testrunner
target_version = 1

View File

@@ -729,6 +729,24 @@
</File>
</Filter>
</Filter>
<Filter
Name="Logging"
Filter="">
<Filter
Name="Header Files"
Filter="">
<File
RelativePath=".\src\SyslogTest.h">
</File>
</Filter>
<Filter
Name="Source Files"
Filter="">
<File
RelativePath=".\src\SyslogTest.cpp">
</File>
</Filter>
</Filter>
</Files>
<Globals>
</Globals>

View File

@@ -956,6 +956,26 @@
</File>
</Filter>
</Filter>
<Filter
Name="Logging"
>
<Filter
Name="Header Files"
>
<File
RelativePath=".\src\SyslogTest.h"
>
</File>
</Filter>
<Filter
Name="Source Files"
>
<File
RelativePath=".\src\SyslogTest.cpp"
>
</File>
</Filter>
</Filter>
</Files>
<Globals>
</Globals>

View File

@@ -1,7 +1,7 @@
//
// HTTPServerTest.cpp
//
// $Id: //poco/Main/Net/testsuite/src/HTTPServerTest.cpp#11 $
// $Id: //poco/Main/Net/testsuite/src/HTTPServerTest.cpp#13 $
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
@@ -35,7 +35,7 @@
#include "CppUnit/TestSuite.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/AbstractHTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
@@ -50,6 +50,7 @@
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerParams;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::AbstractHTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
@@ -96,12 +97,12 @@ namespace
}
};
class RedirectRequestHandler: public HTTPRequestHandler
class RedirectRequestHandler: public AbstractHTTPRequestHandler
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
void run()
{
response.redirect("http://www.appinf.com/");
response().redirect("http://www.appinf.com/");
}
};
@@ -398,6 +399,52 @@ void HTTPServerTest::testMaxKeepAlive()
}
void HTTPServerTest::testKeepAliveTimeout()
{
ServerSocket svs(0);
HTTPServerParams* pParams = new HTTPServerParams;
pParams->setKeepAlive(true);
pParams->setMaxKeepAliveRequests(4);
pParams->setKeepAliveTimeout(Poco::Timespan(3, 0));
HTTPServer srv(new RequestHandlerFactory, svs, pParams);
srv.start();
HTTPClientSession cs("localhost", svs.address().port());
cs.setKeepAlive(true);
cs.setKeepAliveTimeout(Poco::Timespan(2, 0));
HTTPRequest request("POST", "/echoBody", HTTPMessage::HTTP_1_1);
request.setContentType("text/plain");
request.setChunkedTransferEncoding(true);
std::string body(5000, 'x');
for (int i = 0; i < 3; ++i)
{
cs.sendRequest(request) << body;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
assert (response.getContentType() == "text/plain");
assert (response.getChunkedTransferEncoding());
assert (response.getKeepAlive());
assert (rbody == body);
}
Poco::Thread::sleep(4000);
{
cs.sendRequest(request) << body;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
assert (response.getContentType() == "text/plain");
assert (response.getChunkedTransferEncoding());
assert (response.getKeepAlive());
assert (rbody == body);
}
}
void HTTPServerTest::test100Continue()
{
ServerSocket svs(0);
@@ -522,6 +569,7 @@ CppUnit::Test* HTTPServerTest::suite()
CppUnit_addTest(pSuite, HTTPServerTest, testChunkedRequestKeepAlive);
CppUnit_addTest(pSuite, HTTPServerTest, testClosedRequestKeepAlive);
CppUnit_addTest(pSuite, HTTPServerTest, testMaxKeepAlive);
CppUnit_addTest(pSuite, HTTPServerTest, testKeepAliveTimeout);
CppUnit_addTest(pSuite, HTTPServerTest, test100Continue);
CppUnit_addTest(pSuite, HTTPServerTest, testRedirect);
CppUnit_addTest(pSuite, HTTPServerTest, testAuth);

View File

@@ -1,7 +1,7 @@
//
// HTTPServerTest.h
//
// $Id: //poco/Main/Net/testsuite/src/HTTPServerTest.h#8 $
// $Id: //poco/Main/Net/testsuite/src/HTTPServerTest.h#9 $
//
// Definition of the HTTPServerTest class.
//
@@ -54,6 +54,7 @@ public:
void testChunkedRequestKeepAlive();
void testClosedRequestKeepAlive();
void testMaxKeepAlive();
void testKeepAliveTimeout();
void test100Continue();
void testRedirect();
void testAuth();

View File

@@ -1,7 +1,7 @@
//
// NetTestSuite.cpp
//
// $Id: //poco/Main/Net/testsuite/src/NetTestSuite.cpp#14 $
// $Id: //poco/Main/Net/testsuite/src/NetTestSuite.cpp#15 $
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
@@ -43,6 +43,7 @@
#include "FTPClientTestSuite.h"
#include "MailTestSuite.h"
#include "ICMPClientTestSuite.h"
#include "SyslogTest.h"
CppUnit::Test* NetTestSuite::suite()
@@ -61,6 +62,7 @@ CppUnit::Test* NetTestSuite::suite()
pSuite->addTest(FTPClientTestSuite::suite());
pSuite->addTest(MailTestSuite::suite());
pSuite->addTest(ICMPClientTestSuite::suite());
pSuite->addTest(SyslogTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,215 @@
//
// SyslogTest.cpp
//
// $Id: //poco/Main/Net/testsuite/src/SyslogTest.cpp#2 $
//
// 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 "SyslogTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Net/RemoteSyslogChannel.h"
#include "Poco/Net/RemoteSyslogListener.h"
#include "Poco/Net/DNS.h"
#include "Poco/Thread.h"
#include "Poco/Message.h"
#include "Poco/AutoPtr.h"
#include <list>
using namespace Poco::Net;
class CachingChannel: public Poco::Channel
/// Caches the last n Messages in memory
{
public:
typedef std::list<Poco::Message> Messages;
CachingChannel(std::size_t n = 100);
/// Creates the CachingChannel. Caches n messages in memory
~CachingChannel();
/// Destroys the CachingChannel.
void log(const Poco::Message& msg);
/// Writes the log message to the cache
void getMessages(std::vector<Poco::Message>& msg, int offset, int numEntries) const;
/// Retrieves numEntries Messages starting with position offset. Most recent messages are first.
std::size_t getMaxSize() const;
std::size_t getCurrentSize() const;
private:
CachingChannel(const CachingChannel&);
Messages _cache;
std::size_t _size;
std::size_t _maxSize;
mutable Poco::FastMutex _mutex;
};
std::size_t CachingChannel::getMaxSize() const
{
return _maxSize;
}
std::size_t CachingChannel::getCurrentSize() const
{
return _size;
}
CachingChannel::CachingChannel(std::size_t n):
_cache(),
_size(0),
_maxSize(n),
_mutex()
{
}
CachingChannel::~CachingChannel()
{
}
void CachingChannel::log(const Poco::Message& msg)
{
Poco::FastMutex::ScopedLock lock(_mutex);
_cache.push_front(msg);
if (_size == _maxSize)
{
_cache.pop_back();
}
else
++_size;
}
void CachingChannel::getMessages(std::vector<Poco::Message>& msg, int offset, int numEntries) const
{
msg.clear();
Messages::const_iterator it = _cache.begin();
while (offset > 0 && it != _cache.end())
++it;
while (numEntries > 0 && it != _cache.end())
{
msg.push_back(*it);
++it;
}
}
SyslogTest::SyslogTest(const std::string& name): CppUnit::TestCase(name)
{
}
SyslogTest::~SyslogTest()
{
}
void SyslogTest::testListener()
{
Poco::AutoPtr<RemoteSyslogChannel> channel = new RemoteSyslogChannel();
channel->setProperty("loghost", "localhost:51400");
channel->open();
Poco::AutoPtr<RemoteSyslogListener> listener = new RemoteSyslogListener(51400);
listener->open();
CachingChannel cl;
listener->addChannel(&cl);
poco_assert (cl.getCurrentSize() == 0);
Poco::Message msg("asource", "amessage", Poco::Message::PRIO_CRITICAL);
channel->log(msg);
Poco::Thread::sleep(1000);
listener->close();
channel->close();
poco_assert (cl.getCurrentSize() == 1);
std::vector<Poco::Message> msgs;
cl.getMessages(msgs, 0, 10);
poco_assert (msgs.size() == 1);
poco_assert (msgs[0].getSource() == "asource");
poco_assert (msgs[0].getText() == "amessage");
poco_assert (msgs[0].getPriority() == Poco::Message::PRIO_CRITICAL);
}
void SyslogTest::testOldBSD()
{
Poco::AutoPtr<RemoteSyslogChannel> channel = new RemoteSyslogChannel();
channel->setProperty("loghost", "localhost:51400");
channel->setProperty("format", "bsd");
channel->open();
Poco::AutoPtr<RemoteSyslogListener> listener = new RemoteSyslogListener(51400);
listener->open();
CachingChannel cl;
listener->addChannel(&cl);
poco_assert (cl.getCurrentSize() == 0);
Poco::Message msg("asource", "amessage", Poco::Message::PRIO_CRITICAL);
channel->log(msg);
Poco::Thread::sleep(1000);
listener->close();
channel->close();
poco_assert (cl.getCurrentSize() == 1);
std::vector<Poco::Message> msgs;
cl.getMessages(msgs, 0, 10);
poco_assert (msgs.size() == 1);
// the source is lost with old BSD messages: we only send the local host name!
poco_assert (msgs[0].getSource() == Poco::Net::DNS::thisHost().name());
poco_assert (msgs[0].getText() == "amessage");
poco_assert (msgs[0].getPriority() == Poco::Message::PRIO_CRITICAL);
}
void SyslogTest::setUp()
{
}
void SyslogTest::tearDown()
{
}
CppUnit::Test* SyslogTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SyslogTest");
CppUnit_addTest(pSuite, SyslogTest, testListener);
CppUnit_addTest(pSuite, SyslogTest, testOldBSD);
return pSuite;
}

View File

@@ -0,0 +1,61 @@
//
// SyslogTest.h
//
// $Id: //poco/Main/Net/testsuite/src/SyslogTest.h#1 $
//
// Definition of the SyslogTest class.
//
// 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.
//
#ifndef SyslogTest_INCLUDED
#define SyslogTest_INCLUDED
#include "Poco/Net/Net.h"
#include "CppUnit/TestCase.h"
class SyslogTest: public CppUnit::TestCase
{
public:
SyslogTest(const std::string& name);
~SyslogTest();
void testListener();
void testOldBSD();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // SyslogTest_INCLUDED